So I am trying to create a "TestClass" that basically holds onto my Matcher, actual results, error message, and test label.
However, I am slowly starting to realize this might not be possible but I feel like it should be.
Perhaps someone here can help.
Here is what I am trying to do:
public void runTest(){
Assert.assertThat(testLabel + " " + errorMessage, actualResult, testToRun);
}
or, since I am doing Selenium Tests, something like this:
public void runTestAsWebElement(String attributeToCheck){
Object tempActualResult;
switch (attributeToCheck.toLowerCase()){
case "isdisplayed()":
case "isdisplayed":
tempActualResult = ((WebElement) actualResult).isDisplayed();
break;
case "isselected":
case "isselected()":
tempActualResult = ((WebElement) actualResult).isSelected();
break;
case "isenabled":
case "isenabled()":
tempActualResult = ((WebElement) actualResult).isEnabled();
break;
case "text":
tempActualResult = ((WebElement) actualResult).getText();
break;
default:
tempActualResult = ((WebElement) actualResult).getAttribute(attributeToCheck);
}
Assert.assertThat(testLabel + " " + errorMessage, tempActualResult, testToRun);
}
However, I am wondering, will the matchers be able to figure out that the Actual Result is a String or Boolean? Or will it always fail since both objects are being compared as Objects, rather than strings (not sure how the underlying code would be executed).
Any advice on how to properly handle this situation would be much appreciated!
Just to give some context - I am currently writing code like this:
Switch(whatToTest){
case "eye portfolio tests":
customCheckErrorMessages.add("The Eye Portfolio header doesn't match expected user's value");
customCheckActualResults.add(eyePortfolioPage.eyePortfolioAccountHeader);
customCheckExpectedResults.add(holder);
customCheckTests.add(containsString(holder));
customTestAttributeToTest.add("text");
break;
//just showing what my step looks like
}
String actualResult = "";
for(int x = 0; x < customCheckErrorMessages.size(); x++){
try{
switch (customTestAttributeToTest.get(x)){
case "text":
actualResult = customCheckActualResults.get(x).getText();
break;
default:
actualResult = customCheckActualResults.get(x).getAttribute(customTestAttributeToTest.get(x));
break;
}
}catch (IndexOutOfBoundsException e){
//Assuming this field wasn't actually entered. Defaulting to getText
actualResult = customCheckActualResults.get(x).getText();
}
System.out.println("Additional Test #" + (x+1));
Assert.assertThat(customCheckErrorMessages.get(x) + " Expected: \"" + customCheckExpectedResults.get(x)
+ "\", Actual: \"" + customCheckActualResults.get(x).getText().trim(),
actualResult.trim(),
customCheckTests.get(x));
}
I would like to write code like this:
switch(whatIWantToTest){
case "transaction tests":
customTests.add(new TestClass("There should be at least one transaction appearing on the page", //error Message
"Looking For Transactions:", //Test Label
myOrdersPage.transactions.size(), //Actual Result
greaterThanOrEqualTo(1))); //Test to run (should contain expected result)
//Just showing what my step looks like
}
for (TestClass test : customTests){
test.runTest();
}
Here is the code I decided to use. If anyone has a better suggestion I would love to hear it :)
private String testType;
public String errorMessage, testAttribute;
public WebElement actualResult;
public List<WebElement> actualResults;
public String providedStringValue = null;
public Boolean providedBooleanValue = null;
public Matcher testToRun;
public int attempts = 1;
//Empty Constructor
public TestCase() {
errorMessage = "";
testType = "";
actualResult = null;
actualResults = null;
testToRun = null;
providedStringValue = null;
providedBooleanValue = null;
}
//Run Test as a String check
public TestCase(String errorMessage, String providedResult, Matcher testToRun){
this.errorMessage = errorMessage;
providedStringValue = providedResult;
testType = "String";
this.testToRun = testToRun;
}
//Run Test as a Boolean check
public TestCase(String errorMessage, Boolean providedResult, Matcher testToRun){
this.errorMessage = errorMessage;
providedBooleanValue = providedResult;
testType = "Boolean";
this.testToRun = testToRun;
}
//Run Test on a WebElement
public TestCase(String errorMessage, String testAttribute, WebElement actualResult, Matcher testToRun) {
this.errorMessage = errorMessage;
testType = "WebElement";
this.testAttribute = testAttribute;
this.actualResult = actualResult;
this.testToRun = testToRun;
}
//Run Test on a List<WebElement>
public TestCase(String errorMessage, String testAttribute, List<WebElement> actualResults, Matcher testToRun) {
this.errorMessage = errorMessage;
testType = "List";
this.testAttribute = testAttribute;
this.actualResults = actualResults;
this.testToRun = testToRun;
}
public void clearTest() {
errorMessage = "";
testType = "";
testAttribute = "";
actualResult = null;
actualResults = null;
testToRun = null;
providedStringValue = null;
providedBooleanValue = null;
}
public void runTest() {
try {
if (testType.equalsIgnoreCase("WebElement")) {
runTestAsWebElement(testAttribute);
} else if (testType.equalsIgnoreCase("List")) {
runTestAsList(testAttribute);
} else if(testType.equalsIgnoreCase("Boolean")){
runTestAsBooleanCheck();
} else if(testType.equalsIgnoreCase("String")){
runTestAsStringCheck();
} else {
Assert.fail("Don't know how to run this test type");
}
} catch (StaleElementReferenceException e) {
if (attempts < 5) {
System.out.println("StaleElementReferenceException - Running test again");
attempts++;
runTest();
return;
} else {
throw e;
}
}
attempts = 1;
}
private void runTestAsStringCheck(){
Assert.assertThat(errorMessage, providedStringValue, testToRun);
}
private void runTestAsBooleanCheck(){
Assert.assertThat(errorMessage, providedBooleanValue, testToRun);
}
//Sometimes the actualResult is a WebElement which means the value to check is wrapped within another value.
private void runTestAsWebElement(String attributeToCheck) {
Object actualResultHolder;
switch (attributeToCheck.toLowerCase()) {
case "exists":
case "present":
try{
actualResult.isDisplayed(); //Forcing WebElement to look for element. If throws exception, element not found
actualResultHolder = true;
} catch (NoSuchElementException e){
actualResultHolder = false;
}
break;
case"display":
case "displayed":
case "isdisplayed()":
case "isdisplayed":
try{
actualResultHolder = actualResult.isDisplayed();
} catch (NoSuchElementException e){
System.out.println("Element not found");
throw e;
//actualResultHolder = false;
}
break;
case "selected":
case "isselected":
case "isselected()":
actualResultHolder = actualResult.isSelected();
break;
case "enabled":
case "isenabled":
case "isenabled()":
actualResultHolder = actualResult.isEnabled();
break;
case "text":
actualResultHolder = actualResult.getText().trim();
break;
default:
if (attributeToCheck.contains("css: ")) {//In case we want to test the css attribute instead of the HTML attribute
attributeToCheck = attributeToCheck.split("css: ")[1];
actualResultHolder = actualResult.getCssValue(attributeToCheck);
} else {
actualResultHolder = actualResult.getAttribute(attributeToCheck);
}
}
Assert.assertThat(errorMessage + "\n Actual Result = \"" + actualResultHolder + "\" ", actualResultHolder, testToRun);
}
private void runTestAsList(String attributeToCheck) {
switch (attributeToCheck.toLowerCase()) {
case "size":
case "size()":
Assert.assertThat(errorMessage, actualResults.size(), testToRun);
break;
default:
//do nothing - Test has to do with the list of elements.
Assert.assertThat(errorMessage, actualResults, testToRun);
}
}
Then, if for whatever reason I need some other type of test I just add it to the class.
Related
I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....
I am trying to print a json response response in a recyclerview. my Recyclerview is like a expanded listView. And my json resone is like this:
{"Table1":
[
{"filedate":"Oct 26, 2016"},
{"filedate":"Oct 18, 2016"}
],
"Table2":
[{
"filedate":"Oct 18, 2016",
"file1":"12.txt"
},
{
"filedate":"Oct 26, 2016",
"file1":"acerinvoice.pdf"
}
]}
and I trying to print this json resonse using this code:
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
//I think problrm is here
#Override
public void onResponse(String response) {
try {
**JSONObject object = new JSONObject(response);
JSONArray jsonarray = object.getJSONArray("Table1");
JSONArray jsonarray1 = object.getJSONArray("Table2");
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
String str = obj.optString("filedate").trim();
int lth = jsonarray1.length();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();**
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
Toast.makeText(getApplicationContext(), (CharSequence) data, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
ExpandableListAdapter
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
TextView itemTextView = new TextView(context);
itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
itemTextView.setTextColor(0x88000000);
itemTextView.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerView.ViewHolder(itemTextView) {
};
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
TextView itemTextView = (TextView) holder.itemView;
itemTextView.setText(data.get(position).text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
But this code print nothing in my recycler UI.It show only a empty layout.I have also tried to print the response in my log and it prints whole response together.I want to print table1 contents in headers and table2 contents in as child(items) with their respective headers.how to do this?If any other information needed please ask..
You should probably check your response first of everything. As per your requirements you should use HashMap and ArrayList. Follow these following steps:
1.Take a ArrayLsit and store child data of 1st heading and so on with index starting from 0.
2.Store headers in HashMap as key.
ex: HashMap<String,ArrayList<Data>> hm;
hm.put("your first heading string","related arraylist");
Then use ExpandableListView to arrange parent and child items.
please check your json response this is invalid json response first try to validate your json formate after try to decode and add in recycler view.
Check Your Response into Logcat also the Exception. I've tested the Response you've supplied that contains some unnecessary "," that may cause the Exception.
I have solve my problem to just change above code like this..
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
try {
jsonarray = object.getJSONArray("Table1");
jsonarray1 = object.getJSONArray("Table1");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
//
String str = obj.optString("filedate").trim();
Log.d("test", str);
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
// Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
String str3 = obj1.optString("category").trim();
String str2 = obj1.optString("file1").trim();
String str4 = obj1.optString("4").trim();
Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
if (str == str1) {
// data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str3));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));
}
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapterheader.notifyDataSetChanged();
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
I am trying to fetch the resultsetmeta data using Spring jdbc template. It works fine if there is atleast one row returned.
The problem arises when there is no rows returned i.e. an empty resultSet.
I have tried a lot and still stuck up with the same. If there is any solution to this, please help me with this.
Also, I found ResultSetWrappingSqlRowSetMetaData class in spring. Is this of some use in my context?
Thanks for the help.
Finally I found the answer to my question. Below is the code:
template.query(builder.toString(),new ResultSetExtractor<Integer>() {
#Override
public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i = 1 ; i <= columnCount ; i++){
SQLColumn column = new SQLColumn();
column.setName(rsmd.getColumnName(i));
column.setAutoIncrement(rsmd.isAutoIncrement(i));
column.setType(rsmd.getColumnTypeName(i));
column.setTypeCode(rsmd.getColumnType(i));
column.setTableName(sqlTable.getName().toUpperCase());
columns.add(column);
}
return columnCount;
}
});
For a detailed explanation you can visit here
You can also use JdbcUtils
#SuppressWarnings("unchecked")
public static List<TableColumnTypeMap> getTableColumns(DataSource dataSource,
String tableName) {
try {
return (List<TableColumnTypeMap>) JdbcUtils.extractDatabaseMetaData(dataSource,
new DatabaseMetaDataCallback() {
#Override
public Object processMetaData(DatabaseMetaData dbmd)
throws SQLException, MetaDataAccessException {
ResultSet rs = dbmd
.getColumns("", "%", tableName + "%", null);
List<TableColumnTypeMap> list = new ArrayList();
while (rs.next()) {
String tableCat = rs.getString("TABLE_CAT");
String tableSchem = rs.getString("TABLE_SCHEM");
String tableName = rs.getString("TABLE_NAME");
String columnName = rs.getString("COLUMN_NAME");
String typeName = rs.getString("TYPE_NAME");
String columnSize = rs.getString("COLUMN_SIZE");
String nullable = rs.getString("NULLABLE");
String remarks = rs.getString("REMARKS");
int dataType = rs.getInt("DATA_TYPE");
System.out.println(tableName);
TableColumnTypeMap tableColumnTypeMap = new TableColumnTypeMap()
.setColumnName(columnName)
.setColumnType(typeName)
.setJavaClassName(getColumnCLassName(dataType))
.setRemarks(remarks);
list.add(tableColumnTypeMap);
}
return list;
}
});
} catch (MetaDataAccessException ex) {
throw new RuntimeException("get table list failed", ex);
}
}
for java class map:
private static String getColumnCLassName(int sqlType) {
String className = String.class.getName();
switch (sqlType) {
case Types.NUMERIC:
case Types.DECIMAL:
className = java.math.BigDecimal.class.getName();
break;
case Types.BIT:
className = java.lang.Boolean.class.getName();
break;
case Types.TINYINT:
className = java.lang.Byte.class.getName();
break;
case Types.SMALLINT:
className = java.lang.Short.class.getName();
break;
case Types.INTEGER:
className = java.lang.Integer.class.getName();
break;
case Types.BIGINT:
className = java.lang.Long.class.getName();
break;
case Types.REAL:
className = java.lang.Float.class.getName();
break;
case Types.FLOAT:
case Types.DOUBLE:
className = java.lang.Double.class.getName();
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
className = "byte[]";
break;
case Types.DATE:
className = java.sql.Date.class.getName();
break;
case Types.TIME:
className = java.sql.Time.class.getName();
break;
case Types.TIMESTAMP:
className = java.sql.Timestamp.class.getName();
break;
case Types.BLOB:
className = java.sql.Blob.class.getName();
break;
case Types.CLOB:
className = java.sql.Clob.class.getName();
break;
default:
break;
}
return className;
}
for result class
/**
* #author ryan
* #date 19-7-15 下午6:05
*/
#Data
#Accessors(chain = true)
public class TableColumnTypeMap {
private String columnName;
private String columnType;
private String javaClassName;
private String remarks;
}
I have a piece of software out in the field and I need to add a new table to it. I have the table in my entity framework and new clients get the table. How to I update the others?
ADDED: To make it clear my development and new clients have the table. How to update the older clients databases is the question?
Since it is in my model it seems I should just call a create method and everything should happen under the hood.
_context.NewTable.CreateTable();
But think that I will have to write a sql command string to see if table exists and if it doesn't to create the table.
IDVisitorEntities _context = new IDVisitorEntities ();
String cmd = IF NOT EXISTS ( SELECT [name]
FROM sys.tables
WHERE [name] = NewTable )
CREATE TABLE NewTable (
ID int IDENITY,
NAME VARCHAR(40))
_context.NewTable.CommandText (cmd);
I want to only run this one time if the table doesn't exist. So that doesn't solve that problem. I really don't know what to do.
ADDED 5/6/2013
I'm thinking that EF has the Property Collection for each table and that might hold a clue. Might have to use ICustomTypeDescriptor ... Anyone else have any thoughts?
Added 7/15/2013
I started building it, at my new job, here is a sample. I need to create a file(s) with the partial classes and have the abstract and interface applied to them. It has a long way to go but this is a start...
namespace DataModelMAXFM
{
public abstract class ATable
{
private ArrayList _columns = new ArrayList();
private ArrayList colsToAdd = new ArrayList();
public ArrayList Columns
{
get
{
return _columns;
}
}
public bool TableCreate(SqlConnection sqlConn)
{
//assuming table needs to be created (already checked)
//get column list
//use for loop to create query string
// run command
ITable thisItable;
if (Columns.Count <= 0) //generate column list if not already created
{
if (!ColumnList())
return false;
}
if (this is ITable)
{
thisItable = (ITable) this;
}
else
{
throw new Exception("");
}
StringBuilder sb = new StringBuilder("CREATE TABLE " + thisItable.GetTableName() + " (");
bool flgFirst = true; // to allow for proper comma placement
foreach (PropertyInfo prop in Columns)
{
String propType = this.GetDataType(prop);
if (propType == String.Empty)//check to make sure datatype found a match, EF to SQL
{
return false;
}
if (!flgFirst)
{
sb.Append(", ");
}
else
{
flgFirst = false;
}
sb.Append(prop.Name + " " + propType);
}
// add right parentheses
sb.Append(")");
//now run query created above
SqlCommand com;
try
{
com = new SqlCommand(sb.ToString(), sqlConn);
com.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine("TableCreate e:" + e.ToString());
return false;
}
return true;
}
public bool TableExists(SqlConnection sqlConn)
{
SqlDataReader sdr = null;
SqlCommand com;
ITable thisItable;
try
{
//create and execute command
if (this is ITable)
thisItable = (ITable)this;
else
{
throw new Exception("");
}
com = new SqlCommand("Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = " + thisItable.GetTableName(), sqlConn);
sdr = com.ExecuteReader();
if (!sdr.HasRows)//ie table does not exist
{
return false;
}
}
catch (Exception e)
{
Console.WriteLine("TableCreate e:" + e.ToString());
return false;
}
//close datareader
try
{
sdr.Close();
}
catch (Exception e)
{
Console.WriteLine("close sqldatareader TableExists e: " + e.ToString());
}
return true;
}
public bool ColumnList()
{
bool flgListCreated = false;
PropertyInfo[] propList = typeof(TransactionCategory).GetProperties();
foreach (PropertyInfo prop in propList)
{
if (prop.CanRead && prop.CanWrite)
{
MethodInfo mget = prop.GetGetMethod(false);
MethodInfo mset = prop.GetSetMethod(false);
// Get and set methods have to be public
if (mget == null)
{
continue;
}
if (mset == null)
{
continue;
}
Columns.Add(prop);
if (!flgListCreated)
{
flgListCreated = true;
}
}
}
return flgListCreated;
}
public bool ColumnsExist(SqlConnection sqlConn)
{
ITable thisItable;
if (Columns.Count <= 0)
{
if (!ColumnList())
return false;
}
//2013-07-10 create basic connection and data reader
if (this is ITable)
thisItable = (ITable)this;
else
{
throw new Exception("");
}
SqlDataReader sdr = null;
SqlCommand com;
foreach (PropertyInfo prop in Columns)
{
try
{
//create and execute command
com = new SqlCommand("Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = " + thisItable.GetTableName() + " and COLUMN_NAME = " + prop.Name, sqlConn);
sdr = com.ExecuteReader();
//if no rows returned to datareader == column does not exist, add to ArrayList of columns to add
if (!sdr.HasRows)
colsToAdd.Add(prop);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
}
//close datareader
try
{
sdr.Close();
}
catch (Exception e)
{
Console.WriteLine("close sqldatareader ColumnsExist e: " + e.ToString());
}
if (colsToAdd.Count == 0)
return false;
//returns true only if method worked and found columns to add to DB
return true;
}
public bool ColumnsCreate(SqlConnection sqlConn)
{
ITable thisItable;
StringBuilder sb = new StringBuilder();
if (colsToAdd.Count <= 0)
{
if (!ColumnsExist(sqlConn)) //2013-07-08 - MAXIMUS\58398(BJH) //if no columns, attempt to create list
return false; // if Column list was not created, return false
}
// add a array of the alter table
if (this is ITable)
thisItable = (ITable)this;
else
{
throw new Exception();
}
sb.Append("ALTER TABLE " + thisItable.GetTableName() + " ADD ( ");
bool flgFirst = true; // allows for no leading comma on first entry
String propType;
foreach (PropertyInfo prop in colsToAdd)
{
//make sure SQL datatype can be determined from EF data
propType = this.GetDataType(prop);
if (propType == String.Empty)
throw new Exception("no datatype match found " + prop.Name + " " + prop.PropertyType.ToString());
if (!flgFirst)
{
sb.Append(", ");
}
else
{
flgFirst = false;
}
sb.Append(prop.Name + " " + propType);
}
sb.Append(" )");
SqlCommand com;
try
{
com = new SqlCommand(sb.ToString(), sqlConn);
com.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
return true;
}
public bool ColumnsUpdate(SqlConnection sqlConn)
{
if (ColumnsExist(sqlConn))
return ColumnsCreate(sqlConn);
else
return false;
}
//method to convert from EF to SQL datatypes, see noted issues
public String GetDataType(PropertyInfo pi)
{
String s = "";
String pistr = pi.PropertyType.ToString();
switch (pistr)
{
case "Byte[]":
s = "binary";
break;
case "Boolean":
s = "bit";
break;
case "String Char[]": // also maps to other options such as nchar, ntext, nvarchar, text, varchar
s = "char";
break;
case "DateTime":
s = "datetime";
break;
case "DateTimeOffset":
s = "datetimeoffset";
break;
case "Decimal":
s = "decimal";
break;
case "Double":
s = "float";
break;
case "Int16":
s = "smallint";
break;
case "Int32":
s = "int";
break;
case "Int64":
s = "bigint";
break;
case "Single":
s = "real";
break;
case "TimeSpan":
s = "time";
break;
case "Byte":
s = "tinyint";
break;
case "Guid":
s = "uniqueidentifier";
break;
case "Xml":
s = "xml";
break;
default:
Console.WriteLine("No datatype match found for " + pi.ToString() + " " + pi.PropertyType.ToString());
return String.Empty;
}
return s;
}
}
public interface ITable
{
int ID
{
get;
}
bool TableUpdate(SqlConnection sqlConn);
bool TableStoredProceduresCreate(SqlConnection sqlConn);
bool TableStoredProceduresDrop(SqlConnection sqlConn);
bool TableCreateTriggers(SqlConnection sqlConn);
bool TableCreateViews(SqlConnection sqlConn);
DataTable GetDataTable();
DateTime dtTableImplemented
{
get;
}
String GetTableName();
}
}
How to I update the others?
And how do you upgrade code of others to require that table? Probably by using some patch or upgrade package and this package should create your table as well.
Since it is in my model it seems I should just call a create method and everything should happen under the hood.
No. EF itself has nothing to define database schema (Except creating SQL script for whole database creation). What you are looking for is possible with EF Migrations but that is feature of EF 4.3 and newer when using code first and DbContext API.
I'm trying to figure out how to write a custom FindElement routine in Selenium 2.0 WebDriver. The idea would be something like this:
driver.FindElement(By.Method( (ISearchContext) => {
/* examine search context logic here... */ }));
The anonymous method would examine the ISearchContext and return True if it matches; False otherwise.
I'm digging through the Selenium code, and getting a bit lost. It looks like the actual By.* logic is carried out server-side, not client side. That seems to be complicating matters.
Any suggestions?
I do a multi-staged search. I have a method that performs a try catch and then a method that gets the element. In theory you could do a try catch until instead of this way but I like this way better because of my setup.
public bool CheckUntil(IWebDriver driver, string selectorType, string selectorInfo)
{
int Timer = 160;
bool itemFound = false;
for (int i = 0; i < Timer; i++)
if(itemFound)
{
i = 0
}
else
{
Thread.Sleep(500);
if(selectorType.ToLower() == "id" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.Id(selectorInfo).Displayed)
{
itemFound = true;
}
}
else if(selectorType.ToLower() == "tagname" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.TagName(selectorInfo).Displayed)
{
itemFound = true;
}
}
}
return itemFound;
}
Here's my try catch method you can add as many different types as you want id, cssselector, xpath, tagname, classname, etc.
public bool TryCatch(IWebDriver driver, string selectorType, string selectorInfo)
{
bool ElementFound = false;
try
{
switch(selectorType)
{
case "id":
driver.FindElement(By.Id(selectorInfo);
break;
case "tagname":
driver.FindElement(By.TagName(selectorInfo);
break;
}
ElementFound = truel
}
catch
{
ElementFound = false;
}
return ElementFound;
}
Ok, I figured out how to do this. I'm leveraging driver.ExecuteScript() to run custom js on the webdriver. It looks a bit like this:
function elementFound(elem) {
var nodeType = navigator.appName == ""Microsoft Internet
Explorer"" ? document.ELEMENT_NODE : Node.ELEMENT_NODE;
if(elem.nodeType == nodeType)
{
/* Element identification logic here */
}
else { return false; }
}
function traverseElement(elem) {
if (elementFound(elem) == true) {
return elem;
}
else {
for (var i = 0; i < elem.childNodes.length; i++) {
var ret = traverseElement(elem.childNodes[i]);
if(ret != null) { return ret; }
}
}
}
return traverseElement(document);