Gridview_RowEditing empty values - vb.net

I have a gridview control that i am manually binding the data in. When i edit a row and update it the values of the text boxes that are sent are always the Old Values. I've found a few threads on this but have not had any luck extracting the new values.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Private Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim gv As GridView = sender
For i As Integer = 0 To gv.Columns.Count Step 1
Dim cell As DataControlFieldCell = gv.Rows(e.RowIndex).Cells(i)
gv.Columns(0).ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, True)
Next
For Each s As DictionaryEntry In e.NewValues
Debug.Print(s.Key & " | " & s.Value)
Next
ds.Tables("testTable").Rows(e.RowIndex).BeginEdit()
[ ... ]
ds.Tables("testTable").Rows(e.RowIndex).EndEdit()
GridView1.EditIndex = -1
BindData()
End Sub
I also want to point out that the ExtractValuesFromCell code is just my most recent attempt to get the New Data. Prior to that i was using something like this
Dim tb as TextBox = sender.Rows(e.RowIndex).Cells(1).Controls(0)
Label1.Text = tb.Text
Also here is how the data looks to start
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (ds.Tables.Count = 0) Then
ds.Tables.Add("testTable")
ds.Tables("testTable").Columns.Add("Driver Name")
ds.Tables("testTable").Columns.Add("Total")
ds.Tables("testTable").Columns.Add("# Of Calls")
ds.Tables("testTable").Columns("Total").ReadOnly = True
ds.Tables("testTable").Columns("# Of Calls").ReadOnly = True
Dim newRow As DataRow = ds.Tables("testTable").NewRow()
newRow("Driver Name") = ""
newRow("Total") = ""
newRow("# Of Calls") = ""
ds.Tables("testTable").Rows.Add(newRow)
End If
BindData()
End Sub

You should DataBind your GridView only if Not Page.IsPostback, otherwise the new values are overwritten.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowupdating.aspx

public static void filedownload(string Path)
{
string str = "";
FileInfo file = new FileInfo(Path);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
HttpContext.Current.Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
HttpContext.Current.Response.ContentType = CommonStrings.returnextension(file.Extension.ToLower());
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.WriteFile(file.FullName);
// End the response
HttpContext.Current.Response.End();
}
else
{
// 9-vgrfu8i "File Not Found!";
}
// Response.Redirect(e.CommandArgument.ToString());
}
public static string GetBarCodeid(ListBox lbListBox)
{
string strCode = "";
if (lbListBox.Items.Count > 0)
{
for (int i = 0; i < lbListBox.Items.Count; i++)
{
if (lbListBox.Items[i].Selected == true)
{
if (strCode == "")
{
strCode = lbListBox.Items[i].Value.ToString();
}
else
{
strCode += "," + lbListBox.Items[i].Value.ToString();
}
}
}
}
return strCode;
}
public static string GetBarCodeName(ListBox lbListBox)
{
string strBarCodeName = "";
if (lbListBox.Items.Count > 0)
{
for (int i = 0; i < lbListBox.Items.Count; i++)
{
if (lbListBox.Items[i].Selected == true)
{
if (strBarCodeName == "")
{
strBarCodeName = lbListBox.Items[i].Text.ToString();
}
else
{
strBarCodeName += "," + lbListBox.Items[i].Text.ToString();
}
}
}
}
return strBarCodeName;
}
public static double GetBarCodeCount(ListBox lbListBox, double Count)
{
double intBarCodeCount = 0;
if (lbListBox.Items.Count > 0)
{
for (int i = 0; i < lbListBox.Items.Count; i++)
{
if (lbListBox.Items[i].Selected == true)
{
if (intBarCodeCount == 0)
{
intBarCodeCount = 1;
}
else
{
intBarCodeCount++;
}
}
}
}
return intBarCodeCount;
}
public static void SelectListBox(ListBox lbListBox, string strBarCodeId)
{
ExecuteProcedures ex = new ExecuteProcedures(1, MasterCommonStrings.ConnectionString);
ex.Parameters.Add("#vcrBarCodeid", SqlDbType.VarChar, 500, strBarCodeId);
DataTable dt = (DataTable)ex.LoadTableWithProcedure("Proc_Erp_Trn_Get_BarCode_Bata");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < lbListBox.Items.Count; j++)
{
if (dt.Rows[i]["data"].ToString() == lbListBox.Items[j].Value.ToString())
{
lbListBox.Items[j].Selected = true;
break;
}
}
}
}
}
public static string GetgridBarCode(DataTable dt, string strColumnName)
{
string strBarCodeCount = "";
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (Convert.ToInt32(dt.Rows[i]["intStatus"]) != 2)
{
if (dt.Rows[i][strColumnName].ToString() != "")
if (strBarCodeCount == "")
{
strBarCodeCount = dt.Rows[i][strColumnName].ToString();
}
else
{
strBarCodeCount += dt.Rows[i][strColumnName].ToString();
}
}
}
}
return strBarCodeCount;
}
public static DataTable CheckBarCodeExistsOrNot(ListBox lbListbox, string strColumeName, string strReplacegridBarCodeid, DataView dvDescription)
{
DataTable dtDescription = new DataTable();
dtDescription = (DataTable)dvDescription.Table;
string strgridBarCode = CommonFunctions.GetgridBarCode(dtDescription, strColumeName);
string strSelectBarCode = CommonFunctions.GetBarCodeid(lbListbox);
ExecuteProcedures ex = new ExecuteProcedures(3, MasterCommonStrings.ConnectionString);
ex.Parameters.Add("#vcrgridBarcodeid", SqlDbType.VarChar, 500, strgridBarCode);
ex.Parameters.Add("#vcrSelectBarcodeid", SqlDbType.VarChar, 500, strSelectBarCode);
ex.Parameters.Add("#vcrReplaceBarCodeid", SqlDbType.VarChar, 500, strReplacegridBarCodeid);
DataTable dt = (DataTable)ex.LoadTableWithProcedure("Proc_Erp_Trn_Check_BarCode_Exists_Or_Not");
return dt;
}
public static int BarcodeUpdateIntoBarCodeDrec(string strBarCode_Description_Drec_id, SqlTransaction sqlTran, SqlConnection Con)
{
ExecuteProcedures ex = new ExecuteProcedures(1, MasterCommonStrings.ConnectionString);
ex.Parameters.Add("#intBarCode_Description_Drec_id", SqlDbType.VarChar, 8000, strBarCode_Description_Drec_id);
int i = Convert.ToInt32(ex.InvokeProcedure("Proc_Erp_Trn_Update_erp_mst_BarCode_Drec", sqlTran, ValueDataType.Number, Con));
if (i != 0)
{
return i;
}
else
{
return 0;
}
}
public static string AddBarcodeToListBox(TextBox txtScanBarcode, ListBox lbScanBarCode, ListBox lbSystemBarCode)
{
string barcodePresent = "";
if (txtScanBarcode.Text != "")
{
foreach (ListItem li in lbSystemBarCode.Items)
{
if (li.Text != txtScanBarcode.Text)
{
barcodePresent = "Not In Our System";
}
else
{
if (li.Selected == true)
{
barcodePresent = "Barcode Already Scan";
txtScanBarcode.Text = "";
txtScanBarcode.Focus();
break;
}
else
{
lbScanBarCode.Items.Add(txtScanBarcode.Text);
li.Selected = true;
txtScanBarcode.Text = "";
txtScanBarcode.Focus();
barcodePresent = "Barcode Scan Successfully";
break;
}
}
}
if (barcodePresent == "Not In Our System")
{
txtScanBarcode.Text = "";
txtScanBarcode.Focus();
}
}
else
{
barcodePresent = "Please Scan Barcode";
}
return barcodePresent;
}
public static void RemoveBarCodeFromListBox(ListBox lbScanBarCode, ListBox lbSystemBarCode)
{
if (lbScanBarCode.Items.Count > 0)
{
for (int i = 0; i < lbScanBarCode.Items.Count; i++)
{
if (lbScanBarCode.Items[i].Selected)
{
foreach (ListItem li1 in lbSystemBarCode.Items)
{
if (lbScanBarCode.Items[i].Text == li1.Text)
{
li1.Selected = false;
break;
}
}
lbScanBarCode.Items.Remove(lbScanBarCode.Items[i]);
}
}
}
}
public static void AddBarcodeToGridListBox(ListBox lbBarCode, ListBox lbGridScanBarCodeDisplay)
{
if (lbBarCode.Items.Count > 0)
{
for (int i = 0; i < lbBarCode.Items.Count; i++)
{
if (lbBarCode.Items[i].Selected == true)
{
lbGridScanBarCodeDisplay.Items.Add(lbBarCode.Items[i].Text);
}
}
}
}
public static void Alert(string strMessage, System.Web.UI.Page PAGE)
{
HttpContext Current = HttpContext.Current;
string strScript = "<script type=text/javascript>alert('" + strMessage + "')</script>";
if (!PAGE.IsStartupScriptRegistered("Alert"))
{
PAGE.RegisterStartupScript("Alert", strScript);
}
}
public static int DeletedTotalDrec(DataView dv, string strTableName, string strColumnName, string Value, SqlTransaction SqlTra, SqlConnection Con)
{
DataTable dtDrec = new DataTable();
dtDrec = (DataTable)dv.Table;
int i = 0;
if (dtDrec.Rows.Count > 0)
{
ExecuteProcedures one = new ExecuteProcedures(3, MasterCommonStrings.ConnectionString);
one.Parameters.Add("#TableName", SqlDbType.VarChar, 8000, strTableName);
one.Parameters.Add("#ColumnName", SqlDbType.VarChar, 8000, strColumnName);
one.Parameters.Add("#ColumnValue", SqlDbType.VarChar, 8000, Value);
int b = Convert.ToInt32(one.InvokeProcedure("Proc_Erp_Trn_Deleted_Transction_Total_Drec", SqlTra, ValueDataType.Number, Con));
for (int j = 0; j < dtDrec.Rows.Count; j++)
{
ExecuteProcedures EX = new ExecuteProcedures(19, MasterCommonStrings.ConnectionString);
EX.Parameters.Add("#TableName", SqlDbType.VarChar, 8000, strTableName);
EX.Parameters.Add("#FirstColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[0].ColumnName.ToString());
EX.Parameters.Add("#SecondColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[1].ColumnName.ToString());
EX.Parameters.Add("#ThiredColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[2].ColumnName.ToString());
EX.Parameters.Add("#FourColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[3].ColumnName.ToString());
EX.Parameters.Add("#FiveColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[4].ColumnName.ToString());
EX.Parameters.Add("#SixtColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[5].ColumnName.ToString());
EX.Parameters.Add("#SevenColumnName", SqlDbType.VarChar, 8000, dtDrec.Columns[6].ColumnName.ToString());
EX.Parameters.Add("#EightColumnName ", SqlDbType.VarChar, 8000, dtDrec.Columns[7].ColumnName.ToString());
EX.Parameters.Add("#NineColumnName", SqlDbType.VarChar, 8000, strColumnName);
EX.Parameters.Add("#FirstColumnNameValue ", SqlDbType.VarChar, 8000, dtDrec.Rows[j][0].ToString());
EX.Parameters.Add("#SecondColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][1].ToString());
EX.Parameters.Add("#ThiredColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][2].ToString());
EX.Parameters.Add("#FourColumnNameValue ", SqlDbType.VarChar, 8000, dtDrec.Rows[j][3].ToString());
EX.Parameters.Add("#FiveColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][4].ToString());
EX.Parameters.Add("#SixtColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][5].ToString());
EX.Parameters.Add("#SevenColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][6].ToString());
EX.Parameters.Add("#EightColumnNameValue", SqlDbType.VarChar, 8000, dtDrec.Rows[j][7].ToString());
EX.Parameters.Add("#NineColumnNameValue ", SqlDbType.VarChar, 8000, Value);
i = Convert.ToInt32(EX.InvokeProcedure("proc_erp_Trn_Insert_into_Total_Drec", SqlTra, ValueDataType.Number, Con));
}
}
return i;
}
public static bool CheckRows(Manage_Drec Description)
{
if (Description.InTable.Rows.Count > 0)
{
return true;
}else
{
return false;
}
}
#endregion
# region "Procedures"
public static void SetRadiobutton(string strStatus, RadioButton Rbyes, RadioButton rbNo)
{
if (strStatus == "Yes")
{
Rbyes.Checked = true;
}
else
{
Rbyes.Checked = false;
}
if (strStatus == "No")
{
rbNo.Checked = true;
}
else
{
rbNo.Checked = false;
}
}
public static void Set_CheckBox(bool Status, CheckBox ChkName)
{
if (Status == true)
{
ChkName.Checked = true;
}
else
{
ChkName.Checked = false;
}
}
public static void DoSomeFileWritingStuff(string message)
{
//Debug.WriteLine("Writing to file...");
try
{
using (StreamWriter writer = new StreamWriter(LOG_FILE, true))
{
if (message == "")
{
writer.WriteLine("Cache Callback: {0}", DateTime.Now);
}
else
{
writer.WriteLine(message);
}
writer.Close();
}
AspSendEmail smail = new AspSendEmail();
//smail.strHost = mail.intrawebsolns.com
smail.SendEmail("support#intrawebsolns.com", "amit4692#gmail.com", "Exception Error", message, "Error ERP");
}
catch (Exception x)
{
//Debug.WriteLine(x);
DoSomeFileWritingStuff(x.Message);
}
//Debug.WriteLine("File write successful");
}
public static void SetRights(string Rights, Panel pnl)
{
foreach (Control ctrl in pnl.Controls)
{
if (ctrl.GetType().Name == "Button")
{
if ((((Button)ctrl).ID == "btnAdd" && Rights.IndexOf("A") > -1) || (((Button)ctrl).ID == "btnEdit" && Rights.IndexOf("E") > -1)
|| (((Button)ctrl).ID == "btnDelete" && Rights.IndexOf("D") > -1))
{
ctrl.Visible = true;
}
if ((((Button)ctrl).ID == "btnAdd" && Rights.IndexOf("S") > -1) || (((Button)ctrl).ID == "btnEdit" && Rights.IndexOf("S") > -1)
|| (((Button)ctrl).ID == "btnDelete" && Rights.IndexOf("S") > -1))
{
ctrl.Visible = true;
}
}
}
}
#endregion
public static void Enable_Btn_For_Add(Button btnAdd, Button btnCancel, Button btnDelete, Button btnEdit, Button btnUpdate, Button btnexit, Button btnfind)
{
btnEdit.Enabled = false;
btnAdd.Enabled = false;
btnfind.Enabled = false;
btnUpdate.Enabled = true;
btnCancel.Enabled = true;
btnDelete.Enabled = false;
btnexit.Enabled = true;
}
public static bool Check_Entry_exists(string tableName, string columnName, string columnValue)
{
bool result=false;
try
{
ExecuteProcedures ex = new ExecuteProcedures(4, AccountCommonStrings.ConnectionString);
ex.Parameters.Add("#tableName", SqlDbType.VarChar, 100, tableName);
ex.Parameters.Add("#columnName", SqlDbType.VarChar, 100, columnName);
ex.Parameters.Add("#columnValue", SqlDbType.VarChar, 100, #columnValue);
ex.Parameters.Add("#isbitdeleted", SqlDbType.Int, 0);
string temp =Convert.ToString( ex.InvokeProcedure("proc_check_Delete_entry", ValueDataType.String));
if (temp == "false")
{
result = false;
}
else
{
result = true;
}
}
catch (Exception)
{
}
return result;
}
public static bool Check_Entry_exists(string tableName, string columnName, string columnValue,string isbitdeleted)
{
bool result = false;
try
{
ExecuteProcedures ex = new ExecuteProcedures(4, AccountCommonStrings.ConnectionString);
ex.Parameters.Add("#tableName", SqlDbType.VarChar, 100, tableName);
ex.Parameters.Add("#columnName", SqlDbType.VarChar, 100, columnName);
ex.Parameters.Add("#columnValue", SqlDbType.VarChar, 100, #columnValue);
ex.Parameters.Add("#isbitdeleted", SqlDbType.Int, isbitdeleted);
string temp = Convert.ToString(ex.InvokeProcedure("proc_check_Delete_entry", ValueDataType.String));
if (temp == "false")
{
result = false;
}
else
{
result = true;
}
}
catch (Exception)
{
}
return result;
}
}

Related

Android MPAndroidChart xAxis.setValueFormatter throws ArrayIndexOutOfBoundsException

Good morning,
I'm struggling with ArrayIndexOutOfBoundsException thrown when i'm inserting the row
xAxis.setValueFormatter(formatter) (commented in code).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bc = findViewById(R.id.chart);
CaricaStorico cs = new CaricaStorico();
try {
cs.execute().get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List<BarEntry> turno1 = new ArrayList<>();
List<BarEntry> turno2 = new ArrayList<>();
List<BarEntry> turno3 = new ArrayList<>();
String[] date = new String[100];
boolean datiturno1 = false;
boolean datiturno2 = false;
boolean datiturno3 = false;
for (int i = 0; i < storicoMacchina.size(); i++) {
Storico st = storicoMacchina.get(i);
System.out.println(st.getData() + " - " + st.getProduzione1() + " - " + st.getProduzione2() + " - " + st.getProduzione3());
turno1.add(new BarEntry(i, st.getProduzione1()));
turno2.add(new BarEntry(i, st.getProduzione2()));
turno3.add(new BarEntry(i, st.getProduzione3()));
if (st.getProduzione1() != 0) {
datiturno1 = true;
}
if (st.getProduzione2() != 0) {
datiturno2 = true;
}
if (st.getProduzione3() != 0) {
datiturno3 = true;
}
Calendar c = Calendar.getInstance();
c.setTime(st.getData());
String dataMese = c.get(Calendar.DAY_OF_MONTH) + "/" + (c.get(Calendar.MONTH) + 1);
xLabels.add(dataMese);
}
ValueFormatter formatter = new ValueFormatter() {
#Override
public String getAxisLabel(float value, AxisBase axis) {
return xLabels.get((int) value);
}
};
BarDataSet set1 = null;
BarDataSet set2 = null;
BarDataSet set3 = null;
set1 = new BarDataSet(turno1, "Turno 1");
set2 = new BarDataSet(turno2, "Turno 2");
set3 = new BarDataSet(turno3, "Turno 3");
System.out.println(datiturno1 + "," + datiturno2 + "," + datiturno3);
float groupSpace = 0.04f;
float barSpace = 0.02f;
float barWidth = 0.3f;
// set1.setColors(new int[] { R.color.red, R.color.red1, R.color.red2, R.color.red3 },MainActivity.this);
set1.setColor(getResources().getColor(R.color.turno1));
set2.setColor(getResources().getColor(R.color.turno2));
set3.setColor(getResources().getColor(R.color.turno3));
BarData barData;
if (datiturno3 == false) {
barData = new BarData(set1, set2);
groupSpace = 0.06f;
barSpace = 0.02f;
barWidth = 0.45f;
} else {
barData = new BarData(set1, set2, set3);
}
barData.setBarWidth(barWidth);
bc.setData(barData);
Description desc = new Description();
desc.setText("Produzione ultima settimana");
bc.setDescription(desc);
bc.groupBars(0, groupSpace, barSpace);
XAxis xAxis = bc.getXAxis();
xAxis.setCenterAxisLabels(true);
xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1);
xAxis.setAxisMaximum(storicoMacchina.size());
// xAxis.setValueFormatter(formatter);
bc.invalidate();
}
without this line code is working fine except for the labels in xAxis that i'm trying to set with this line.
Anyone can help me to find what i'm doing wrong?
Thank you for your help
your text
I'have found workaround to solve my problem changing the code above with this
If anyone can explain me the reason value index differs from my xlabel, dataset size will be appreciated.
Thanks again
public String getAxisLabel(float value, AxisBase axis) {
String label = "";
if ((value >= 0) && (value <= xLabels.size() -1)) {
label = xLabels.get((int) value);
}
return label;
}

i am getting an error in eclipse - An error occurred while instantiating class : 'void org.apache.xmlbeans.XmlOptions.put(java.lang.Object)'

Here is my code i am using
package testCases;
import org.openqa.selenium.By;
import org.testng.Reporter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.apache.commons.collections4.*;
import base.TestBase;
public class StudentRegistrationForm extends TestBase {
#Test(dataProvider="getData")
public void addStudent(String fname, String email, String CurrentAddress,String PermAddress) {
driver.get(confg.getProperty("url2"));
log.debug("Navigated to : " + confg.getProperty("url2"));
driver.findElement(By.cssSelector(or.getProperty("fullname"))).sendKeys(fname);
driver.findElement(By.cssSelector(or.getProperty("email"))).sendKeys(email);
driver.findElement(By.cssSelector(or.getProperty("currentAddress"))).sendKeys(CurrentAddress);
driver.findElement(By.cssSelector(or.getProperty("permAddress"))).sendKeys(PermAddress);
driver.findElement(By.cssSelector(or.getProperty("submit"))).click();
log.debug("Completed Test 2 - Student Registration Form");
Reporter.log("Completed Test 2 - Student Registration Form");
}
#DataProvider
public Object[][] getData(){
String SheetName = "sheet1";
int rows = excel.getRowCount(SheetName);
int cols = excel.getColumnCount(SheetName);
Object[][] data = new Object[rows-1][cols];
for(int RowNum = 2; RowNum < rows; RowNum++) {
for(int colNum = 0; colNum < cols; colNum++) {
data[RowNum-2][colNum] = excel.getCellData(SheetName, colNum, RowNum);
}
}
return data;
}
}
Also here is the excel reader. I don't know why I am getting an error attached in the picture:
package utilities;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.commons.collections4.list.*;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public String path;
public FileInputStream fis =null;
public FileOutputStream fileOut = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row = null;
private XSSFCell cell = null;
public ExcelReader(String Path) {
this.path = Path;
try {
fis = new FileInputStream(Path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getRowCount(String Sheetname) {
int sheetIndex = workbook.getSheetIndex(Sheetname);
if(sheetIndex ==-1)
return 0;
else {
sheet = workbook.getSheetAt(0);
int num = sheet.getLastRowNum();
return num;
}
}
public String getCellData(String sheetname, String colName, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetname);
int col_num = -1;
if(index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for(int i =0;i < row.getLastCellNum(); i++) {
System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_num = i;
}
if(col_num == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row == null)
return "";
cell = row.getCell(col_num);
if(cell==null)
return "";
if(cell.getCellType()==CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC || cell.getCellType()==CellType.FORMULA ){
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
double d = cell.getNumericCellValue();
Calendar cal =Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
cal.get(Calendar.MONTH)+1 + "/" +
cellText;
}
return cellText;
}else if(cell.getCellType()==CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}catch(Exception e) {
e.printStackTrace();
return "row "+rowNum+" or column "+colName +" does not exist in xls";
}
}
// returns the data from a cell
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <=0)
return "";
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";
if(cell.getCellType()==CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC || cell.getCellType()==CellType.FORMULA ){
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal =Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText =
(String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH)+1 + "/" +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
cellText;
}
return cellText;
}else if(cell.getCellType()==CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e){
e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist in xls";
}
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if(rowNum<=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;
sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if(rowNum<=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;
sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}
if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
//cell style for hyperlinks
CellStyle hlink_style = workbook.createCellStyle();
XSSFFont hlink_font = workbook.createFont();
hlink_font.setUnderline(XSSFFont.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
//hlink_style.setWrapText(true);
XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.FILE);
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is created successfully else false
public boolean addSheet(String sheetname){
FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is removed successfully else false if sheet does not exist
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;
FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName,String colName){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
sheet=workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
if(row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
cell.setCellValue(colName);
cell.setCellStyle(style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_40_PERCENT.getIndex());
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(FillPatternType.NO_FILL);
for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
// find whether sheets exists
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
}
// returns number of columns in a sheet
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if(row==null)
return -1;
return row.getLastCellNum();
}
//String sheetName, String testCaseName,String keyword ,String URL,String message
public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
url=url.replace('\\', '/');
if(!isSheetExist(sheetName))
return false;
sheet = workbook.getSheet(sheetName);
for(int i=2;i<=getRowCount(sheetName);i++){
if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
setCellData(sheetName, screenShotColName, i+index, message,url);
break;
}
}
return true;
}
public int getCellRowNum(String sheetName,String colName,String cellValue){
for(int i=2;i<=getRowCount(sheetName);i++){
if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
return i;
}
}
return -1;
}
// to run this on stand alone
public static void main(String arg[]) throws IOException{
ExcelReader datatable = null;
datatable = new ExcelReader("C:\\CM3.0\\app\\test\\Framework\\AutomationBvt\\src\\config\\xlfiles\\Controller.xlsx");
for(int col=0 ;col< datatable.getColumnCount("TC5"); col++){
System.out.println(datatable.getCellData("TC5", col, 1));
}
}
}
I dont know why this error occurs. I have added all the required dependencies. the excel reader is from a separe course and that doesn't show any error. only my code - which uses this class, is showing this error.

Want to use same data provider but different excel path for different functions to provide data in selenium

Want to use same DataProvider to provide data to multiple methods. Have created utility using Apache POI to read excel File and parameterized it and using data provider im sending data to the application.
Data Provider provides the data to one of the methods but using same data provider I want to provide data to another method but with different excel path. In short, parameterized the path. How to do it?
public Object [][] logindetails() {
configexcel datas= new configexcel("C:\\Users\\xyz.xlsx"); //configexcel class
int rows= datas.rowsncol(0);
int col= datas.column(0);
Object [][] data= new Object[rows-1][col];
for(int i=1;i<rows;i++) {
for (int j=0;j<col;j++) {
data[i-1][j]= datas.readdata(0,i,j);
}
return data;
}
--configexcel datas= new configexcel("C:\\Users\\xyz.xlsx"); //want to parameterize this.
//Constructor
package excelconfig;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class configexcel {
XSSFWorkbook loadwb;
XSSFSheet sheet;
public configexcel(String excelpath) {
try {
File src=new File(excelpath);
FileInputStream file= new FileInputStream(src);
loadwb= new XSSFWorkbook(file);
} catch (Exception e) {
System.out.print("The error is"+e.getMessage());
}
}
public String readdata(int sheets,int row,int col) {
sheet=loadwb.getSheetAt(sheets);
String inputs=sheet.getRow(row).getCell(col).getStringCellValue();
return inputs;
}
public int rowsncol(int rows) {
int count=loadwb.getSheetAt(rows).getLastRowNum();
count=count+1;
return count;
}
public int column(int col) {
sheet= loadwb.getSheetAt(0);
int counts= sheet.getRow(col).getLastCellNum();
// counts=counts+1;
return counts;
}```
}
Use excel reader in selenium and store data fields in your code and do parameterization
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public String path;
public FileInputStream fis = null;
public FileOutputStream fileOut = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row = null;
private XSSFCell cell = null;
public ExcelReader(String path) {
this.path = path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// returns the row count in a sheet
public int getRowCount(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return 0;
else {
sheet = workbook.getSheetAt(index);
int number = sheet.getLastRowNum() + 1;
return number;
}
}
// returns the data from a cell
public String getCellData(String sheetName, String colName, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
int col_Num = -1;
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num = i;
}
if (col_Num == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum - 1);
if (row == null)
return "";
cell = row.getCell(col_Num);
if (cell == null)
return "";
//System.out.println(cell.getCellType().name());
//
if (cell.getCellType().name().equals("STRING"))
return cell.getStringCellValue();
// if (cell.getCellType().STRING != null)
// if(cell.getCellType()==Xls_Reader.CELL_TYPE_STRING)
// return cell.getStringCellValue();
else if ((cell.getCellType().name().equals("NUMERIC")) || (cell.getCellType().name().equals("FORMULA"))) {
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal = Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType().BLANK != null)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
} catch (Exception e) {
e.printStackTrace();
return "row " + rowNum + " or column " + colName + " does not exist in xls";
}
}
// returns the data from a cell
public String getCellData(String sheetName, int colNum, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum - 1);
if (row == null)
return "";
cell = row.getCell(colNum);
if (cell == null)
return "";
//
if (cell.getCellType().name().equals("STRING"))
return cell.getStringCellValue();
//
// if (cell.getCellType().STRING != null)
// return cell.getStringCellValue();
else if ((cell.getCellType().name().equals("NUMERIC")) || (cell.getCellType().name().equals("FORMULA"))) {
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal = Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType().BLANK != null)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
} catch (Exception e) {
e.printStackTrace();
return "row " + rowNum + " or column " + colNum + " does not exist in xls";
}
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName, String colName, int rowNum, String data) {
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return false;
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if (colNum == -1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
// cell style
// CellStyle cs = workbook.createCellStyle();
// cs.setWrapText(true);
// cell.setCellStyle(cs);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is created successfully else false
public boolean addSheet(String sheetname) {
FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is removed successfully else false if sheet does
// not exist
public boolean removeSheet(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return false;
FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName, String colName) {
// System.out.println("**************addColumn*********************");
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return false;
XSSFCellStyle style = workbook.createCellStyle();
// style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
// style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
// cell = row.getCell();
// if (cell == null)
// System.out.println(row.getLastCellNum());
if (row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
cell.setCellValue(colName);
cell.setCellStyle(style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try {
if (!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
// style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
// style.setFillPattern(XSSFCellStyle.NO_FILL);
for (int i = 0; i < getRowCount(sheetName); i++) {
row = sheet.getRow(i);
if (row != null) {
cell = row.getCell(colNum);
if (cell != null) {
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// find whether sheets exists
public boolean isSheetExist(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1) {
index = workbook.getSheetIndex(sheetName.toUpperCase());
if (index == -1)
return false;
else
return true;
} else
return true;
}
// returns number of columns in a sheet
public int getColumnCount(String sheetName) {
// check if sheet exists
if (!isSheetExist(sheetName))
return -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if (row == null)
return -1;
return row.getLastCellNum();
}
public int getCellRowNum(String sheetName, String colName, String cellValue) {
for (int i = 2; i <= getRowCount(sheetName); i++) {
if (getCellData(sheetName, colName, i).equalsIgnoreCase(cellValue)) {
return i;
}
}
return -1;
}
}

Entity framework in order

Sourcefile and file name are the source path . Archive folder and the archive filename is the destination folder . The value of the input file should be moved to the destination file.Getting error while copying file from source to destination. Showing "File has been already created". Please let me know how to find the directory of a source file without hardcode. How can I write the valid details in another file in the XML Format.
using System; using System.Collections.Generic;using System.IO;
using System.Linq;using System.Security; using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using EmployeeValidation;
using static EmployeeValidation.FundsValidatorException;
namespace FundsValidator
{
public class empValidator
{
public bool ProcessData(string sourceFolder, string fileName, string archiveFolder, string archiveFileName, SqlConnection connection)
{
List<Order> Orders = ReadAllDataFromInputFile(sourceFolder,fileName);
//Step 2
//SetValidationFlag
List<Order> ValidOrder = SetValidationFlag(Orders);
//Step 3
//InsertOrderData
bool insertBit = InsertOrderData(ValidOrder, connection);
//Step 4
//GetProductsCommission
DataTable dtprodcomm = GetProductsCommission(connection);
//Step 5
//archive file
bool archive = CopyToArchive( sourceFileName, sourceFilePath, archiveFileName, archiveFilePath)
return true;
}
public List<Order> ReadAllDataFromInputFile(string sourceFolder, string fileName)
{
List<Order> inputlist = null;
{
try
{
inputlist = new List<Order>();
var inputlines = File.ReadAllLines(sourceFolder + fileName);
foreach (var item in inputlines)
{
string[] datas = item.Split(',');
Order orderdetails = new Order()
{
OrderId = datas[0],
SalesPersonId = datas[1],
OrderDate = Convert.ToDateTime(datas[2]).ToShortDateString(),
ModelNbr = datas[3],
Quantity = datas[4],
CustomerId = datas[5],
DeliveryDate = datas[6]
};
inputlist.Add(orderdetails);
}
}
catch(OrderProcessorException)
{
throw new OrderProcessorException();
}
}
return inputlist;
}
public List<Order> SetValidationFlag(List<Order> Orders)
{
List<Order> validList = null;
validList = new List<Order>();
int num = 0;
DateTime dtOrderdate;
DateTime dtdeliverydate;
if (Orders != null && Orders.Count >0)
{
foreach(var item in Orders)
{
if(int.TryParse(item.OrderId, out num) &&
item.SalesPersonId.StartsWith("SP") && item.SalesPersonId.Substring(2).Length == 3 && int.TryParse(item.SalesPersonId.Substring(2), out num) &&
DateTime.TryParse(item.OrderDate, out dtOrderdate) &&
item.ModelNbr.StartsWith("ML") && item.ModelNbr.Substring(2).Length == 3 && int.TryParse(item.ModelNbr.Substring(2), out num) &&
int.TryParse(item.Quantity, out num) && DateTime.TryParse(item.DeliveryDate, out dtdeliverydate) && (Convert.ToDateTime(item.DeliveryDate) - Convert.ToDateTime(item.OrderDate)).TotalDays > 7)
{
item.ValidFlag = "V";
}
else
{
item.ValidFlag = "E";
}
validList.Add(item);
}
}
return validList;
}
public bool InsertOrderData(List<Order> Orders, SqlConnection connectionString)
{
bool bret = true;
{
if(Orders !=null && Orders.Count >0)
{
foreach(var item in Orders)
{
using (SqlCommand command = connectionString.CreateCommand())
{
command.CommandText = "Insert into SBA.Orders(OrderId,SalesPersonId,OrderDate,ModelNbr,Quantity,CustomerId,Deliverydate,ValidFlag) Values('" + item.OrderId + "','" + item.SalesPersonId + "','" + item.OrderDate + "','" + item.ModelNbr + "','" + item.Quantity + "','" + item.CustomerId + "','" + item.DeliveryDate + "','" + item.ValidFlag + "')";
command.Connection = connectionString;
connectionString.Open();
int count = command.ExecuteNonQuery();
connectionString.Close();
if (count > 0)
{
bret = true;
}
else
bret = false;
}
}
}
else
{
bret = false;
}
}
return bret;
}
public DataTable GetProductsCommission(SqlConnection connectionString)
{
DataTable dtProductsCommission = null;
using (SqlCommand command = connectionString.CreateCommand())
{
command.CommandText = "Select ModelNbr,Commission_Percentage,Base_Price from SBA.Product_Commission";
command.Connection = connectionString;
connectionString.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
dtProductsCommission = ds.Tables[0];
}
return dtProductsCommission;
}
public bool InsertCommissionData(List<Order> Orders, DataTable dtProductsCommission, SqlConnection connectionString)
{
bool bret = true;
if (Orders != null && Orders.Count > 0 && dtProductsCommission.Rows.Count > 0)
{
foreach (var item in Orders)
{
if (item.ValidFlag == "V")
{
foreach (DataRow dr in dtProductsCommission.Rows)
{
float commamt = Convert.ToInt32(dr["Commission_Percentage"]) * Convert.ToInt32(dr["Base_Price"]) * Convert.ToInt32(item.Quantity);
using (SqlCommand cmd = connectionString.CreateCommand())
{
cmd.CommandText = "Insert into SBA.Order_Commission(OrderId,CommissionAmt) Values('" + item.OrderId + "','" + commamt + "')";
connectionString.Open();
cmd.ExecuteNonQuery();
connectionString.Close();
bret = true;
}
}
}
}
}
else
{
bret = false;
}
return bret;
}
public bool CopyToArchive(string sourceFileName, string sourceFilePath, string archiveFileName, string archiveFilePath)
{
bool bret = true;
if(!File.Exists(archiveFilePath + archiveFileName))
{
File.Copy(sourceFilePath + sourceFileName, archiveFilePath + archiveFileName);
}
else
{
File.Delete(archiveFilePath + archiveFileName);
File.Copy(sourceFilePath + sourceFileName, archiveFilePath + archiveFileName);
}
return bret;
}
}
}
I have fixed this problem.Please refer this program for more details
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 FundsValidator
{
public void ProcessData(string FilePath, string FileName, SqlConnection connection, string errorFilename, string errorFilepath)
{
List<Funds> Alllstfunds = new List<Funds>();
List<Funds> Validlstfunds = new List<Funds>();
Alllstfunds= ReadValuesfromInputfile(FilePath, FileName);
Validlstfunds = GetValidFunds(Alllstfunds, errorFilename, errorFilepath);
SaveValidListToDB(Validlstfunds,connection);
List<Funds> Removeddup= GerPerFundDetails(Validlstfunds);
CalculateNavandSaveToDatabase(Removeddup,connection);
}
public List<Funds> ReadValuesfromInputfile(string FilePath, string FileName)
{
List<Funds> AllListfunds = new List<Funds>();
string s1= null;
StreamReader sw = File.OpenText(FilePath + FileName);
while ((s1 = sw.ReadLine()) != null)
{
Funds fund = new Funds();
string[] s = s1.Split(',');
fund.FundsID = s[0].ToString();
fund.SubfundID = s[1].ToString();
fund.Asset = s[2].ToString();
fund.La = s[3].ToString();
fund.o = s[4].ToString();
AllListfunds.Add(fund);
}
return AllListfunds;
}
public List<Funds> GetValidFunds(List<Funds> Alllstfunds, string errorFilename,string errorFilepath)
{
try
{
List<Funds> validlist = new List<Funds>();
List<Funds> Invalid = new List<Funds>();
foreach (Funds x in Alllstfunds)
{
bool valid = true;
valid = valid && (!string.IsNullOrEmpty(x.FundsID) && x.FundsID.StartsWith("F")) && x.FundsID.Length == 4 && x.FundsID.Substring(1).Length == 3 && x.FundsID.Substring(1).All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.SubfundID)) && x.SubfundID.StartsWith("SF") && x.SubfundID.Length == 5 && x.SubfundID.Substring(2).Length == 3 && x.SubfundID.Substring(2).All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.Asset)) && x.Asset.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.La)) && x.La.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(x.o)) && x.o.All(char.IsDigit);
if (valid)
{
validlist.Add(x);
}
else
{
Invalid.Add(x);
}
}
SaveInValidinErrorTxt(Invalid, errorFilename, errorFilepath);
return validlist;
}
catch (Exception ex)
{
throw new FundsValidatorException(ex.Message);
}
}
public void SaveInValidinErrorTxt(List<Funds> Invalid,string errorFilename,string errorFilepath)
{
if (Invalid.Count > 0 && Invalid != null)
{
if (!File.Exists(errorFilepath + errorFilename))
{
var i=File.Create(errorFilepath + errorFilename);
i.Close();
}
StreamWriter sw = File.AppendText(errorFilepath+errorFilename);
foreach (Funds f in Invalid)
{
sw.WriteLine(f.FundsID+","+f.SubfundID+","+f.Asset+","+f.La+","+f.o);
}
sw.Flush();
sw.Close();
}
}
public void SaveValidListToDB(List<Funds> Validlstfunds, SqlConnection connection)
{
try
{
foreach (Funds f in Validlstfunds)
{
connection.Open();
SqlCommand cmd = new SqlCommand(("Insert into SBA.Fund_Details (FundId,SubFundId,Assets,Liabilities,OutstandingShares) Values ( '" + f.FundsID + "','" + f.SubfundID + "','" + f.Asset + "','" + f.La + "','" + f.o + "')"), connection);
int i = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
}
}
catch (Exception ex)
{
throw new FundsValidatorException(ex.Message);
}
}
public List<Funds> GerPerFundDetails(List<Funds> Validlists)
{
List<string> s = new List<string>();
List<Funds> RemoveDup = new List<Funds>();
String[] r = (from a in Validlists
select a.FundsID).Distinct().ToArray();
foreach (String x in r)
{
int assetnum = 0;
int lanum = 0;
int onum=0;
foreach (Funds q in Validlists)
{
if (x.ToString() == q.FundsID)
{
assetnum = assetnum + int.Parse(q.Asset);
lanum=lanum+int.Parse(q.La);
onum=onum+int.Parse(q.o);
}
}
Funds f= new Funds();
f.FundsID=x.ToString();
f.Asset=assetnum.ToString();
f.La=lanum.ToString();
f.o= onum.ToString();
RemoveDup.Add(f);
}
return RemoveDup;
}
public void CalculateNavandSaveToDatabase(List<Funds> Removeddup,SqlConnection connection)
{
List<Funds> NAVClaculated = new List<Funds>();
foreach(Funds item in Removeddup)
{
item.NAV= (float)(Math.Round(((float.Parse(item.Asset) - float.Parse(item.La))/(float.Parse(item.o))),2));
NAVClaculated.Add(item);
}
foreach (Funds f in NAVClaculated)
{
connection.Open();
SqlCommand cmd = new SqlCommand(("Insert into SBA.Nav_Report (FundId,Assets,Liabilities,OutstandingShares,Nav) Values ( '" + f.FundsID + "','" + f.Asset + "','" + f.La + "','" + f.o +"','"+f.NAV+ "')"), connection);
int i = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
}
}
}
}
namespace Tarriffs
{
public class Tariff
{
public string UserId { get; set; }
public string UserName { get; set; }
public string Category { get; set; }
public string LastMeterReading { get; set; }
public string CurrentMeterReading { get; set; }
public string ReadingDate { get; set; }
public string NoofUnits { get; set; }
public string CalculatedAmount { get; set; }
}
class Program
{
static void Main(string[] args)
{
string inputfile = #"D:\Tarriffs\Input file\Tarriff_0919.txt";
List<Tariff> read = new List<Tariff>();
StreamReader sr = File.OpenText(inputfile);
string s= null;
while((s= sr.ReadLine())!=null)
{
string[] item = s.Split(',');
Tariff tar = new Tariff();
tar.UserId= item[0];
tar.UserName= item[1];
tar.Category= item[2];
tar.LastMeterReading= item[3];
tar.CurrentMeterReading= item[4];
tar.ReadingDate= item[5];
bool valid = validandlogger(tar.UserId, tar.UserName, tar.Category, tar.LastMeterReading, tar.CurrentMeterReading, tar.ReadingDate);
if (valid)
{
double[] tarriffcalculation = tarriffcalc(tar.LastMeterReading, tar.CurrentMeterReading);
Tariff final = new Tariff();
final.UserId = item[0];
final.UserName = item[1];
final.NoofUnits = tarriffcalculation[0].ToString();
final.CalculatedAmount = tarriffcalculation[1].ToString();
SqlConnection conn= new SqlConnection(#"Data Source=NA03OSDVP00746\SQLEXPRESS;Initial Catalog=DBTarriffValidation;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Insert into dbo.custom values ('" + final.UserId + "','" + final.UserName + "','" + final.NoofUnits + "','" + final.CalculatedAmount + "')", conn);
int i = cmd.ExecuteNonQuery();
conn.Close();
}
}
}
public static bool validandlogger(string UserId, string UserName, string Category, string LastMeterReading, string CurrentMeterReading, string ReadingDate)
{
bool valid = true;
DateTime dt;
Regex name = new Regex("^[a-zA-Z0-9]{6}$");
valid = valid && (!string.IsNullOrEmpty(UserId)) && UserId.All(char.IsDigit);
valid = valid && (!string.IsNullOrEmpty(UserName)) && name.IsMatch(UserName);
string[] vcategory = { "COM", "DOM", "OTD" };
valid = valid && vcategory.Contains(Category);
valid = valid && LastMeterReading.All(char.IsDigit);
valid = valid && CurrentMeterReading.All(char.IsDigit);
valid = valid && DateTime.TryParseExact(ReadingDate, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (!valid)
{
string errortextfile = #"D:\Tarriffs\Error_log\";
string errorfile = "Error_"+DateTime.Now.ToString("MMyyyy")+".txt";
if (!File.Exists(errortextfile + errorfile))
{
var i = File.Create(errortextfile + errorfile);
i.Close();
}
StreamWriter sw = File.AppendText(errortextfile + errorfile);
sw.WriteLine(UserId + "," + UserName + "," + Category + "," + LastMeterReading + "," + CurrentMeterReading + "," + ReadingDate);
sw.Flush();
sw.Close();
}
else
{
return true;
}
return false;
}
public static double[] tarriffcalc(string LastMeterReading, string CurrentMeterReading)
{
int LMeterReading = 0;
int CMeterReading = 0;
LMeterReading = int.Parse(LastMeterReading);
CMeterReading = int.Parse(CurrentMeterReading);
int units = CMeterReading - LMeterReading;
double totalamount = 0;
if (units <= 100)
{
var baserate = 20;
totalamount = (units * 1) + baserate;
}
else if (units <= 200)
{
var baserate = 20;
totalamount = (units * 1.5) + baserate;
}
else if (units <= 500)
{
var baserate = 40;
totalamount = 250 +((units-200)*3)+baserate;
}
else if (units > 500)
{
var baserate = 40;
totalamount = 1700 + ((units - 500) * 5.75) + baserate;
}
return new double[] {units,totalamount};
}
}
}

Entity Framework in stock market

public List<StockMarket> ReadAllRecords(string TxtFilePath, string TxtFileName)
{
List<StockMarket> Stock = new List<StockMarket>();
String[] a = File.ReadAllLines(TxtFilePath + TxtFileName);
foreach (var b in a)
{
String[] d = b.Split(',');
StockMarket S = new StockMarket();
S.ProductId = d[0];
S.ProductName = d[1];
S.StockId = d[2];
S.StockName = d[3];
S.StockPrice = d[4];
S.NumberofStocks = d[5];
S.Currency = d[6];
Stock.Add(S);
}
return Stock;
}
public List<StockMarket> GetValidRecords(List<StockMarket> Stock, string ErrorFilePath, string ErrorFileName)
{
List<StockMarket> Valid = new List<StockMarket>();
List<StockMarket> InValid = new List<StockMarket>();
foreach (var s in Stock)
{
bool ValidRecord = true;
if (String.IsNullOrEmpty(s.ProductId) || !s.ProductId.All(Char.IsDigit))
{
ValidRecord = false;
}
if (!s.ProductName.StartsWith("ABC") || s.ProductName.Length != 6)
{
ValidRecord = false;
}
if (String.IsNullOrEmpty(s.StockId) || !s.StockId.All(Char.IsDigit))
{
ValidRecord = false;
}
if (!s.StockName.StartsWith("SBC") || s.StockName.Length != 7)
{
ValidRecord = false;
}
if (string.IsNullOrEmpty(s.StockPrice))
{
ValidRecord = false;
}
if (string.IsNullOrEmpty(s.NumberofStocks) || !s.NumberofStocks.All(char.IsDigit))
{
ValidRecord = false;
}
if (!(s.Currency.Equals("INR") || s.Currency.Equals("USD") || s.Currency.Equals("EUR")))
{
ValidRecord = false;
}
if (ValidRecord)
{
Valid.Add(s);
}
else
{
InValid.Add(s);
}
}
LogErrorRecord(InValid, ErrorFilePath, ErrorFileName);
return Valid;
}
public List<StockMarket> CalculateTotalPrice(List<StockMarket> Stock)
{
foreach (var s in Stock)
{
if (s.Currency.Equals("INR"))
{
s.TotalPrice = (Convert.ToDouble(s.StockPrice) * Convert.ToDouble(s.NumberofStocks) * 1).ToString();
}
else if (s.Currency.Equals("USD"))
{
s.TotalPrice = (Convert.ToDouble(s.StockPrice) * Convert.ToDouble(s.NumberofStocks) * 0.5).ToString();
}
else if (s.Currency.Equals("EUR"))
{
s.TotalPrice = (Convert.ToDouble(s.StockPrice) * Convert.ToDouble(s.NumberofStocks) * 0.75).ToString();
}
}
return Stock;
}
public void LogErrorRecord(List<StockMarket> InvalidStock, string ErrorFilePath, string ErrorFileName)
{
List<String> InvalidItems = new List<string>();
foreach (var I in InvalidStock)
{
InvalidItems.Add(I.ProductId + " " + I.ProductName + " " + I.StockId + " " + I.StockName + " " + I.StockPrice + " " + I.NumberofStocks + " " + I.Currency);
}
File.AppendAllLines(ErrorFilePath + ErrorFileName, InvalidItems);
}
public void SavetoDB(List<StockMarket> Stock, SqlConnection connection)
{
String Query = "insert into StockMarket(ProductId,Productname,StockId,StockName,StockPrice,NumberofStocks,Currency,TotalPrice) Values(#ProductId,#ProductName,#StockId,#StockName,#StockPrice,#NumberofStocks,#Currency,#TotalPrice)";
connection.Open();
foreach (var a in Stock)
{
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.Add("#ProductId", a.ProductId);
cmd.Parameters.Add("#ProductName", a.ProductName);
cmd.Parameters.Add("#StockId", a.StockId);
cmd.Parameters.Add("#StockName", a.StockName);
cmd.Parameters.Add("#StockPrice", a.StockPrice);
cmd.Parameters.Add("#NumberofStocks", a.NumberofStocks);
cmd.Parameters.Add("#Currency", a.Currency);
cmd.Parameters.Add("#TotalPrice", a.TotalPrice);
int b = cmd.ExecuteNonQuery();
}
connection.Close();
}
public void SaveDistinctProductName(List<StockMarket> Stock, SqlConnection connection)
{
String Query = "if not exists( select * from Product where ProductId = #ProductId) begin insert into Product (ProductId,ProductName) Values(#ProductId,#ProductName)end";
connection.Open();
foreach (var a in Stock)
{
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.Add("#ProductId", a.ProductId);
cmd.Parameters.Add("#ProductName", a.ProductName);
int b = cmd.ExecuteNonQuery();
}
connection.Close();
}
public void SaveDistinctStockName(List<StockMarket> Stock, SqlConnection connection)
{
String Query = "if not exists( select * from Stock where StockId = #StockId) begin insert into Stock (StockId,StockName) Values(#StockId,#StockName)end";
connection.Open();
foreach (var a in Stock)
{
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.Add("#StockId", a.StockId);
cmd.Parameters.Add("#StockName", a.StockName);
int b = cmd.ExecuteNonQuery();
}
connection.Close();
}
Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database. This short video explains the differences and how to find the one that is right for you.
Please let me know the overview of the code
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=NA03OSDVP00746\SQLEXPRESS;Initial Catalog=DBEmployeeValidation;Integrated Security=True");
EmployeeValidator empValidator = new EmployeeValidator();
empValidator.ProcessData(#"D:\Employee_Validator\Input File\", "Emp_122014.xml", #"D:\Employee_Validator\Error File\", "Emp_122014.xml", connection);
}
}
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
using System.Text.RegularExpressions;
using System.Data.Linq;
using System.Globalization;
using System.Xml.Serialization;
using System.IO;
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,string errorFilePath, string errorFileName, SqlConnection connection)
{
//Do your logic here
//Step 1
//ReadAllEmployeesFromXmlFile
List<Employee> lstemp = new List<Employee>();
List<Employee> validemp = new List<Employee>();
lstemp = ReadAllEmployeesFromXmlFile(xmlFilePath,xmlFileName);
validemp = PickValidEmployees(lstemp);
SaveValidEmployeesToDB(validemp, connection);
ReadfromDBtoTxt(connection);
//Step 2
//PickValidEmployees
//Step 3
//SaveValidEmployeesToDataBase
}
public List<Employee> ReadAllEmployeesFromXmlFile(string xmlFilePath, string xmlFileName)
{
//Read the employee details from the xml file and return it in List collection
//Do not hardcode the filename and the file path here
//Do not return the date with time appended to it.
string employeefile = xmlFilePath + xmlFileName;
List<Employee> empdetail = new List<Employee>();
XElement getelementfile = XElement.Load(employeefile);
IEnumerable<XElement> items = getelementfile.Elements();
foreach (var item in items)
{
string _EmployeeId = item.Element("EmployeeId").Value;
string _EmployeeName = item.Element("EmployeeName").Value;
string _EmailId = item.Element("EmailId").Value;
string _DateOfJoining = item.Element("DateOfJoining").Value;
empdetail.Add(new Employee(){ EmployeeId= _EmployeeId,
EmployeeName= _EmployeeName,
EmailId=_EmailId,
DateOfJoining=_DateOfJoining
});
}
return empdetail;
}
public List<Employee> PickValidEmployees(List<Employee> employees)
{
//Pick the valid employees from the List collection
//Return the valid employees in a List
List<Employee> valid = new List<Employee>();
List<Employee> Invalid = new List<Employee>();
List<string> empnum = new List<string>();
bool isvalid = true;
foreach(Employee em in employees)
{
Regex rgxisnumeric = new Regex(#"^\d$");
Regex rgxisalphanumeric=new Regex( #"^\d*[a-zA-Z]{1,}\d*");
Regex rgxemail = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Regex rgxDate= new Regex(#"^((0[1-9]|1[0-2])\/((0|1)[0-9]|2[0-9]|3[0-1])\/((19|20)\d\d))$");
if (!empnum.Contains(em.EmployeeId))
{
empnum.Add(em.EmployeeId);
isvalid = true;
}
else
{
isvalid = false;
}
int empname;
isvalid= isvalid && (!string.IsNullOrEmpty(em.EmployeeId)) && (rgxisnumeric.IsMatch(em.EmployeeId));
isvalid= isvalid && (int.TryParse(em.EmployeeName, out empname)== false);
isvalid= isvalid && (!string.IsNullOrEmpty(em.EmployeeName)) && (rgxisalphanumeric.IsMatch(em.EmployeeName));
isvalid= isvalid && (!string.IsNullOrEmpty(em.EmailId)) && (rgxemail.IsMatch(em.EmailId));
isvalid= isvalid && (!string.IsNullOrEmpty(em.DateOfJoining)) && (rgxDate.IsMatch(em.DateOfJoining));
if(isvalid)
{
DateTime dt;
isvalid= isvalid && DateTime.TryParseExact(em.DateOfJoining,"MM/dd/yyyy",new CultureInfo("en-US"),DateTimeStyles.None, out dt);
}
if(isvalid)
{
valid.Add(em);
}
else
{
Invalid.Add(em);
}
}
SaveInValidEmployeesTotxt(Invalid);
return valid;//Return only valid employees in List
}
public void SaveValidEmployeesToDB(List<Employee> employees, SqlConnection connection)
{
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
//Do not hardcode the connection string here
SqlConnection conn = connection;
foreach(Employee emp in employees)
{
string command = "Insert into SBA.Employees (EmployeeId,EmployeeName,EmailId,DateOfJoining) values (#EmployeeId,#EmployeeName,#EmailId,#DateOfJoining)";
SqlCommand cmd = new SqlCommand(command, conn);
conn.Open();
cmd.Parameters.AddWithValue("#EmployeeId",emp.EmployeeId);
cmd.Parameters.AddWithValue("#EmployeeName",emp.EmployeeName);
cmd.Parameters.AddWithValue("#EmailId",emp.EmailId);
cmd.Parameters.AddWithValue("#DateOfJoining",DateTime.Parse(emp.DateOfJoining).ToString("MM/dd/yyyy"));
cmd.ExecuteNonQuery();
conn.Close();
}
}
public void SaveInValidEmployeesTotxt(List<Employee> Invalid)
{
string invalidpath = #"D:\Employee_Validator\Error File\Emp_122014.xml";
XmlSerializer serialise = new XmlSerializer(typeof(List<Employee>));
TextWriter writeinvalid = new StreamWriter(invalidpath);
serialise.Serialize(writeinvalid,Invalid);
}
public void ReadfromDBtoTxt(SqlConnection connection)
{
string newfilepath = #"D:\Employee_Validator\DBtoTXT\EmpoValid_" + DateTime.Now.ToString("MMyyyy") + ".txt";
List<Employee> dbtotextlist = new List<Employee>();
if (!File.Exists(newfilepath))
{
var g= File.Create(newfilepath);
g.Close();
}
SqlCommand cmd = new SqlCommand("Select * from SBA.Employees",connection);
connection.Open();
SqlDataReader readdata = cmd.ExecuteReader();
while (readdata.Read())
{
dbtotextlist.Add(new Employee
{
EmployeeId = readdata["EmployeeId"].ToString(),
EmployeeName = readdata["EmployeeName"].ToString(),
EmailId = readdata["EmailId"].ToString(),
DateOfJoining = readdata["DateOfJoining"].ToString()
});
}
sconnection.Close();
StreamWriter sw = File.AppendText(newfilepath);
foreach(Employee s in dbtotextlist)
{
sw.WriteLine(s.EmployeeId+","+s.EmployeeName+","+s.EmailId+","+ DateTime.Parse(s.DateOfJoining).ToString("MM/dd/yyyy"));
}
sw.Flush();
sw.Close();
}
}
}
static void Main(string[] args)
{
SqlConnection connectionObject = new SqlConnection(#"Data Source=NA03OSDVP00746\SQLEXPRESS;Initial Catalog= DBFXCalculation;Integrated Security=True");
Main fxcalculatorobj = new Main();
fxcalculatorobj.ProcessData(#"D:\frameworksample\Input File\", "TradeOrders_032013.txt",
#"D:\frameworksample\ErrorLog\", "InvalidRecords_032014.txt", connectionObject,
#"D:\frameworksample\Archive\", "TradeOrders_032013_Processed.txt");
/*
* Pass the file path, file names and connection string in this method alone.
* Do not hardcode in any other methods
*/
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Reflection;
namespace frameworksample
{
class Main
{
public void ProcessData(string sourceFolder, string fileName, string errorLogFilePath,
string errorLogFileName, SqlConnection connectionObject,
string archiveFilePath, string archiveFileName)
{
//Step 1:ReadAllDataFromInputFile
List<Trade> trades = ReadAllDataFromInputFile(sourceFolder, fileName);
//Step 2:PickValidTradeDetails;
List<Trade> validateTrade = PickValidTradeDetails(trades, errorLogFilePath, errorLogFileName);
//Step 3: SaveValidRecordsToDB
SaveValidRecordsToDB(validateTrade, connectionObject);
//Step 4:CalculateFXRate
List<FXRate> fxRates = CalculateFXRate(connectionObject);
//Step 5:SaveFXRate
//List<FXRate> fxRates = new List<FXRate>();
SaveFXRate(fxRates, connectionObject);
//Step 6:CopyToArchive
CopyToArchive(archiveFilePath, archiveFileName);
//Validate data
}
public List<Trade> ReadAllDataFromInputFile(string sourceFolder, string fileName)
{
List<Trade> trades = new List<Trade>();
//Do your logic to read file and storing it into list of trades ..here..
//Do not hardcode the filename and the file path here
using(StreamReader sr= File.OpenText(sourceFolder+fileName))
{
string s="";
while((s=sr.ReadLine())!=null)
{
if(s.Contains(','))
{
string[] splited= s.Split(',');
Trade tradeitem= new Trade();
tradeitem.TradeId= splited[0];
tradeitem.ISIN= splited[1];
tradeitem.TradeDate= splited[2];
tradeitem.MaturityDate= splited[3];
tradeitem.SchemeName= splited[4];
tradeitem.TradeType= splited[5];
tradeitem.Currency= splited[6];
tradeitem.Amount= splited[7];
trades.Add(tradeitem);
}
}
}
return trades;
}
public List<Trade> PickValidTradeDetails(List<Trade> trades, string errorLogFilePath, string errorLogFileName)
{
//email: \w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)* ,,,, \b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b
// Step 1 : filter the valid trades and invalid trades, save the invalid
List<Trade> validTrades = new List<Trade>(); //identify all the valid trades and assign.
//Do not hardcode the filename and the file path here
List<Trade> invalidTrade = new List<Trade>();
bool isValid = true;
foreach (Trade x in trades)
{
isValid=(!string.IsNullOrEmpty(x.TradeId));
Regex rgxtradeid = new Regex(#"\bTR\d{3}\b");
isValid = isValid && rgxtradeid.IsMatch(x.TradeId);
isValid=(isValid && (!string.IsNullOrEmpty(x.ISIN)));
Regex rgxisin = new Regex(#"\bISIN\d{3}\b");
isValid = (rgxisin.IsMatch(x.ISIN));
Regex rgxdate = new Regex("((0[1-9]|1[0-2])\\/((0|1)[0-9]|2[0-9]|3[0-1])\\/((19|20)\\d\\d))$");
DateTime dt;
isValid = (isValid && (!string.IsNullOrEmpty(x.TradeDate)) && (rgxdate.IsMatch(x.TradeDate)));
isValid = (isValid && (!string.IsNullOrEmpty(x.MaturityDate)) && (rgxdate.IsMatch(x.MaturityDate)));
if (isValid)
{
DateTime MD = DateTime.Parse(x.MaturityDate);
DateTime TD = DateTime.Parse(x.TradeDate);
int year = MD.Year - TD.Year;
isValid = isValid && (year > 5);
isValid = isValid && (!string.IsNullOrEmpty(x.TradeType));
isValid = isValid && (x.Currency.Equals("GBP") || x.Currency.Equals("EUR") || x.Currency.Equals("USD") || x.Currency.Equals("INR"));
isValid = isValid && (!string.IsNullOrEmpty(x.Amount));
int i;
bool isnumeric = int.TryParse(x.Amount, out i);
isValid = isValid && (isnumeric);
}
if(isValid)
{
Trade val= new Trade();
val.TradeId= x.TradeId;
val.ISIN= x.ISIN;
val.TradeDate= x.TradeDate;
val.MaturityDate= x.MaturityDate;
val.SchemeName= x.SchemeName;
val.TradeType= x.TradeType;
val.Currency= x.Currency;
val.Amount= x.Amount;
validTrades.Add(val);
}
else
{
Trade valerror= new Trade();
valerror.TradeId= x.TradeId;
valerror.ISIN= x.ISIN;
valerror.TradeDate= x.TradeDate;
valerror.MaturityDate= x.MaturityDate;
valerror.SchemeName= x.SchemeName;
valerror.TradeType= x.TradeType;
valerror.Currency= x.Currency;
valerror.Amount= x.Amount;
invalidTrade.Add(valerror);
}
}
SaveInvalidRecordsToLogFile(invalidTrade, errorLogFilePath, errorLogFileName);
// SaveInvalidRecordsToLogFile(List<Trades>); // pass all the invalid trades to log...
return validTrades;
}
public bool SaveInvalidRecordsToLogFile(List<Trade> invalidTrades, string errorLogFilePath, string errorLogFileName)
{
//Do your logic here
//Do not hardcode the filename and the file path here
if (invalidTrades != null && invalidTrades.Count > 0)
{
string errorLogfile = errorLogFilePath + errorLogFileName;
try
{
if (!File.Exists(errorLogfile))
{
var invalidfile = File.Create(errorLogfile);
invalidfile.Close();
}
using (StreamWriter swinvalid = File.AppendText(errorLogfile))
{
swinvalid.WriteLine("TradeId|ISIN|TradeDate|MaturityDate|Tradetype|Currency|Amount");
foreach (Trade ivt in invalidTrades)
{
swinvalid.WriteLine(ivt.TradeId + "," + ivt.ISIN + "," + ivt.TradeDate + "," + ivt.MaturityDate + "'" + ivt.TradeType + "," + ivt.Currency + "," + ivt.Amount);
}
}
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
}
return true;
}
public bool SaveValidRecordsToDB(List<Trade> validTrades, SqlConnection sqlConnectionObject)
{
//Do your logic here to upload to DB table
//Do not hardcode the connection string here
//Do not create the redundant connection Object for SqlConnection, use the conncetionObject given in the method parameter.
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
//var ConnectionString = sqlConnectionObject.ConnectionString;
if (validTrades.Count > 0 && validTrades != null)
{
SqlConnection conn = sqlConnectionObject;
conn.Open();
foreach (Trade valid in validTrades)
{
SqlCommand cmd = new SqlCommand(("Insert into SBA.Trade_Details (TradeID,ISIN,TradeDate,MaturityDate,SchemeName,TradeType,Currency,Amount) values (#TradeID,#ISIN,#TradeDate,#MaturityDate,#SchemeName,#TradeType,#Currency,#Amount)"),conn);
cmd.Parameters.Add("#TradeID",valid.TradeId);
cmd.Parameters.Add("#ISIN", valid.ISIN);
cmd.Parameters.Add("#TradeDate", valid.TradeDate);
cmd.Parameters.Add("#MaturityDate", valid.MaturityDate);
cmd.Parameters.Add("#SchemeName", valid.SchemeName);
cmd.Parameters.Add("#TradeType", valid.TradeType);
cmd.Parameters.Add("#Currency", valid.Currency);
cmd.Parameters.Add("#Amount", valid.Amount);
cmd.ExecuteNonQuery();
}
conn.Close();
}
return true;
}
public List<FXRate> CalculateFXRate(SqlConnection sqlConnectionObject)
{
// TODO :Read the Trade details for TradeType FX from database and calculate the rates.
// Calculate the rate for each trade and add in a list of FXRates.
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
//List<FXRate> FxRates = null; // assign list of FXRates;
//Do not hardcode the connection string here
//Do not create the redundant connection Object for SqlConnection, use the conncetionObject given in the method parameter.
List<FXRate> FxRates = new List<FXRate>();
List<Trade> trades = new List<Trade>();
try
{
SqlConnection conne = sqlConnectionObject;
string queryString = "Select * from SBA.Trade_Details";
SqlCommand cmd = new SqlCommand(queryString, conne);
conne.Open();
SqlDataReader datareader = cmd.ExecuteReader();
while (datareader.Read())
{
Trade validfx = new Trade{TradeId = datareader["TradeId"].ToString(),ISIN = datareader["ISIN"].ToString(),TradeDate = datareader["TradeDate"].ToString(),
MaturityDate = datareader["MaturityDate"].ToString(),SchemeName = datareader["SchemeName"].ToString(),TradeType = datareader["TradeType"].ToString(),
Currency = datareader["Currency"].ToString(), Amount = datareader["Amount"].ToString()};
trades.Add(validfx);
}
conne.Close();
foreach (Trade trad_para_to_calc_fx in trades)
{
FXRate fx = new FXRate();
fx.TradeId = trad_para_to_calc_fx.TradeId;
fx.Currency = trad_para_to_calc_fx.Currency;
fx.Amount = trad_para_to_calc_fx.Amount;
float amount = float.Parse(fx.Amount, CultureInfo.InvariantCulture.NumberFormat);
if (trad_para_to_calc_fx.Currency == "USD")
{
fx.AppliedFXRate = float.Parse("0.5",CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("0.5",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
if (trad_para_to_calc_fx.Currency == "GBP")
{
fx.AppliedFXRate = float.Parse("0.6", CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("0.7",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
if (trad_para_to_calc_fx.Currency == "EUR")
{
fx.AppliedFXRate = float.Parse("0.7", CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("0.7",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
if (trad_para_to_calc_fx.Currency == "INR")
{
fx.AppliedFXRate = float.Parse("1", CultureInfo.InvariantCulture.NumberFormat).ToString();
float app_fx_rate = float.Parse("1",CultureInfo.InvariantCulture.NumberFormat);
fx.CalculatedFXRate = ((app_fx_rate) * (amount)).ToString();
}
FxRates.Add(fx);
}
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
return FxRates;
}
public bool SaveFXRate(List<FXRate> fxRates, SqlConnection sqlConnectionObject)
{
//Do your logic here to upload to DB table
//Do not hardcode the connection string here
//Do not create the redundant connection Object for SqlConnection, use the conncetionObject given in the method parameter.
//Do not Prefix Database name in the SQL Query. Query should be "Insert into SBA.TableName"
//Should not be "Insert into DatabaseName.SBA.TableName"
try
{
if (fxRates.Count > 0 && fxRates != null)
{
SqlConnection conne = sqlConnectionObject;
conne.Open();
foreach(FXRate calculated in fxRates)
{
SqlCommand cmd = new SqlCommand("Insert into SBA.FX_Rate (TradeId,Currency,Amount,AppliedFXRate,CalculatedFXRate) values (#TradeId,#Currency,#Amount,#AppliedFXRate,#CalculatedFXRate)", conne);
cmd.Parameters.AddWithValue("#TradeId", calculated.TradeId);
cmd.Parameters.AddWithValue("#Currency",calculated.Currency);
cmd.Parameters.AddWithValue("#Amount",calculated.Amount);
cmd.Parameters.AddWithValue("#AppliedFXRate",calculated.AppliedFXRate);
cmd.Parameters.AddWithValue("#CalculatedFXRate", calculated.CalculatedFXRate);
cmd.ExecuteNonQuery();
}
conne.Close();
}
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
return true;
}
public bool CopyToArchive(string sourcePathWithFileName, string targetPathWithFileName)
{
//Do your logic here
//Do not hardcode the filename and the file path here
try
{
string inputpath="";
string input="";
FileInfo[] files;
DirectoryInfo Di;
string targetFile = sourcePathWithFileName + targetPathWithFileName;
Di = new DirectoryInfo(#"D:\frameworksample\");
files = Di.GetFiles("*.txt", SearchOption.AllDirectories);
foreach (FileInfo di1 in files)
{
if (di1.Name == "TradeOrders_032013.txt")
{
inputpath = di1.DirectoryName.ToString();
input = inputpath+"\\" + di1.Name.ToString();
}
}
if (!Directory.Exists(sourcePathWithFileName))
{
Directory.CreateDirectory(sourcePathWithFileName);
var targetfilecreation = File.Create(targetFile);
targetfilecreation.Close();
}
else
{
File.Delete(targetFile);
Directory.Delete(sourcePathWithFileName, true);
Directory.CreateDirectory(sourcePathWithFileName);
var targetfilecreation =File.Create(targetFile);
targetfilecreation.Close();
}
System.IO.File.Copy(input, targetFile, true);
}
catch (Exception ex)
{
throw new FXCalculatorException(ex.Message);
}
//File.Copy(sourcePathWithFileName + "\\" + targetPathWithFileName, true);
return true;
}
private void ProcessData(Main main)
{
throw new NotImplementedException();
}
//internal void ProcessData(string p, string p_2, string p_3, string p_4, System.Data.SqlClient.SqlConnection connectionObject, string p_5, string p_6)
//{
// throw new NotImplementedException();
//}
}
}