Can I get element value in selenium? - c#

I want to get a value from one input in selenium. But I need this value in other project test in the same solution. Can I get this value in this case or I need run both test project at the same time to get it?
This is my variable (I have it in a class project)
public static string strNumeroCotizacion;
I get the value here in a test project called "Cotizacion":
Variables_RW.element = Variables_RW.driver.FindElement(By.XPath("//INPUT[#id='numeroCotizacion']"));
Variables_RW.strNumeroCotizacion = Variables_RW.element.GetAttribute("value").ToString();
And I need use it in this case in other project called "facturacion" in the same solution:
Variables_RW.driver.FindElement(By.XPath("//INPUT[#id='sCotizacion']")).SendKeys("strNumeroCotizacion");
Variables_RW.driver.FindElement(By.XPath("//INPUT[#id='sCotizacion']")).SendKeys(Keys.Enter);

Interesting question. I don't think you can use variable from the different projects.
But you can write the value of that variable in the file when running your project1 and after you can read it in project 2.
It depends on which language you are using in selenium.
This is the Java Solution
To write to the file:
#SuppressWarnings("unchecked")
public void customerDataWrite(String custID, String OrderNum, String Contact) {
// First OrderData
JSONObject createdOrderData = new JSONObject();
createdOrderData.put("customer", custID);
createdOrderData.put("orderName", OrderNum);
createdOrderData.put("contactName", Contact);
// Add order numbers to list
JSONArray OrderDataList = new JSONArray();
OrderDataList.add(createdOrderData);
// Write JSON file
try (FileWriter file = new FileWriter("orderdata.json")) {
file.write(OrderDataList.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
To read from the file:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("orderdata.json"));
// Get order object
JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) array.get(0);
// Get order contact name
orderContactName = (String) jsonObject.get("contactName");
System.out.println(orderContactName);
// Get company name
orderCustomerName = (String) jsonObject.get("customer");
System.out.println(orderCustomerName);
// Get order Order name
orderOrderName = (String) jsonObject.get("orderName");
System.out.println(orderOrderName);
}

Related

Saving Binary Data FHIR DB

I am trying to save Binary data to FHIR DB.
This is my method:
public static Patient SavePdfForms(string resource, HttpClientEventHandler messageHandler, string[] pdfForms, Patient patient, FhirClient BinaryBundleClient)
{
Bundle BinaryBundle = new Bundle();
BinaryBundle.Type = Bundle.BundleType.Collection;
try
{
foreach (var item in pdfForms)
{
Binary BinaryData = new Binary();
var bytearray = Encoding.ASCII.GetBytes(item);
BinaryData.Data = bytearray;
BinaryData.ContentType = "application/fhir+json";
var binaryResource = BinaryBundleClient.Create(BinaryData);
BinaryBundle.AddResourceEntry(BinaryData, resource + "/BundleResource/" + binaryResource.Id);
}
}
catch (Exception ex)
{
throw;
}
var bundleId = BinaryBundleClient.Create(BinaryBundle);
patient.Identifier.Add(new Identifier("BinaryBundle", bundleId.Id));
return BinaryBundleClient.Update(patient);
}
The string[] of pdfForms is base64 and for each form I am creating a new binary and adding data and content type. But the line var binaryResource = BinaryBundleClient.Create(BinaryData); throws an error and data is not a valid json. I tried with different content type but that is not working. Any ideas why?
Assuming you are creating a new resource instance in BinaryBundleClient.Create(BinaryData) and the server to store it.
In your case, you directly pass the binary information in Fhirclient.Create(your data)
binaryResource = BinaryBundleClient.Create(BinaryData);
You must mention the type of the resource instance which follows:
Create Fhir client
var client = new FhirClient("http://server.fire.ly");
After Creating FhirClient You have to create a new resource instance. It will be like
var pat = new Patient() { /* set up data */ };
var created_pat = client.Create<Patient>(pat);
this interaction will throw an Exception when things go wrong, in most cases a FhirOperationException. This exception has an Outcome property that contains an OperationOutcome resource, and which you may inspect to find out more information about why the interaction failed. Most FHIR servers will return a human-readable error description in the OperationOutcome to help you out.
Refer here

JsonDocument - Read child object

I have a JSON object that I'm trying to read properties from. Here is a sample:
{"id":"335057af-a156-41c6-a0de-0cdc05856b3d",
"title":"Test 100488-100489 not included",
"code":"QWNCY47Y999",
"start":"2022-08-10T22:00:00.000Z",
"end":"2022-08-11T02:00:00.000Z",
"closeAfter":"2022-08-08T23:59:00.000Z",
"archiveAfter":"2022-11-08T22:00:00.000Z",
"timezone":"America/New_York",
"defaultLocale":"enUS",
"currency":"USD",
"registrationSecurityLevel":"Public",
"status":"Pending",
"eventStatus":"Upcoming",
"planningStatus":"In-Planning",
"testMode":true,
"planners":[{"firstName":"C","lastName":"G","email":"Noreply#events.qwerty.comx"}],
"created":"2021-06-11T09:55:57.667Z",
"lastModified":"2021-07-08T17:21:48.039Z",
"customFields":[
{"id":"f2cf4864-171f-44fa-919a-248d37e42563",
"name":"Level of Service",
"value":["Full Support"],
"type":"SingleSelect",
"order":25},
{"id":"c1539edf-a3e1-4f40-9747-e93f4fedfa5d",
"name":"Internal/External",
"value":["Internal","External"],
"type":"MultiSelect",
"order":42},
{"id":"1b525d2a-b3f8-4141-91ae-45de5ee3a2fe",
"name":"Request ID",
"value":["MRF000558"],
"type":"AutoIncrement",
"order":53}],
"category":{"name":"Conference"},
"_links":{"invitation":{"href":"http://sandbox-www.qwerty.com/d/8nqg6n/1Q"},
"agenda":{"href":"http://sandbox-www.qwerty.com/d/8nqg6n/6X"},
"summary":{"href":"http://sandbox-www.qwerty.com/d/8nqg6n"},
"registration":{"href":"http://sandbox-www.qwerty.com/d/8nqg6n/4W"}},
"virtual":false,
"format":"In-person"}
I can programmatically read string properties, but if one of the properties is another object, I can't read it.
try
{
var x1 = content2.RootElement.GetProperty("code"); // it works
var x2 = content2.RootElement.GetProperty("currency"); // it works
var x3 = content2.RootElement.GetProperty("start"); // it works
var x99 = content2.RootElement.GetProperty("summary"); // exception, key not found
var x999 = x99.GetProperty("href");
}
catch(System.Exception ex)
{
Console.WriteLine(ex.Message);
}
Ultimately, my goal is to read the summary child object and get property href.
you have a bug. "summary" goes after "_links"
this works for me
var contentObj = JObject.Parse(content);
var href = contentObj["_links"]["summary"]["href"];
output
http://sandbox-www.qwerty.com/d/8nqg6n
for you I guess it could be
var x9 = content2.RootElement.GetProperty("_links");
var x99 = x9.GetProperty("summary");
var x999 = x99.GetProperty("href").ToString();
//or just
var x999 = content2.RootElement.GetProperty("_links").GetProperty("summary").GetProperty("href").ToString();
Unless this "but if one of the properties is another object, I can't read it." means that you don't have a well defined format for your JSON file, just create an object for your JSON file and deserialize it. Then you can access it directly via that objects property.

Adding object to JSON file

I'm creating a software on which I added a profiles feature where the user can create profile to load his informations faster. To store these informations, I'm using a JSON file, which contains as much objects as there are profiles.
Here is the format of the JSON file when a profile is contained (not the actual one, an example) :
{
"Profile-name": {
"form_email": "example#example.com",
//Many other informations...
}
}
Here is the code I'm using to write the JSON and its content :
string json = File.ReadAllText("profiles.json");
dynamic profiles = JsonConvert.DeserializeObject(json);
if (profiles == null)
{
File.WriteAllText(jsonFilePath, "{}");
json = File.ReadAllText(jsonFilePath);
profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);
}
profiles.Add(profile_name.Text, new Profile_Name { form_email = form_email.Text });
var newJson = JsonConvert.SerializeObject(profiles, Formatting.Indented);
File.WriteAllText(jsonFilePath, newJson);
profile_tr.Nodes.Add(profile_name.Text, profile_name.Text);
debug_tb.Text += newJson;
But when the profiles.json file is completely empty, the profile is successfully written, but when I'm trying to ADD a profile when another one already exists, I get this error :
The best overloaded method match for 'Newtonsoft.Json.Linq.JObject.Add(string, Newtonsoft.Json.Linq.JToken)' has some invalid arguments on the profiles.Add(); line.
By the way, you can notice that I need to add {} by a non-trivial way in the file if it's empty, maybe it has something to do with the error ?
The expected output would be this JSON file :
{
"Profile-name": {
"form_email": "example#example.com",
//Many other informations...
},
"Second-profile": {
"form_email": "anotherexample#example.com"
//Some other informations...
}
}
Okay so I found by reading my code again, so I just replaced dynamic profiles = JsonConvert.DeserializeObject(json); to dynamic profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);.
But it still don't fix the non-trivial way I use to add the {} to my file...
The object the first DeserializeObject method returns is actually a JObject, but below you deserialize it as a Dictionary. You shouldn't be mixing the types, choose either one.
If you use the JObject then to add objects you need to convert them to JObjects:
profiles.Add(profile_name.Text, JObject.FromObject(new Profile_Name { form_email = form_email.Text }));
In both cases, when the profile is null you just need to initialize it:
if (profiles == null)
{
profiles = new JObject(); // or new Dictionary<string, Profile_Name>();
}

Ban a variable from a list with a "ban" list

How can I ban a variable from a list without removing it from that list by adding the variable to a list of "banned" variable?
I wish to be able to type in a string. That string is compared to the file names in a folder. If there is a match, the file is read. If I type this same string again, the file should not be read again. There for I want to have a list of "banned" string that is checked whilst typing to avoid the file to be read again.
I have tried a few ways but not getting there. Below is an example of my last attempt.
What would be the best way?
public class test
{
string scl= "test3";
List <string> lsf,lso;
void Start ()
{
lsf=//file names
new List<string>();
lso=//files open
new List<string>();
lsf.Add("test0");
lsf.Add("test1");
lsf.Add("test2");
lsf.Add("test3");
lsf.Add("test4");
lso.Add("idhtk49fngo");//random string
}
void Update ()
{
if
(
Input.GetKeyDown("a")
)
{
for
(
int i=0;
i<lsf.Count;
i++
)
{
if(lsf[i]==scl)
{
Debug.Log
(i+" is read");
for
(
int j=0;
j<lso.Count;
j++
)
{
//how can i avoid reading
//lsf[3] here the second time
//"a" is pressed (by having "test3"
//added to a "ban" list (lso) )
if(scl!=lso[j])
{
lso.Add(lsf[i]);
}
}
}
}
}
}
Michael’s answer is the way to go here but it can be improved using the more appropriate collection available to keep track of opened files; if you want uniqueness use a set, not a list:
HashSet<string> openedFiles = new HashSet<string>();
public static bool TryFirstRead(
string path,
out string result)
{
if (openedFiles.Add(path))
{
result = File.ReadAllText(path);
return true;
}
result = null;
return false;
}
Also, I’d avoid throwing vexing exceptions. Give the consumer a friendly way to know if the file was read or not, don’t make them end up having to use exceptions as a flow control mechanism.
I didn't understand although if you want to replace a value from another list.
You can use the list index to create a new list with the values which you removed.
String list1 = {"hi", "hello", "World"};
String list2 = {"bye", "goodbye", "World"};
List1[1] = list2[1];
I would suggest such way:
public static List<string> openedFiles = new List<string>();
public static string ReadFileAndAddToOpenedList(string path)
{
if (openedFiles.Contains(path))
throw new Exception("File already opened");
// Instead of throwing exception you could for example just log this or do something else, like:
// Consolle.WriteLine("File already opened");
else
{
openedFiles.Add(path);
return File.ReadAllText(path);
}
}
The idea is - on every file read, add file to list, so you can check every time you try read file, if it was already read (or opened). If it is, throw exception (or do something else). Else read a file.
You could instead of making it a string list use your own class
public class MyFile
{
public string Name;
public bool isOpen;
public MyFile(string name)
{
Name = name;
isOpen = false;
}
}
List<MyFile> lsf = new List<MyFile>()
{
new MyFile("test0"),
new MyFile("test1"),
new MyFile("test2"),
new MyFile("test3"),
new MyFile("test4")
};
Than when you read the file set isOpen to true
MyFile[someIndex].isOpen = true;
and later you can check this
// E.g. skip in a loop
if(MyFile[someIndex]) continue;
You could than also use Linq in order to get a list of only unread files:
var unreadFiles = lsf.Select(f => f.Name).Where(file => !file.isOpen);

Files,strings and save

I been having trouble trying to figure this out. When I think I have it I get told no. Here is a picture of it.
I am working on the save button. Now after the user adds the first name, last name and job title they can save it. If a user loads the file and it comes up in the listbox, that person should be able to click on the name and then hit the edit button and they should be able to edit it. I have code, but I did get inform it looked wackey and the string should have the first name, last name and job title.
It is getting me really confused as I am learning C#. I know how to use savefiledialog but I am not allowed to use it on this one. Here is what I am suppose to be doing:
When the user clicks the “Save” button, write the selected record to
the file specified in txtFilePath (absolute path not relative) without
truncating the values currently inside.
I am still working on my code since I got told that it will be better file writes records in a group of three strings. But this is the code I have right now.
private void Save_Click(object sender, EventArgs e)
{
string path = txtFilePath.Text;
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (Employee employee in employeeList.Items)
sw.WriteLine(employee);
}
}
else
try
{
StreamWriter sw = File.AppendText(path);
foreach (var item in employeeList.Items)
sw.WriteLine(item.ToString());
}
catch
{
MessageBox.Show("Please enter something in");
}
Now I can not use save or open file dialog. The user should be able to open any file on the C,E,F drive or where it is. I was also told it should be obj.Also the program should handle and exceptions that arise.
I know this might be a noobie question but my mind is stuck as I am still learning how to code with C#. Now I have been searching and reading. But I am not finding something to help me understand how to have all this into 1 code. If someone might be able to help or even point to a better web site I would appreciate it.
There are many, many ways to store data in a file. This code demonstrates 4 methods that are pretty easy to use. But the point is that you should probably be splitting up your data into separate pieces rather than storing them as one long string.
public class MyPublicData
{
public int id;
public string value;
}
[Serializable()]
class MyEncapsulatedData
{
private DateTime created;
private int length;
public MyEncapsulatedData(int length)
{
created = DateTime.Now;
this.length = length;
}
public DateTime ExpirationDate
{
get { return created.AddDays(length); }
}
}
class Program
{
static void Main(string[] args)
{
string testpath = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestFile");
// Method 1: Automatic XML serialization
// Requires that the type being serialized and all its serializable members are public
System.Xml.Serialization.XmlSerializer xs =
new System.Xml.Serialization.XmlSerializer(typeof(MyPublicData));
MyPublicData o1 = new MyPublicData() {id = 3141, value = "a test object"};
MyEncapsulatedData o2 = new MyEncapsulatedData(7);
using (System.IO.StreamWriter w = new System.IO.StreamWriter(testpath + ".xml"))
{
xs.Serialize(w, o1);
}
// Method 2: Manual XML serialization
System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(testpath + "1.xml");
xw.WriteStartElement("MyPublicData");
xw.WriteStartAttribute("id");
xw.WriteValue(o1.id);
xw.WriteEndAttribute();
xw.WriteAttributeString("value", o1.value);
xw.WriteEndElement();
xw.Close();
// Method 3: Automatic binary serialization
// Requires that the type being serialized be marked with the "Serializable" attribute
using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Create))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(f, o2);
}
// Demonstrate how automatic binary deserialization works
// and prove that it handles objects with private members
using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Open))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MyEncapsulatedData o3 = (MyEncapsulatedData)bf.Deserialize(f);
Console.WriteLine(o3.ExpirationDate.ToString());
}
// Method 4: Manual binary serialization
using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Create))
{
using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(f))
{
w.Write(o1.id);
w.Write(o1.value);
}
}
// Demonstrate how manual binary deserialization works
using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Open))
{
using (System.IO.BinaryReader r = new System.IO.BinaryReader(f))
{
MyPublicData o4 = new MyPublicData() { id = r.ReadInt32(), value = r.ReadString() };
Console.WriteLine("{0}: {1}", o4.id, o4.value);
}
}
}
}
As you are writing the employee objects with WriteLine, the underlying ToString() is being invoked. What you have to do first is to customize that ToString() methods to fit your needs, in this way:
public class Employee
{
public string FirstName;
public string LastName;
public string JobTitle;
// all other declarations here
...........
// Override ToString()
public override string ToString()
{
return string.Format("'{0}', '{1}', '{2}'", this.FirstName, this.LastName, this.JobTitle);
}
}
This way, your writing code still keeps clean and readable.
By the way, there is not a reverse equivalent of ToSTring, but to follow .Net standards, I suggest you to implement an Employee's method like:
public static Employee Parse(string)
{
// your code here, return a new Employee object
}
You have to determine a way of saving that suits your needs. A simple way to store this info could be CSV:
"Firstname1","Lastname 1", "Jobtitle1"
" Firstname2", "Lastname2","Jobtitle2 "
As you can see, data won't be truncated, since the delimiter " is used to determine string boundaries.
As shown in this question, using CsvHelper might be an option. But given this is homework and the constraints therein, you might have to create this method yourself. You could put this in Employee (or make it override ToString()) that does something along those lines:
public String GetAsCSV(String firstName, String lastName, String jobTitle)
{
return String.Format("\"{0}\",\"{1}\",\"{2}\"", firstName, lastName, jobTitle);
}
I'll leave the way how to read the data back in as an exercise to you. ;-)

Categories

Resources