I found out that my index page wasn't showing the updated user info for currently logged in user. So I changed the form page from:
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.SubmittedBy, new { Value = Model.ADAccount })
</div>
</div>
**to:**
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.SubmittedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.UpdatedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.UpdateBy, new { htmlAttributes = new { Value = Model.ADAccount } })
</div>
</div>
I had also tried changing the form page like this but it didn't change anything:
#Html.HiddenFor(model => model.UpdateBy, new { Value = Model.ADAccount })
The submit looks like this in the form page:
#(Html.Kendo().Button()
.Name("submit")
.Content("Submit")
.HtmlAttributes(new { #class = "k-primary" })
.Events(ev => ev.Click("onClick")))
But for some reason it's still not showing the UpdateBy in the Index list. I don't see a specific reference in the Controller for UpdateBy or SubmittedBy. I see them both in the ApplicantCapturedData.cs list:
public string UpdateBy { get; set; }
public string SubmittedBy { get; set; }
I see in ApplicantController.cs, the Edit Post puts some data in the DB, but doesn't mention the updateBy or SubmittedBy variables or model specifically. However, in the old code, the SubmittedBy variable change did show on the index list. I looked in the project, and there are no specific references to SubmittedBy besides ApplicantController
When I put a watch on UpdateBy, I see it go back and forth between the old user, me, and null. Apparently it ends with the old user, because that's what is displayed in the list of applicants on the index after the form is submitted.
Any thoughts on how to fix this? I'm new to MVC, and I'm not sure why this change isn't getting back to the model/db. When the applicantController gets the applicantCapturedData, it shows the old value for UpdateBy, not the new value.
The Edit Method should return current loged-in user to the view instead of BD data, but it's not. I'm not sure why.
I looked at controller not receiving model info, but it didn't seem like the same issue to me.
Let me know if you think I'm leaving any crucial info out that you need. I obviously can't post all of the mvc files and code here for clarity and sanity.
******Update*********
This is the Edit/Post method in ApplicantController.cs. It doesn't specifically refer to the SubmittedBy or UpdateBy, but the SubmittedBy part does show up in the index, even when we updated it in the form with current AD user:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ApplicantCapturedData applicantCapturedData)
{
var eRecordSchedulinglist = applicantCapturedData.ERecordScheduling;
var eRecordScheduling = new ERecordScheduling();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
if (ModelState.IsValid)
{
//ERecordScheduling eRecordScheduling = new ERecordScheduling();
db.Entry(applicantCapturedData).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
int getid = applicantCapturedData.ID;
//Getting values for provider license already in db
var query = from p in db.ProviderLicenses
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in query)
{
db.ProviderLicenses.Remove(i);
}
db.SaveChanges();
int c = 1;
if (providerLicenselist != null)
{
var updatePLS = providerLicenselist.ToList();
// adding only new record to db
foreach (var i in updatePLS)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = getid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
//getting Values already existing in db for Erecording Schedulign
var queryERS = from p in db.ERecordSchedulings
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryERS)
{
db.ERecordSchedulings.Remove(i);
}
db.SaveChanges();
if (eRecordSchedulinglist != null)
{
var updateESCH = eRecordSchedulinglist.ToList();
foreach (var item in updateESCH)
{
eRecordScheduling.DepartmentName = item.DepartmentName;
eRecordScheduling.Shedules = item.Shedules;
eRecordScheduling.VisitType = item.VisitType;
eRecordScheduling.GenericProvider = item.GenericProvider;
eRecordScheduling.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = getid;
if (eRecordScheduling.ERecordSchedulingID <= c)
{
eRecordScheduling.ERecordSchedulingID = eRecordScheduling.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
}
}
//Getting Values that already exisit in db for Taxonomy
var querytaxo = from p in db.TaxNPITaxonomies
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in querytaxo)
{
db.TaxNPITaxonomies.Remove(i);
}
db.SaveChanges();
if (taxlist != null)
{
var UpdateTaxo = taxlist.ToList();
foreach (var t in UpdateTaxo)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = getid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
var queryeprescribe = from p in db.EPrescribes
where p.ApplicantCapturedData_ID == getid
select p;
foreach (var i in queryeprescribe)
{
db.EPrescribes.Remove(i);
}
db.SaveChanges();
if (eprescribelist != null)
{
var updateeprescribe = eprescribelist.ToList();
foreach (var t in updateeprescribe)
{
eprescribe.EPrescribeOptions = t.EPrescribeOptions;
eprescribe.ID = t.ID;
t.ApplicantCapturedData_ID = getid;
if (eprescribe.ApplicantCapturedData_ID <= c)
{
eprescribe.ApplicantCapturedData_ID = eprescribe.ApplicantCapturedData_ID++;
}
db.EPrescribes.Add(t);
db.SaveChanges();
}
}
//Geting values that already exist in db for Payors
var queryPayor = from p in db.Payors
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryPayor)
{
db.Payors.Remove(i);
}
db.SaveChanges();
if (payorlist != null)
{
var updatepayor = payorlist.ToList();
foreach (var p in updatepayor)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = getid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Here's the save in ApplicantController.cs. It doesn't have a specific reference to UpdateBy or SubmittedBy either, and yet SubmittedBy used to update when I changed the AD user:
// [HttpPost]
public ActionResult Save(ApplicantCapturedData applicantCapturedData)
{
ViewBag.PostedBills = applicantCapturedData.BillingAreas;
applicantCapturedData.BillingAreas = applicantCapturedData.BillingAreas;
//updating eRecordScheduling
var list = applicantCapturedData.ERecordScheduling;
var a = new ERecordScheduling();
var OtherAddressList = applicantCapturedData.PracticeInfoOtherLocations;
var otheraddresses = new PracticeInfoOtherLocation();
//var payorlist = applicantCapturedData.Payor;
//var payor = new Payor();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var Eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
// var lastEnt = db.ERecordSchedulings.AsEnumerable().Where(i => i.ERecordSchedulingID.CompareTo(a.ERecordSchedulingID))
int c = 1;//lastEnter.LastOrDefault().ERecordSchedulingID;
if (ModelState.IsValid)
{
db.ApplicantCapturedDatas.Add(applicantCapturedData);
// db.ERecordSchedulings.Add(applicantCapturedData);
db.SaveChanges();
//db.ERecordSchedulings.Add(applicantCapturedData.ERecordScheduling);
//get the primary key id after adding to the Db
int newid = applicantCapturedData.ID;
if (applicantCapturedData.ERecordScheduling != null)
{
// check if we have more record on Erecord scheduling using the count
//if count is greater than zero we have record to add to db.
if (applicantCapturedData.ERecordScheduling.Count() > 0)
{
/*
* This loops thru the list and add record
*
*/
foreach (var item in list)
{
a.DepartmentName = item.DepartmentName;
a.Shedules = item.Shedules;
a.VisitType = item.VisitType;
a.GenericProvider = item.GenericProvider;
a.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = newid;
//if you put a breakpoint at the beginning of this class you will see that all id is 0 I had to increment the id so I don't override itself.
if (a.ERecordSchedulingID <= c)
{
a.ERecordSchedulingID = a.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
//item.LicenseNumber = a.LicenseNumber;
//item.State = a.State;
//item.ProviderLicenseID = a.ProviderLicenseID;
}
}
}
if (applicantCapturedData.ProviderLicense != null)
{
if (applicantCapturedData.ProviderLicense.Count() > 0)
{
foreach (var i in providerLicenselist)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = newid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
}
if (applicantCapturedData.Payor != null)
{
if (applicantCapturedData.Payor.Count() > 0)
{
foreach (var p in payorlist)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = newid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.PracticeInfoOtherLocations != null)
{
if (applicantCapturedData.PracticeInfoOtherLocations.Count() > 0)
{
foreach (var p in OtherAddressList)
{
otheraddresses.City = p.City;
otheraddresses.Fax = p.Fax;
otheraddresses.Phone = p.Phone;
otheraddresses.State = p.State;
otheraddresses.Street = p.Street;
otheraddresses.Suite = p.Suite;
otheraddresses.ZipCode = p.ZipCode;
otheraddresses.AppID = newid;
otheraddresses.ID = p.ID;
if (otheraddresses.ID <= c)
{
otheraddresses.ID = otheraddresses.ID++;
}
db.PracticeInfoOtherLocations.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.EPrescribe != null)
{
if (applicantCapturedData.EPrescribe.Count() > 0)
{
foreach (var p in Eprescribelist)
{
eprescribe.EPrescribeOptions = p.EPrescribeOptions;
eprescribe.ID = p.ID;
p.ApplicantCapturedData_ID = newid;
if (eprescribe.ID <= c)
{
eprescribe.ID = eprescribe.ID++;
}
db.EPrescribes.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.TaxNPITaxonomy != null)
{
if (applicantCapturedData.TaxNPITaxonomy.Count() > 0)
{
foreach (var t in taxlist)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = newid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Related
i have a problem, I am trying to take the value of a field of the users table that I populated in the first while, but when I try to take the value in the second while of the second call, it returns 0, I cannot understand why, the values in the field are populated.
my code below:
var r = new sn_ws.RESTMessageV2('success_factors_api', 'GET');
var response = r.execute();
var reviver = function(key, value) {
if (typeof value === 'undefined') {
return null;
}
};
var responseBody = JSON.parse(response.getBody(), reviver());
var httpStatus = response.getStatusCode();
//gs.info(responseBody.d.results[0].nationalId);
var gr = new GlideRecord('sys_user');
gr.addEncodedQuery('u_codice_fiscaleISNOTEMPTY');
gr.query();
while (gr.next()) {
var fiscalCode = gr.getValue('u_codice_fiscale');
responseBody.d.results.forEach(function(obj) {
if (fiscalCode === obj.nationalId) {
gr.u_personal_id_external_successfactor = obj.personIdExternal;
gr.update();
}
});
}
var r2 = new sn_ws.RESTMessageV2('success_factors_api', 'GETEMPLOYMENT');
var response2 = r2.execute();
var reviver2 = function(key, value) {
if (typeof value === 'undefined') {
return null;
}
};
var responseBody2 = JSON.parse(response2.getBody(), reviver2());
var httpStatus2 = response2.getStatusCode();
gr.addEncodedQuery('u_personal_id_external_successfactorISNOTEMPTY');
while (gr.next()) {
var personalIdExternal = gr.getValue('u_personal_id_external_successfactor');
gs.info(personalIdExternal); //return me 0
responseBody2.d.results.forEach(function(obj) {
if (personalIdExternal === obj.personIdExternal) {
gr.u_user_id_successfactor = obj.userId;
gr.update();
}
});
}
Your second loop is missing a gr.query(). Also, you should never reuse a GlideRecord like that. Declare a new GlideRecord for the second loop.
i'm new in servicenow and I have to add this filter "document_id.number STARTS WITH BKNG"
as a query, how can i do in servicenow?
this is my code:
// only show 30 in header menu dropdown
var max = 30;
var t = data;
t.items = [];
t.count = 0;
var u = getMyApprovals();
// use record watchers to tell header when to update dropdown counts
t.record_watchers = [];
t.record_watchers.push({'table':'sysapproval_approver','filter':'approverIN' + u.toString() + '^state=requested'});
var z = new GlideRecord('sysapproval_approver');
z.addQuery("approver", u);
z.addQuery("state", "requested");
z.addQuery("document_id.number", "STARTSWITH", "BKNG")
z.orderByDesc('sys_updated_on');
z.setLimit(max);
z.query();
var link = {};
link.title = gs.getMessage('View all approvals');
link.type = 'link';
link.href = '?id=approvals';
link.items = [];
t.items.push(link);
while (z.next()) {
var a = {};
var rec = getRecordBeingApproved(z);
if (!rec.isValidRecord()) // nothing being approved - hmmm
continue;
a.short_description = rec.short_description + "";
if (rec.getRecordClassName() == "sc_request") {
var items = new GlideRecord("sc_req_item");
items.addQuery("request", rec.getUniqueValue());
items.query();
if (items.getRowCount() > 1)
a.short_description = items.getRowCount() + " requested items";
else if (items.getRowCount() == 1) {
items.next();
a.short_description = items.getValue("short_description");
}
}
$sp.getRecordValues(a, z, 'sys_id,sys_updated_on');
a.number = rec.getDisplayValue();
a.__table = z.getRecordClassName();
a.type = 'approval';
t.items.push(a);
t.count++;
}
function getRecordBeingApproved(gr) {
if (!gr.sysapproval.nil())
return gr.sysapproval.getRefRecord();
return gr.document_id.getRefRecord();
}
i tried doing z.addQuery ("document_id.number", "STARTSWITH", "BKNG")
but it doesn't works.
i don't know how to do.
You can't dot-walk the document_id field when using .addQuery() as it is not a reference filed. Instead, you can use the Approval for (sysapproval) reference field like so:
z.addQuery("sysapproval.number", "STARTSWITH", "BKNG");
I have a repository method that gets data from a table and returns a list.
Here is code of this repository method:
public List<HeatMapViewModel> GetStops()
{
using (TraxgoDB ctx = new TraxgoDB())
{
List<HeatMapViewModel> items = new List<HeatMapViewModel>();
var firstitem = ctx.Logging.Where(x => x.Datatype == Datatype.Start).AsEnumerable().FirstOrDefault();
var midnight = new DateTime(firstitem.CurrentDateTime.Year, firstitem.CurrentDateTime.Month,
firstitem.CurrentDateTime.Day, 00, 00, 00);
TimeSpan difference = (firstitem.CurrentDateTime - midnight);
var difference_after_midnight = (int)difference.TotalMinutes;
items.Add(new HeatMapViewModel
{
Latitude2 = firstitem.Latitude,
Longitude2 = firstitem.Longitude,
FirstStartDifference = difference_after_midnight
});
var lastItem = ctx.Logging.Where(x => x.Datatype == Datatype.Stop).AsEnumerable().LastOrDefault();
var before_midnight = new DateTime(lastItem.CurrentDateTime.Year, lastItem.CurrentDateTime.Month,
lastItem.CurrentDateTime.Day, 23, 59, 00);
TimeSpan difference_before = (before_midnight - lastItem.CurrentDateTime);
var difference_before_midnight = (int)difference_before.TotalMinutes;
items.Add(new HeatMapViewModel
{
Latitude2 = lastItem.Latitude,
Longitude2 = lastItem.Longitude,
LastStartDifference = difference_before_midnight
});
var allitems = ctx.Logging;
var filteredQuery = allitems.Where(x => x.Datatype == Datatype.Start || x.Datatype == Datatype.Stop).OrderByDescending(x => x.LogID).ToList();
for (int i = 1; i < filteredQuery.Count; i++)
{
if (filteredQuery[i].Datatype == Datatype.Stop && filteredQuery[i - 1].Datatype == Datatype.Start)
{
TimeSpan differenceTicks = filteredQuery[i - 1].CurrentDateTime - filteredQuery[i].CurrentDateTime;
items.Add(new HeatMapViewModel
{
Latitude2 = filteredQuery[i].Latitude,
Longitude2 = filteredQuery[i].Longitude,
Difference = (int)differenceTicks.TotalMinutes
});
}
}
return items;
}
}
And thats the controller that returns data from the repository method:
public JsonResult Stops()
{
var stops = repoEntities.GetStops();
return Json(stops.ToArray(), JsonRequestBehavior.AllowGet);
}
I set a breakpoint in the controller method and see that it gets three elements:
And in dev console in chrome I see three elements:
But on the map i only see one marker:
Where is my mistake or what did i miss out?
I found where is problem
In firstitem and lastitem I return properties LastStartDifference and FirstStartDifference instead of Difference.
I am trying to get specific values from the general site that contains the annual reports of public-listed firms using Selenium Webdriver JS. Kindly help me investigate. I get the issue on clicking the Annual Report link.
The process that I'm trying to automate is listed below:
Go to site (http://edge.pse.com.ph/financialReports/form.do)
Filter by type of report (sendKeys('Annual Report') and fromDate attribute value to 4-23-2012 (year 2012 to get 4-5 annual reports of each firm)
click btnSearch
click Annual Report link per company row to view report (a tag is inside a td)
switch to the popup window
get specific values as object values and store it in the array
close popup window and get back to initial window
Repeat it on the succeeding company rows (take note that the site has pagination and a total of 22 pages (or tables) must be looped through
Kindly check my initial code for the process below. I also think that my implicitWaits are working. Does it apply on Selenium executeScript commands?
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://edge.pse.com.ph/financialReports/form.do');
driver.wait(until.titleIs('Financial Reports'), 1000)
driver.manage().timeouts().implicitlyWait(5000);
driver.findElement(By.name('tmplNm')).sendKeys('Annual Report');
driver.executeScript("document.getElementsByName('fromDate').setAttribute('value', '4-23-2012')");
driver.findElement(By.id('btnSearch')).click();
var totalPages = 22;
var num = 0;
while (num < totalPages) {
var pagingArray = driver.executeScript("document.querySelector('.paging').getElementsByTagName('span')");
for (var p = 0; p < pagingArray.length; p++) {
var page = driver.executeScript("pagingArray[p].getElementsByTagName('a')[0]");
page.click();
var table = driver.executeScript("document.querySelector('table.list')");
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
// Store the current window handle
var winHandleBefore = driver.getWindowHandle();
var reportLink = driver.executeScript("table.rows[i].cells[j].getElementsByTagName('a')[0]");
reportLink.click();
// Switch to new window opened
for (var winHandle in driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
var companyName = driver.executeScript("document.getElementById('companyName').innerHTML");
var stockTicker = driver.executeScript("document.getElementById('companyStockSymbol').innerHTML");
checkCompany(companyName, stockTicker);
var tableBS = driver.executeScript("document.getElementById('BS')");
var currentYear = driver.executeScript("tableBS.rows[1].cells[1].getElementsByTagName('span')[0]");
if (!checkBalanceSheets(companyName, currentYear)) {
bsCurrentYear = new Object();
bsCurrentYear.year = currentYear;
bsCurrentYear.currentAssets = driver.executeScript("tableBS.rows[2].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.totalAssets = driver.executeScript("tableBS.rows[3].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.currentLiabilities = driver.executeScript("tableBS.rows[4].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.totalLiabilities = driver.executeScript("tableBS.rows[5].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.company = companyName;
balanceSheets.push(bsCurrentYear);
}
var previousYear = driver.executeScript("tableBS.rows[1].cells[2].getElementsByTagName('span')[0]");
if (!checkBalanceSheets(companyName, previousYear)) {
bsPreviousYear = new Object();
bsPreviousYear.year = previousYear;
bsPreviousYear.currentAssets = driver.executeScript("tableBS.rows[2].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.totalAssets = driver.executeScript("tableBS.rows[3].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.currentLiabilities = driver.executeScript("tableBS.rows[4].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.totalLiabilities = driver.executeScript("tableBS.rows[5].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.company = companyName;
balanceSheets.push(bsPreviousYear);
}
var tableIS = driver.executeScript("document.getElementById('IS')");
if (!checkIncomeStatements(companyName, currentYear)) {
isCurrentYear = new Object();
isCurrentYear.year = currentYear;
isCurrentYear.grossrevenue = driver.executeScript("tableIS.rows[4].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.grossexpense = driver.executeScript("tableIS.rows[7].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.netincomeaftertax = driver.executeScript("tableIS.rows[10].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.company = companyName;
isCurrentYear.eps = driver.executeScript("tableIS.rows[12].cells[1].getElementsByTagName('span')[0]");
incomeStatements.push(isCurrentYear);
}
if (!checkIncomeStatements(companyName, previousYear)) {
isPreviousYear = new Object();
isPreviousYear = previousYear;
isPreviousYear.grossrevenue = driver.executeScript("tableIS.rows[4].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.grossexpense = driver.executeScript("tableIS.rows[7].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.netincomeaftertax = driver.executeScript("tableIS.rows[10].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.company = companyName;
isPreviousYear.eps = driver.executeScript("tableIS.rows[12].cells[2].getElementsByTagName('span')[0]");
incomeStatements.push(isPreviousYear);
}
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
}
}
}
}
driver.executeScript("document.querySelector('.paging').getElementsByTagName('a')[2].click()");
num++;
}
PS CheckBalanceSheets and CheckIncomeStatements are for validating IF the year already exists and has been recorded before for the respective company
function checkCompany(name, ticker) {
var found = companies.some(function(el) {
return el.name === name;
});
if (!found) { companies.push({ name: name, ticker: ticker }); }
}
function checkBalanceSheets(name, year) {
var found = balanceSheets.some(function(el) {
return el.name === name && el.year === year;
});
}
function checkIncomeStatements(name, year) {
var found = incomeStatements.some(function(el) {
return el.name === name && el.year === year;
});
}
I have a slight problem here that each time I run the application the first radio button is always checked, I want to make nun of the radio buttons checked. How do I do this?
<div class="col-md-12">
<!--<i class="fa fa-child" aria-hidden="true"></i>-->
#Html.LabelFor(model => model.CCommmunication, "Choose your preferred way of communication", new { #style = "", #class = "", id = "" })
<span style="color: red;">*</span>
#*#Html.DropDownListFor(model => model.Profession, new SelectList(Model.Professions, "Id", "Name"), new { placeholder = "", #style = "", #class = "form-control", id = "Profession" })*#
#Html.EnumRadioButtonFor(model => model.CCommmunication, false,false,"communicationCB") <!--first 2 paramerters are false false communicationCB is the class-->
#Html.ValidationMessageFor(model => model.CCommmunication)
</div>
this is my Model
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication CCommmunication
{ get; set; }
public enum Commmunication
{
[Display(Name = "Email", Order = 0)]
Email,
[Display(Name = "Mobile telephone", Order = 1)]
TelephoneNo,
[Display(Name = "Alternative telephone", Order = 2)]
TelephoneNoAlternative
}
This is my JavaScript
<script>
var checkedVal = $('.communicationCB input[name=CCommmunication]:checked').val(); //Added a variable to check the value
if (checkedVal == "TelephoneNo") { //if checked valuie
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
};
if (checkedVal == "TelephoneNoAlternative") { //if checked valuie == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
};
$('.communicationCB input[name=CCommmunication]').click(function () { //.communication class passed input name == model public communication
if ($(this).val() == "TelephoneNo") { //if value TelephoneNo selected in model
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
}
if ($(this).val() == "TelephoneNoAlternative") { //if value == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
}
});
Finally I have a enumRadioButton.cs
public static class HtmlHelper
{
public static MvcHtmlString EnumRadioButtonFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
bool includeNoneOption = true,
bool isDisabled = false,
string cssClass = null
) where TModel : class
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
throw new InvalidOperationException("Expression must be a member expression");
var name = ExpressionHelper.GetExpressionText(expression);
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
ModelState currentValueInModelState;
var couldGetValueFromModelState = htmlHelper.ViewData.ModelState.TryGetValue(fullName, out currentValueInModelState);
object selectedValue = null;
if (couldGetValueFromModelState && htmlHelper.ViewData.Model != null)
{
selectedValue = expression.Compile()(htmlHelper.ViewData.Model);
}
var enumNames = GetSelectItemsForEnum(typeof(TProperty), selectedValue).Where(n => !string.IsNullOrEmpty(n.Value)).ToList();
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
sb.AppendFormat(
"<ul class=\"radio-button-list{0}\">",
string.IsNullOrEmpty(cssClass) ? string.Empty : " " + cssClass);
foreach (var enumName in enumNames)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
enumName.Value
);
if (id.StartsWith("-"))
id = id.Remove(0, 1);
var value = enumName.Value;
sb.AppendFormat(
//"<li>{2} <label for=\"{0}\">{1}</label></li>", //Originol puts data in a list
"{2} <label for=\"{0}\">{1}</label>",
id,
HttpUtility.HtmlEncode(enumName.Text),
isDisabled
? htmlHelper.RadioButtonFor(expression, value, new { id, disabled = "disabled" }).ToHtmlString()
: htmlHelper.RadioButtonFor(expression, value, new { id }).ToHtmlString()
);
}
sb.Append("</ul>");
return MvcHtmlString.Create(sb.ToString());
}
public static IList<SelectListItem> GetSelectItemsForEnum(Type enumType, object selectedValue)
{
var selectItems = new List<SelectListItem>();
if (enumType.IsGenericType &&
enumType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
enumType = enumType.GetGenericArguments()[0];
selectItems.Add(new SelectListItem { Value = string.Empty, Text = string.Empty });
}
var selectedValueName = selectedValue != null ? selectedValue.ToString() : null;
var enumEntryNames = Enum.GetNames(enumType);
var entries = enumEntryNames
.Select(n => new
{
Name = n,
DisplayAttribute = enumType
.GetField(n)
.GetCustomAttributes(typeof(DisplayAttribute), false)
.OfType<DisplayAttribute>()
.SingleOrDefault() ?? new DisplayAttribute()
})
.Select(e => new
{
Value = e.Name,
DisplayName = e.DisplayAttribute.Name ?? e.Name,
Order = e.DisplayAttribute.GetOrder() ?? 50
})
.OrderBy(e => e.Order)
.ThenBy(e => e.DisplayName)
.Select(e => new SelectListItem
{
Value = e.Value,
Text = e.DisplayName,
Selected = e.Value == selectedValueName
});
selectItems.AddRange(entries);
return selectItems;
}
}
}
To have none of the radio buttons selected, you make the property nullable
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication? CCommmunication { get; set; }
If CCommmunication has an initial value of null, then no radio buttons will be selected.
But its unclear what you trying to do with all that (unnecessary) code in you extension method, in particular why you are creating IList<SelectListItem> (which is for generating a <select> tag). Your helper can simply be
public static class RadioButtonHelper
{
public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
Type type = Nullable.GetUnderlyingType(metaData.ModelType);
if (type == null || !type.IsEnum)
{
throw new ArgumentException(string.Format("The property {0} is not an enum", name));
}
StringBuilder html = new StringBuilder();
foreach (Enum item in Enum.GetValues(type))
{
string id = string.Format("{0}_{1}", metaData.PropertyName, item);
StringBuilder innerHtml = new StringBuilder();
innerHtml.Append(helper.RadioButtonFor(expression, item, new { id = id }));
innerHtml.Append(helper.Label(id, item.ToDescription()));
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobutton");
div.InnerHtml = innerHtml.ToString();
html.Append(div.ToString());
}
TagBuilder container = new TagBuilder("div");
container.AddCssClass("radiobutton-container");
container.InnerHtml = html.ToString();
return MvcHtmlString.Create(container.ToString());
}
}
which uses the following extension method
public static class EnumExtensions
{
public static string ToDescription(this Enum value)
{
if (value == null)
{
return null;
}
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
}
in association with the [Description] attribute applied to your enum values rather that the [Display] attribute (but you can easily modify that)