Adding dynamic values in an input box using watin for a web based application - watin

I am working on a web based application which takes care of online orders placed by customers .
we are using watin for sanity.This is what my code reads
mybrowser.TextField(Find.ByName("searchBox")).Value = "milk";
mybrowser.Image(Find.ByName("search")).Click();
In the input field i want to add any string value(e.g meat/bakery) of X length
Please help

As I read your question you want to be able to generate and input a string of a specific, given length X. Here is some code I wrote a while ago for that.
public static string GetRandomString(int length)
{
StringBuilder randomString = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i < length; i++)
{
randomString.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * randomNumber.NextDouble() + 65))));
}
return randomString.ToString();
}
If you want to pick from a specific list of items I would use code like this
public static string GenerateRandomFood()
{
string[] foods = {"Bread", "Cheese", "Milk", };
// There are 3 food names
return foods[GetRandomInt(0, 2)];
}
Hope that is what you are after.

Related

Getting path of ArrayList<image> that is already set and convert to string

My program creates a "Deck" of cards in a List, I want to be able to get the image, find the path to parse it to get the information that is in the image name.
For this, I am using an ArrayList to store the cards.
List<Image> mainDeck = new ArrayList<Image>();
To load the image, I am using this code
public List load(List<Image> newDeck) {
count = 0;
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 10; k++) {
newDeck.add(new Image("images/" + prefix.get(i) + "" + (k + 1) + ".png"));
count++;
}// end number card for loop
for (int l = 0; l < 3; l++) {
newDeck.add(new Image("images/" + prefix.get(l) + "" + prefixFace.get(l) + ".png"));
count++;
}// end face card for loop
}// end deck for loop
it then gets called and populated with images that work perfectly, I would like to create a matching array filled with Strings that hold the path for the matching Image array.
The names of images are "c1.png", "c2.png", etc, and I just need the number in the pathname
Once I get the array I should be able to parse the data to get the numbers.
Any help would be much appreciated.
when using get url, I am getting an error, here is that code
for (Image card : mainDeck){
String path = card.getUrl();
String name = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));
nameData.put(card, name);
it is not recognizing card.getUrl();
you don't have to create another arrayList for the paths cause the path data is already saved with the images.
if you want to retrieve the path of an image after creating it then you might use the method getUrl() in the Image class, calling getUrl() from an Image object will return the path that you used to create the image when you called the constructor, note that it will only work if you called the Image constructor using a String as the path for the image, it will not work if you used an inputStream to initialize your image, and also that it was defined in java 9, after getting the path you might split it to get the useful data you want, something like
Image image = new Image("file:/C:/Users/zinou/Desktop/edit.png");
String path = image.getUrl();
String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
System.out.println(name);
and if i were to associate every card with its path, i would use a hashMap as in
List<Image> mainDeck = new ArrayList<Image>();
//population of the list
HashMap<Image, String> nameData = new HashMap<Image, String>();
for (Image card : mainDeck) {
String path = card.getUrl();
String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
nameData.put(card, name);
}
If you have java 8
you can create a class that extends the Image class and give it an additional attribute (the URL), and add a getter for the URL so you can access it, but then your cards will be instances of the new class you created, so you can get the URL for them, the new class may look like this
public class MyImage extends javafx.scene.image.Image{
String url;
public MyImage(String arg0) {
super(arg0);
url = arg0;
}
public String geturl() {
return url;
}
}

Buffer with other publisher - Spring reactor

Can anyone give an example of how Flux.buffer(Publisher other) works, im unable to make use of the other publisher to split the original flux into multiple lists.
Ex:
List<String> strings = new ArrayList<>();
strings.add("A");
strings.add("B");
Flux<String> stringFlux = Flux.fromIterable(strings).cache();
for(int i = 0; i < 100; i++) {
strings.add(""+i);
}
List<Integer> integers = new ArrayList<>(2);
integers.add(1);
integers.add(1);
integers.add(1);
stringFlux.buffer((a) -> {
Flux.fromIterable(integers);
}).subscribe(a -> {
System.out.println(a);
});
this still prints the original list as the output rather than split it.
bufferuntil with a predicate is actually what i was looking for.

Dynamically choose which properties to get using Linq

I have an MVC application with a dynamic table on one of the pages, which the users defines how many columns the table has, the columns order and where to get the data from for each field.
I have written some very bad code in order to keep it dynamic and now I would like it to be more efficient.
My problem is that I don't know how to define the columns I should get back into my IEnumerable on runtime. My main issue is that I don't know how many columns I might have.
I have a reference to a class which gets the field's text. I also have a dictionary of each field's order with the exact property It should get the data from.
My code should look something like that:
var docsRes3 = from d in docs
select new[]
{
for (int i=0; i<numOfCols; i++)
{
gen.getFieldText(d, res.FieldSourceDic[i]);
}
};
where:
docs = List from which I would like to get only specific fields
res.FieldSourceDic = Dictionary in which the key is the order of the column and the value is the property
gen.getFieldText = The function which gets the entity and the property and returns the value
Obviously, it doesn't work.
I also tried
StringBuilder fieldsSB = new StringBuilder();
for (int i = 0; i < numOfCols; i++)
{
string field = "d." + res.FieldSourceDic[i] + ".ToString()";
if (!string.IsNullOrEmpty(fieldsSB.ToString()))
{
fieldsSB.Append(",");
}
fieldsSB.Append(field);
}
var docsRes2 = from d in docs
select new[] { fieldsSB.ToString() };
It also didn't work.
The only thing that worked for me so far was:
List<string[]> docsRes = new List<string[]>();
foreach (NewOriginDocumentManagment d in docs)
{
string[] row = new string[numOfCols];
for (int i = 0; i < numOfCols; i++)
{
row[i] = gen.getFieldText(d, res.FieldSourceDic[i]);
}
docsRes.Add(row);
}
Any idea how can I pass the linq the list of fields and it'll cut the needed data out of it efficiently?
Thanks, Hoe I was clear about what I need....
Try following:
var docsRes3 = from d in docs
select (
from k in res.FieldSourceDic.Keys.Take(numOfCols)
select gen.getFieldText(d, res.FieldSourceDic[k]));
I got my answer with some help from the following link:
http://www.codeproject.com/Questions/141367/Dynamic-Columns-from-List-using-LINQ
First I created a string array of all properties:
//Creats a string of all properties as defined in the XML
//Columns order must be started at 0. No skips are allowed
StringBuilder fieldsSB = new StringBuilder();
for (int i = 0; i < numOfCols; i++)
{
string field = res.FieldSourceDic[i];
if (!string.IsNullOrEmpty(fieldsSB.ToString()))
{
fieldsSB.Append(",");
}
fieldsSB.Append(field);
}
var cols = fieldsSB.ToString().Split(',');
//Gets the data for each row dynamically
var docsRes = docs.Select(d => GetProps(d, cols));
than I created the GetProps function, which is using my own function as described in the question:
private static dynamic GetProps(object d, IEnumerable<string> props)
{
if (d == null)
{
return null;
}
DynamicGridGenerator gen = new DynamicGridGenerator();
List<string> res = new List<string>();
foreach (var p in props)
{
res.Add(gen.getFieldText(d, p));
}
return res;
}

Jqgrid search results pagination with Spring 3.0

I have several jqgrids running and all are functioning fine. However, when I do a search, I am only displaying ten search results per page. Whenever there are more than ten results, clicking on page two has no effect on the grid. Here is one of my controller actions, pay particular attention to the if satatement where search is true....
EDIT
I think I may have found a clue as to what may be causing my issue. You see I have several subgrids under the main grid. In terms of my java code I have object-A which has a list of object-B
, thus A has a subgrid of B. The way i am building up the json string to feed to the grid is by iterating over the list of B contained in A. I did not write a query of some kind to say order by, and limit the results etc.
So i guess the real question should be how to build a finder on a collection so that the contents can be arranged and ordered as i wish?
Here is the action I am calling for one of my entities described as B above. Pay particular attention to where i said person.getContacts()
#RequestMapping(value = "contactjsondata/{pId}", method = RequestMethod.GET)
public #ResponseBody String contactjsondata(#PathVariable("pId") Long personId, Model uiModel, HttpServletRequest httpServletRequest) {
Person person = Person.findPerson(personId);
String column = "id";
if(httpServletRequest.getParameter("sidx") != null){
column = httpServletRequest.getParameter("sidx");
}
String orderType = "DESC";
if(httpServletRequest.getParameter("sord") != null){
orderType = httpServletRequest.getParameter("sord").toUpperCase();
}
int page = 1;
if(Integer.parseInt(httpServletRequest.getParameter("page")) >= 1){
page = Integer.parseInt(httpServletRequest.getParameter("page"));
}
int limitAmount = 10;
int limitStart = limitAmount*page - limitAmount;
List<Contact> contacts = new ArrayList<Contact>(person.getContacts());
double tally = Math.ceil(contacts.size()/10.0d);
int totalPages = (int)tally;
int records = contacts.size();
StringBuilder sb = new StringBuilder();
sb.append("{\"page\":\"").append(page).append("\", \"records\":\"").append(records).append("\", \"total\":\"").append(totalPages).append("\", \"rows\":[");
boolean first = true;
for (Contact c: contacts) {
sb.append(first ? "" : ",");
if (first) {
first = false;
}
sb.append(String.format("{\"id\":\"%s\", \"cell\":[\"%s\", \"%s\", \"%s\"]}",c.getId(), c.getId(), c.getContactType().getName() ,c.getContactValue()));
}
sb.append("]}");
return sb.toString();
}
To fix the issue with pagination you need to replace the following block of code
for (Contact c: contacts) {
sb.append(first ? "" : ",");
if (first) {
first = false;
}
sb.append(String.format("{\"id\":\"%s\", \"cell\":[\"%s\", \"%s\", \"%s\"]}",c.getId(), c.getId(), c.getContactType().getName() ,c.getContactValue()));
}
with:
for (int i=limitStart; i<Math.min(records, limitStart+limitAmount); i++){
Contact c = contacts[i];
sb.append(first ? "" : ",");
if (first) {
first = false;
}
sb.append(String.format("{\"id\":\"%s\", \"cell\":[\"%s\", \"%s\", \"%s\"]}",c.getId(), c.getId(), c.getContactType().getName() ,c.getContactValue()));
}
Another option is using loadonce:true to let the jqGrid handle pagination and sorting. In this case you don't need to make changes described above

linq select a random row

I have a table called Quotes in linq-to-sql that contains 2 columns: author and quote. How do you select both columns of a random row?
Random rand = new Random();
int toSkip = rand.Next(0, context.Quotes.Count);
context.Quotes.Skip(toSkip).Take(1).First();
If you're doing Linq-to-Objects and don't need this to work on SQL, you can use ElementAt() instead of the more verbose Skip(toSkip).Take(1).First() :
var rndGen = new Random(); // do this only once in your app/class/IoC container
int random = rndGen.Next(0, context.Quotes.Count);
context.Quotes.ElementAt(random);
I did it something like this:
list.ElementAt(rand.Next(list.Count());
I stuck a bunch of random operations, including select and shuffle, as extension methods. This makes them available just like all the other collection extension methods.
You can see my code in the article Extending LINQ with Random Operations.
Here is one way to achieve what you want to do:
var quotes = from q in dataContext.Quotes select q;
int count = quotes.Count();
int index = new Random().Next(count);
var randomQuote = quotes.Skip(index).FirstOrDefault();
try it:
list.OrderBy(x => Guid.NewGuid()).Take(1).first();
1 First create a class with rend property
public class tbl_EmpJobDetailsEntity
{
public int JpId { get; set; }
public int rend
{
get
{
Random rnd = new Random();
return rnd.Next(1, 100);
}
}
}
2 Linq query
var rendomise = (from v in db.tbl_EmpJobDetails
select new tbl_EmpJobDetailsEntity
{
JpId=v.JpId
}).OrderBy(o=>o.rend);

Resources