want to fetch the data from excel file - selenium-webdriver

Data drven framework, where the values are changing for every case
public static void main(String[] args) throws BiffException, IOException {
Sheet s;
WebDriver driver = new FirefoxDriver();
FileInputStream fi = new FileInputStream("D:\\Nikhil\\FGX\\DataDriven.xlsx");
Workbook W = Workbook.getWorkbook(fi);
s = W.getSheet(0);
for(int row = 0;row <= s.getRows();row++)
{
String Username = s.getCell(0,row).getContents();
System.out.println("Username" +Username);
driver.get("http://********");
driver.findElement(By.xpath("//*[#id='LoginName']")).sendKeys(Username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.xpath("//*[#id='Password']")).sendKeys(password);
driver.findElement(By.xpath("html/body/form/div/div/div/div/fieldset/button")).click();
}

There are several reasons to get the BiffException look at Biff exception in Java.
Make sure you point the correct file, sheet, cell etc. You need to fetch and iterate the excel data. I may not answered directly to your answer, but the below code might help you,
List getData() { **Fetch the data
String path = "filepath";
List dataList = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("TestData");
java.util.Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = ((XSSFRow) rows.next());
// int r=row.getRowNum();
java.util.Iterator cells = row.cellIterator();
int i = 0;
String[] testData= new String[3];
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
String value = cell.getStringCellValue();
if (!value.equals(null)) {
testData [i] = value;
i++;
}
}
dataList.add(testData);
}
}
catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
public Object[][] data() { **Store the data in desired format
#SuppressWarnings("rawtypes")
List dataList= getData();
Object a[][]=new Object[dataList.size()][2];
for(int i=1;i<dataList.size();i++){
String[] test=(String[]) dataList.get(i);
String username = test[0];
String password=test[1];
a[i][0]=username;
a[i][1]=password;
}
return a;

Related

How can I save items to SQL Server?

I have a site that can upload three pictures, that page saves some other data in the table in SQL Server, but it saves the name of one the pictures the same for pictures in database.
Of course, the name of the pictures are different in the folder that save.
My code:
foreach (var item in FileUpload)
{
if (item != null)
{
Random rnd = new Random();
string Pic = rnd.Next().ToString() + ".jpg";
// string Pic = System.IO.Path.GetFileName(file.FileName);
string Path = System.IO.Path.Combine(Server.MapPath("~/images/cover/"));
item.SaveAs(Path + Pic);
using (MemoryStream ms = new MemoryStream())
{
item.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
lstName.Add(Pic);
}
}
else
{
lstName.Add("9.jpg");
}
RContact.InsertContact(t, lstNam);
ViewBag.Style = "color:green;";
}
and I write in the Repository:
public bool InsertContact(tbl_contact t, List<string> PicsName)
{
db.tbl_contact.Add(t);
foreach (var item in PicsName)
{
t.picname = PicsName[0];
t.picnamet = PicsName[1];
t.picnametr = PicsName[2];
db.tbl_contact.Add(t);
}
return Convert.ToBoolean(db.SaveChanges());
}
but it save the same name.

Returning multiple Row using SqlConnection in web api

My Api:
public ConnectionStringSettings product;
public DbConnection connection1;
public DbCommand cdm1;
public void conn1(string a)
{
product = ConfigurationManager.ConnectionStrings["addConnection"];
connection1 = new SqlConnection();
connection1.ConnectionString = product.ConnectionString;
cdm1 = connection1.CreateCommand();
cdm1.CommandType = CommandType.Text;
cdm1.CommandText = a;
connection1.Open();
}
[Route("api/JobApi/BrowseJobs/")]
[HttpGet]
public object BrowseJobs()
{
string f = "";
try
{
conn1(string.Format("select * from FreelancerLogin"));
//select karim from UserPictures where username= karim
f = cdm1.ExecuteScalar().ToString();
}
catch (Exception ex)
{
f = ex.Message.ToString();
}
return f;
}
it returns single value like 21. But i want to return all row like the image and in json format to use in angularjs. How can i do that? Is there any other way to get my desired result?
you should use SqlDataReader and ExecuteReader method not execute scalar (execut sacal are for update, delete or insert = query with not return except key or valid result) like it:
SqlDataReader reader = cdm1.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();

android app development-passing parameter to database

I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/* */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}

cannot find symbol ActionListener and try catch

I have a problem w my applet: shortly speaking, I want to "take" the variable curreny which is taken from xml and print it when I click on the button OK. The error I get is: error: cannot find symbol curreny. The problem is not importing variable from xml, because I checked separately if it works.
Sorry for the messy code, I'm new to java. All the neccessary packages are imported in the original source, but i didnt put it here just to make the code shorter. EDIT: I deleted part of the code consisting GUI to make it shorter, as you suggested.
public class App2 extends Applet implements ActionListener {
TextField T1 = new TextField();
Label L1 = new Label();
/* GUI code here */
public void actionPerformed(ActionEvent ae)
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDocument = db.parse(new URL("http://www.nbp.pl/kursy/xml/LastA.xml").openStream());
xmlDocument.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/tabela_kursow/pozycja[3]/kurs_sredni";
// System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
// System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
String kurs_dolara = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_dolara = Double.parseDouble(kurs_dolara.replace(',', '.'));
System.out.println(d_kurs_dolara*6);
}
expression = "/tabela_kursow/pozycja[8]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_euro = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_euro = Double.parseDouble(kurs_euro.replace(',', '.'));
System.out.println(d_kurs_euro*6);
}
expression = "/tabela_kursow/pozycja[11]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_funta = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_funta = Double.parseDouble(kurs_funta.replace(',', '.'));
System.out.println(d_kurs_funta*6);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
String wynik = String.valueOf(d_kurs_euro);
L1.setText(wynik);
repaint();
}}

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

my error is simple but for me it is hard to fix it because my knowledge is not good . which is when i Enter the record by clicking the Addbutton of AddStudent record then the record that i deleted like record StudentID = 1, FirstName =Raju ,LastName=Abbasi
After Delete it again and press save Change even After that when i again try to use the ID=1 means enter the Record with ID=1 that i have been deleted and record the StudentID=1 ,FirstName =Ram ,LastName=Rakish .Then error is occur which is
private static SqlDataAdapter CreateSutdentDataAdapter()
{
string gettSQL = "SELECT * FROM Student";
string insertSQL = "SET IDENTITY_INSERT Student ON;INSERT INTO Student(StudentID, FirstName,LastName,Gender,GPA,MyImage)" +
"VALUES (#StudentID,#FirstName,#LastName,#Gender,#GPA,#MyImage);SET IDENTITY_INSERT Student OFF";
string updateSQL = "UPDATE Student SET FirstName=#FirstName,LastName=#LastName ,Gender=#Gender, MyImage=#MyImage," +
" GPA=#GPA WHERE StudentID=#StudentID";
string deleteSQL = "DELETE FROM Student WHERE StudentID=#StudentID";
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand(gettSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand = new SqlCommand(insertSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.InsertCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.InsertCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.InsertCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.UpdateCommand = new SqlCommand(updateSQL, ConnectionManager.GetConnection());
dataAdapter.UpdateCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.UpdateCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.UpdateCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.UpdateCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.UpdateCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.UpdateCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.DeleteCommand = new SqlCommand(deleteSQL, ConnectionManager.GetConnection());
dataAdapter.DeleteCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
return dataAdapter;
}
private static void DefinestudentTableSchema(DataTable table)
{
DataColumn StudentIDColumn = table.Columns.Add("StudentID", typeof(string));
StudentIDColumn.AllowDBNull = false;
table.PrimaryKey = new DataColumn[] { StudentIDColumn };
DataColumn StudentFirstName = table.Columns.Add("FirstName", typeof(string));
StudentFirstName.MaxLength = 150;
DataColumn StudentLastName = table.Columns.Add("LastName", typeof(string));
StudentLastName.MaxLength = 150;
DataColumn StudentGender = table.Columns.Add("Gender", typeof(string ));
DataColumn StudentGPA = table.Columns.Add("GPA", typeof(string ));
DataColumn StudentImage = table.Columns.Add("MyImage", typeof(Byte[]));
}
private static DataSet CreateStudentTrackerDataSet()
{
DataSet StudentTrackerDataSet = new DataSet();
DataTable StudentTable = StudentTrackerDataSet.Tables.Add("Student");
DefinestudentTableSchema(StudentTable);
return StudentTrackerDataSet;
}
public static DataSet GetData()
{
DataSet StudentTrakerDataSet = CreateStudentTrackerDataSet();
StudentTrakerDataSet.EnforceConstraints = false;
StudentDataAdapter.Fill(StudentTrakerDataSet.Tables["Student"]);
StudentTrakerDataSet.EnforceConstraints = true;
return StudentTrakerDataSet;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
public static void SaveData(ref DataSet changesDataSet)
{
DataSet addedDataSet = changesDataSet.GetChanges(DataRowState.Added);
if (addedDataSet != null)
{
StudentDataAdapter.Update(addedDataSet.Tables["Student"]);
changesDataSet.Merge(addedDataSet); // Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
}
DataSet modifiedDataSet = changesDataSet.GetChanges(DataRowState.Modified);
if (modifiedDataSet != null)
{
StudentDataAdapter.Update(modifiedDataSet.Tables["Student"]);
changesDataSet.Merge(modifiedDataSet);
}
DataSet deletedDataSet = changesDataSet.GetChanges(DataRowState.Deleted);
if (deletedDataSet != null)
{
StudentDataAdapter.Update(deletedDataSet.Tables["Student"]);
deletedDataSet.Merge(deletedDataSet);
}
here is my Addmodifyform logic for add the StudentID
public partial class AddModifyStudentRecords : Form
{
DataSet StudentTrackerDataSet;
DataRow currentRow;
public AddModifyStudentRecords()
{
InitializeComponent();
}
public AddModifyStudentRecords(DataSet ds)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = null;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = row;
textBox1.Text =currentRow["StudentID"] .ToString();
textBox2.Text = currentRow["FirstName"].ToString();
textBox4.Text = currentRow["LastName"].ToString();
textBox3.Text = currentRow["Gender"].ToString();
textBox5.Text = currentRow["GPA"].ToString();
txtBrowseFile.Text = currentRow["MyImage"].ToString ();
byte[] data = (byte[])currentRow ["MyImage"];
MemoryStream ms = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(ms);
string StudentID = textBox1.Text.ToString();
string StudentFirstName = textBox2.Text.ToString();
string StudentLastName = textBox4.Text.ToString();
string Gender = textBox3.Text.ToString();
string GPA = textBox5.Text.ToString();
Image MyImage = pictureBox1.Image;
DataTable table = StudentTrackerDataSet.Tables["Student"];
if (currentRow == null) {
currentRow = table.NewRow();
currentRow["StudentID"] = textBox1.Text.ToString();
table.Rows.Add(currentRow );
}
currentRow .BeginEdit();
currentRow ["StudentID" ]=StudentID ;
currentRow["FirstName"] = StudentFirstName;
currentRow["LastName"] = StudentLastName;
currentRow["Gender"] = Gender;
currentRow["GPA"] = GPA;
currentRow["MyImage"] = convertToByte(txtBrowseFile.Text);
currentRow.EndEdit();
Close();
}
public partial class AditStudent : Form
{
// Creat the Class variabl Dataset to track the Student
private DataSet StudentTrackerDataset;
public AditStudent()
{
InitializeComponent();
dataGridView1.DataError += DataGridView1_DataError;
StudentTrackerDataset = ProjectOfSchool.DataAccessLayer.DAC.GetData();
DataTable StudentTable = StudentTrackerDataset.Tables["Student"];
dataGridView1.DataSource = StudentTable;
//StudentTable.Columns["ID"].AutoIncrement = true;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
if (dataGridView1.Columns[i] is DataGridViewImageColumn)
{
((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}
}
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
string message = string.Format("Error in {0} columan in row {1}:{2}", e.ColumnIndex, e.RowIndex, e.Exception.Message);
MessageBox.Show(message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button1_Click(object sender, EventArgs e)
{
AddModifyStudentRecords AddStudent = new AddModifyStudentRecords(StudentTrackerDataset);
AddStudent.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow StudentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
AddModifyStudentRecords modifyStudent = new AddModifyStudentRecords(StudentTrackerDataset, StudentRow);
modifyStudent.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure", "Delete Current Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow currentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
currentRow.Delete();
}
}
private void button4_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Change to Save ", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
try
{
DataSet changesDateSet = StudentTrackerDataset.GetChanges();
ProjectOfSchool.DataAccessLayer.DAC.SaveData(ref changesDateSet);
StudentTrackerDataset.Merge(DAC.GetData());
MessageBox.Show("Data Save Successfully.", "Save Changes");
}
catch (SqlException ex)
{
MessageBox.Show("Data Not Saved:" + ex.Message, "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void button5_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Changes to Save.", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
DialogResult result = MessageBox .Show ("Are you Sure?","Reject Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes )
{
StudentTrackerDataset.RejectChanges();
}
}
}
And When i terminate the program and re execute the program then i saw that StudntID=1 is also save to Database with ID=1
or When i Delete the StudentID =1 and press save Change after press save Change when i also Terminate the program and re exicute the program and after that when i Enter the StudentID =1 Then no error is occur
And other way without termination is to Delete the record StudentID1 but when you Add the Student record but not Add the StudentID=1 But add the StudentID other then 1 in this case error is also not happend . Dear Sherik I have been solve my other error but i have still error which is in my Tittle So please responding me for this error And i re edited my code also So please replay me Thanks
I have record in my Database which have following Datatype as
StudentID=INT,
FirstName=VarChar,
LastName=VarChar,
Gender=Varchar,
GPA=Float,
MyImage=Vabinary (MAX)
Or may be Datarow fail to Delete the record or Update the record. I don't know please tell me and thanks to reply me and I am waiting for your reply.
The error message seems to indicate that you are hitting a Primary Key constraint.
I would suggest that you first stop allowing the user to enter the Student ID field. Let it be generated as an auto increment key in whatever database you are using. In Access, it is called AutoNumber.
Once you have done that, re test and post the results.

Resources