How to clear text field before sending new text values in Serenity - serenity-bdd

#When("{actor} adds/edits (new )user in (his) contact list")
public void contact_add_new_user_in_contact_list(Actor actor, DataTable dataTable) {
Map<String, String> data = dataTable.asMaps().get(0);
actor.attemptsTo(AddContacts.fromDte(data.get("FirstName"), data.get("LastName"),
data.get("Email"), data.get("Phone")));
actor.attemptsTo(Click.on(ContactModal.SAVE_BUTTON.waitingForNoMoreThan(
Duration.ofSeconds(10))));
}
So Here I want to clear previously present data in the form field before sending new values.

try this _actor.AttemptsTo(Clear.On(FormFieldLocator.locatorObject));

Related

How to display external image to rdlc report using AspNetCore.Reporting?

I am trying to display a web requested image in a rdlc report.
What I've done so far:
In Report Designer, set the image source property of the image to 'External' in Report Designer.
In Report Desginer, set the image value using the following expression:
="https://localhost:7015/api/imagens/" & Fields!AsignadoA.Value
In my controller, set 'EnableExternalImages' property of the local report object to true; this I've done
using the following code since said property is not accessible through the object:
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
FieldInfo field = localReport.GetType().GetField("localReport", bindFlags);
object rptObj = field.GetValue(localReport);
Type type = rptObj.GetType();
PropertyInfo pi = type.GetProperty("EnableExternalImages");
pi.SetValue(rptObj, true, null);
Then next error appears:
An unhandled exception occurred while processing the request.
KeyNotFoundException: The given key 'InvalidImage' was not present in the dictionary.
System.Collections.Generic.Dictionary<TKey, TValue>.get_Item(TKey key)
ITInventory.Server.Controllers.EquiposController.Get(string nombre) in EquiposController.cs
var result = localReport.Execute(RenderType.Pdf,1, parametros);
I understand maybe I had to add a parameter called 'InvalidImage' and pass it to the local report, so I did this:
In Report Designer, I added a new parameter called 'InvalidImage'
In my controller, I added the parameter to a dictionary
Dictionary<string, string> parametros = new Dictionary<string, string>();
parametros.Add("InvalidImage", "x");
var result = localReport.Execute(RenderType.Pdf,1, parametros);
I don't get the concept of 'InvalidImage' in this context, so I just assigned it a random value ("x"), expecting a new error message would give more clues.
Still, I'm getting the same error: The given key 'InvalidImage' was not present in the dictionary.
Is there anything I'm missing?
Thank you in advance for the answers.
This solution have been working with me to display an image in a rdlc report using AspNetCore.Reporting, the solution is converting the image to Base64 string and then passing this string to DataSource field (or parameter) and using this field in the report image.
These are the steps:
Converting image to base64 string
public static string ConvertImageToBase64String(string imagePath)
{
string result = null;
if (!string.IsNullOrEmpty(imagePath))
{
using (var b = new Bitmap(imagePath))
{
using (var ms = new MemoryStream())
{
b.Save(ms, ImageFormat.Bmp);
result = Convert.ToBase64String(ms.ToArray());
}
}
}
return result;
}
Passing this string to a DataSource field (or a parameter)
string logoPath = _webHostEnvironment.WebRootPath + "\\Photos\\CompanyLogo.jpeg";
var dataSource = shippingOrders.Select(x => new ShippingOrderCarrierFileVM()
{
CompanyName = _configuration.GetValue<string>("Company:Name"),
CompanyLogo = ConvertImageToBase64String(logoPath),
OrderNumber = x.OrderNumber,
ClientName = x.ClientName,
}
using this field in report image
If you are using a web requested image as you have mentioned, you can use this code to convert it to stream and pass this stream to the Bitmap function, it accept a stream also
//Convrting image URL to a stream
System.Net.WebRequest request = System.Net.WebRequest.Create(URL);
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
using (var b = new Bitmap(responseStream))
{...

Apache Beam : Transform an objects having a list of objects to multiple TableRows to write to BigQuery

I am working on a beam pipeline to process a json and write it to bigquery. The JSON is like this.
{
"message": [{
"name": "abc",
"itemId": "2123",
"itemName": "test"
}, {
"name": "vfg",
"itemId": "56457",
"itemName": "Chicken"
}],
"publishDate": "2017-10-26T04:54:16.207Z"
}
I parse this using Jackson to the below structure.
class Feed{
List<Message> messages;
TimeStamp publishDate;
}
public class Message implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String key;
private String value;
private Map<String, String> eventItemMap = new HashMap<>();
this property translate the list of map as a single map with all the key-value pair together. because, the messages property will be parsed as list of HashMap objets for each key/value. This will be translated to a single map.
Now in my pipeline, I will convert the collection as
PCollection<KV<String, Feed>>
to write it to different tables based on a property in the class. I have written a transform to do this.
The requirement is to create multiple TableRows based on the number of message objects. I have a few more properties in the JSON to along with publishDate which would be added to the tableRow and each message properties.
So the table would be as follows.
id, name, field1, field2, message1.property1, message1.property2...
id, name, field1, field2, message2.property1, message2.property2...
I tried to create the below transformation. But, not sure how it will output multiple rows based on the message list.
private class BuildRowListFn extends DoFn<KV<String, Feed>, List<TableRow>> {
#ProcessElement
public void processElement(ProcessContext context) {
Feed feed = context.element().getValue();
List<Message> messages = feed.getMessage();
List<TableRow> rows = new ArrayList<>();
messages.forEach((message) -> {
TableRow row = new TableRow();
row.set("column1", feed.getPublishDate());
row.set("column2", message.getEventItemMap().get("key1"));
row.set("column3", message.getEventItemMap().get("key2"));
rows.add(row);
}
);
}
But, this also will be a List which I won't be able to apply the BigQueryIO.write transformation.
Updated as per the comment from "Eugene" aka #jkff
Thanks #jkff. Now, i have changed the code as you mentioned in the second paragraph. context.output(row) inside messages.forEach, after setting table row as
List<Message> messages = feed.getMessage();
messages.forEach((message) -> {
TableRow row = new TableRow();
row.set("column2", message.getEventItemMap().get("key1"));
context.output(row);
}
Now, when i try to write this collection to BigQuery, as
rows.apply(BigQueryIO.writeTableRows().to(getTable(projectId, datasetId, tableName)).withSchema(getSchema())
.withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(WriteDisposition.WRITE_APPEND));
I am getting the below exception.
Exception in thread "main" org.apache.beam.sdk.Pipeline$PipelineExecutionException: java.lang.NullPointerException
at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:331)
at org.apache.beam.runners.direct.DirectRunner$DirectPipelineResult.waitUntilFinish(DirectRunner.java:301)
at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:200)
at org.apache.beam.runners.direct.DirectRunner.run(DirectRunner.java:63)
at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)
at org.apache.beam.sdk.Pipeline.run(Pipeline.java:283)
at com.chefd.gcloud.analytics.pipeline.MyPipeline.main(MyPipeline.java:284)
Caused by: java.lang.NullPointerException
at org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl$DatasetServiceImpl.insertAll(BigQueryServicesImpl.java:759)
at org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl$DatasetServiceImpl.insertAll(BigQueryServicesImpl.java:809)
at org.apache.beam.sdk.io.gcp.bigquery.StreamingWriteFn.flushRows(StreamingWriteFn.java:126)
at org.apache.beam.sdk.io.gcp.bigquery.StreamingWriteFn.finishBundle(StreamingWriteFn.java:96)
Please help.
Thank you.
It seems that you are assuming that a DoFn can output only a single value per element. This is not the case: it can output any number of values per element - no values, one value, many values, etc. A DoFn can even output values to multiple PCollection's.
In your case, you simply need to call c.output(row) for every row in your #ProcessElement method, for example: rows.forEach(c::output). Of course you'll also need to change the type of your DoFn to DoFn<KV<String, Feed>, TableRow>, because the type of elements in its output PCollection is TableRow, not List<TableRow> - you're just producing multiple elements into the collection for every input element, but that doesn't change the type.
An alternative method would be to do what you currently did, also do c.output(rows) and then apply Flatten.iterables() to flatten the PCollection<List<TableRow>> into a PCollection<TableRow> (you might need to replace List with Iterable to get it to work). But the other method is easier.

RazorEngine Error trying to send email

I have an MVC 4 application that sends out multiple emails. For example, I have an email template for submitting an order, a template for cancelling an order, etc...
I have an Email Service with multiple methods. My controller calls the Send method which looks like this:
public virtual void Send(List<string> recipients, string subject, string template, object data)
{
...
string html = GetContent(template, data);
...
}
The Send method calls GetContent, which is the method causing the problem:
private string GetContent(string template, object data)
{
string path = Path.Combine(BaseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return Engine.Razor.RunCompile(content, "htmlTemplate", null, data);
}
I am receiving the error:
The same key was already used for another template!
In my GetContent method should I add a new parameter for the TemplateKey and use that variable instead of always using htmlTemplate? Then the new order email template could have newOrderKey and CancelOrderKey for the email template being used to cancel an order?
Explanation
This happens because you use the same template key ("htmlTemplate") for multiple different templates.
Note that the way you currently have implemented GetContent you will run into multiple problems:
Even if you use a unique key, for example the template variable, you will trigger the exception when the templates are edited on disk.
Performance: You are reading the template file every time even when the template is already cached.
Solution:
Implement the ITemplateManager interface to manage your templates:
public class MyTemplateManager : ITemplateManager
{
private readonly string baseTemplatePath;
public MyTemplateManager(string basePath) {
baseTemplatePath = basePath;
}
public ITemplateSource Resolve(ITemplateKey key)
{
string template = key.Name;
string path = Path.Combine(baseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
throw new NotImplementedException("dynamic templates are not supported!");
}
}
Setup on startup:
var config = new TemplateServiceConfiguration();
config.Debug = true;
config.TemplateManager = new MyTemplateManager(BaseTemplatePath);
Engine.Razor = RazorEngineService.Create(config);
And use it:
// You don't really need this method anymore.
private string GetContent(string template, object data)
{
return Engine.Razor.RunCompile(template, null, data);
}
RazorEngine will now fix all the problems mentioned above internally. Notice how it is perfectly fine to use the name of the template as key, if in your scenario the name is all you need to identify a template (otherwise you cannot use NameOnlyTemplateKey and need to provide your own implementation).
Hope this helps.
(Disclaimer: Contributor of RazorEngine)

Get SQL data via listbox

Ok, so what I am trying to do is click one item in a listbox that i have, that listbox gets data from the sql database depending on that the user types into the textbox.
Now when I click that item in the first listbox, I need more info related to that item to show up in the 2nd list box.
When the user enters a name in the textbox, the first 10 in sql show up, now that I have that, I need to click on one of the items and get the 'task' of that client in the next listbox. Task is MATTERS in the database.
I am pretty sure that my code is correct, I get no errors but nothing shows up in the list box.
Here is my code:
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
if (listBox1.ContainsFocus)
{
if (item == "")
{
}
else
{
var con2 = Conn.ConnString();
using (SqlConnection myConnection2 = new SqlConnection(con2))
{
string oString2 = "select CLIENTMATTERS.MATTER, CLIENTMATTERS.DESCRIPTION from CLIENTMATTERS join CLIENTCODES on CLIENTMATTERS.CLIENT = CLIENTCODES.CLIENT Where CLIENTCODES.DESCRIPTION = '#code1'";
SqlCommand oCmd = new SqlCommand(oString2, myConnection2);
oCmd.Parameters.AddWithValue("#code1", item);
myConnection2.Open();
oCmd.Connection.Open();
List<string> codelist2 = new List<string>();
using (SqlDataReader oReader2 = oCmd.ExecuteReader())
{
if (oReader2.HasRows)
{
string value = string.Empty;
while (oReader2.Read())
{
codelist2.Add(oReader2["MATTER"].ToString());
}
}
}
this.listBox2.DataSource = codelist2;
}
}
}
}
You need to use BindingList<> instead of List<>.
The List<> doesn't implement the ListChanged event, so the ListBox doesn't get notified when the datasource changes.
In your example it would look like this:
BindingList<string> codelist2 = new BindingList<string>();
For further information take a look at
BindingList on MSDN.

how I save the incoming text messages into an string ArrayList in android?

how I save the incoming text messages into an string ArrayList in android? i get the sms into a broadcastreceiver class and want to put those text messages to a string ArrayList,every time the message receive put into an ArrayList's next index.
If you are able to get the information down to what ever string representation that you are interested in, what is stopping you from using a normal java arraylist in android?
String test = "test";
List<String> list = new ArrayList<String>();
list.add(test);
for(String s:list) {
System.out.println(s);
}