Is it possible to load formula from excel file into grid view using c#? - excel-2007

Consider this example:
I have an excel file in which I have data in two columns like below-
Salary Commission Net Payable
1000 5 1050
2000 10 2200
3000 15 3450
4000 20 4800
The formula used to calculate the Net Payable is : A2+((A2*B2)/100)
Where A2 = Salary (here 1000), and B2 = Commission (here 5)
When I load these data from excel file into grid view, it only loads the values like above.
My question is: Is there any way so that I can load the internal formula also in grid view? Something like A2+((A2*B2)/100) in a grid view column? Its not any development project. I just wonder if this could be done? Thanks.
Edit: The code I am using to load data
try
{
rst = CMDExcel.ExecuteReader();
}
catch (Exception ex)
{
Interaction.MsgBox("Error in reading Operation data from excel file");
return;
}
while (rst.Read())
{
sSalary = string.Empty;
try
{
sSalary = rst("Salary").ToString().Trim();
}
catch (Exception ex)
{
}
if (sSalary.Length > 0)
{
DGMAIN.Rows.Add();
try
{
DGMAIN.Rows(i).Cells("DGMAIN_SALARY").Value = rst("Salary").ToString();
}
catch (Exception ex)
{
}
try
{
DGMAIN.Rows(i).Cells("DGMAIN_COMMISSION").Value = rst("Commission").ToString();
}
catch (Exception ex)
{
}
try
{
DGMAIN.Rows(i).Cells("DGMAIN_NET_PAYABLE").Value = rst("Net Payable").ToString();
}
catch (Exception ex)
{
}
i = i + 1;
}
}
rst.Close();
There is no problem with the code as it loads data correctly into grid view.

Related

How to get the method name and line number in Exception in ASP Core 5

I want to get the method name and line number when an error occur, I am using Core 5.
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex, "Method Name / Line Number");
}
Update:
I found a Solution like this:
_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());
A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The output would be somewhat like:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
where Main() is the method name and 20 is the line number.
To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}
Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

Adding screenshot in extent report 4 for the failed scenarios

I'm using extent report 4.Actually I'm trying to add Screenshot in extent report when the test fails. I'm using below code to achieve this. Screenshot gets attached in the end of my report (please refer the screenshot), but I want screenshot to get attached in the appropriate step i.e. when the test cases fail. Please help me with solutions or workaround
case FAIL:
String path = WrapperMethods.captureScreenshot();
try
{
test.log(logStatus, message + test.addScreenCaptureFromPath(path));
} catch (IOException e)
{
e.printStackTrace();
}
break;
for version 4 you can work as below
if (result.getStatus() == ITestResult.FAILURE) {
test.fail(MarkupHelper.createLabel(result.getName() + "Test Failed", ExtentColor.RED));
test.fail(result.getThrowable());
String screencastPath = null;
try {
screencastPath = Screeshot.captureScreenshot(WebDriverManager.driver);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
test.fail("<b><font color=blue>" + "Screenshot Name: " + Screeshot.sendScreenName() + "</font></b>");
test.fail("<b><font color=red>"
+ " Click the below link OR check the report folder by above screenshot Name to get the Screenshot of failure "
+ "</font></b>", MediaEntityBuilder.createScreenCaptureFromPath(screencastPath).build());
} catch (IOException e) {
test.fail("Test Failed, Cannot attach screeshot");
}
WebDriverManager.driver.close();
}

data provider mismatch error

I am using below code for data provider but it's not working. Please help to me how to resolve data provider mismatch issue. here mentioned complete details about all the methods reading xls , test , data provider .
#DataProvider
public Object[][] getgbTestData(){
Object data[][] = testutil.getTestData(sheetName);
return data;
}
#Test(dataProvider="getgbTestData")
public void addnewuser(String fname,String lname,String email,String pass,String conpass) throws IOException{
newuser.newregistration1(fname, lname, email, pass, conpass);
}
**method:**
public Personaldetails newregistration1(String fsname,String lsname,String email1,String pass1,String conpass1) throws IOException {
Account.click();
Registerlink.click();
Firstname.sendKeys(fsname);
Lastname.sendKeys(lsname);
useremail.sendKeys(email1);
password.sendKeys(pass1);
confirmpassword.sendKeys(conpass1);
submit.click();
//return person;
return new Personaldetails();
}
//using below method to read data from excel
public static Object[][] getTestData(String sheetName) {
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetName);
Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
// System.out.println(sheet.getLastRowNum() + "--------" +
// sheet.getRow(0).getLastCellNum());
for (int i = 0; i < sheet.getLastRowNum(); i++) {
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
// System.out.println(data[i][k]);
}
}
return data;
}
Looks like the test has required 5 arguments but your data provider method getTestData passing less/greater no of arguments.
You are passing the wrong number of arguments. The method addnewuser() expects 5 arguments, but receives only one. You can see it in the last line in the error message
Arguments: [(java.lang.String)fname]
If you want to pass different number of parameters you can use String[] instead of single arguments. And if you expect 5 arguments each time check what data holds in getTestData()

how am i supposed to pull a record from DAO vector?

I'm trying to implement the login page based on Oracle sql using JFrame(swing). I already have inserted IDs and PWs on database. Plus, I've also already defined appropriate -I think- LoginMember method in DAO. Below are the codes for Jframe page and DAO. Please let me know what is wrong with this. I've been struggling with this for the last 5 hours and still have no idea what to do.. HELP!! Sorry if you feel that I have not given enough info to solve this problem.
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strID=tfID.getText();
String strPW=String.valueOf(pwfPW.getPassword());
if(tfID.getText().equals("")) {
JOptionPane.showMessageDialog(Login.this, "Please type your ID");
} else {
dao=new M_DAO();
dao.loginMember(strID,strPW);
if(tfID.getText().equals(dao.loginMember(strID,strPW))) {
JOptionPane.showMessageDialog(Login.this, strID+" : successfully logged in");
}else if(strID ==null && strID.equals(strPW)){
JOptionPane.showMessageDialog(Login.this, "Incorrect ID or PW.");
}else{
System.out.println(10);
}
}
}
});
DAO:
public Vector loginMember(String strID,String strPW) {
Vector items=new Vector();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
conn=DB.hrConn();
String sql="select * from member where strID=? and strPW=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "strID");
pstmt.setString(2, "strPW");
rs=pstmt.executeQuery();
if(rs.next()){
Vector row=new Vector();
row.add("strID");
row.add("strPW");
items.add(row);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt!=null) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return items;
}
I wish it would work so bad...
It only shows the correct answer when I type nothing on ID and PW textfields, saying "Please type your ID". It prints out 10 when I type something on those.(just to check which line has an error.) Oh, please let me know if I need to specify something else!

SQL Server, JTDS causes java.sql.SQLException: Invalid state, the ResultSet object is closed

I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.