Converting C# Razor view syntax for checkboxlist into VB.Net - html-helper

Here is the HTML code for "CheckBoxListFor" which I copied from "http://www.codeproject.com/Articles/292050/CheckBoxList-For-a-missing-MVC-extension" Could you please help me out in converting this C# code into VB.Net?
#Html.CheckBoxListFor(model => model.PostedCities.CityIDs,
model => model.AvailableCities,
entity => entity.Id,
entity => entity.Name,
model => model.SelectedCities)

#Html.CheckBoxListFor(Function(model) model.PostedCities.CityIDs, _
Function(model) model.AvailableCities, _
Function(entity) entity.Id, _
Function(entity) entity.Name, _
Function(model) model.SelectedCities)

#Html.CheckBoxListFor(Function(model) model.PostedCities.CityIDs, _
Function(model) model.AvailableCities, _
Function(entity) entity.Id, _
Function(entity) entity.Name, _
Function(entity) If(Model.SelectedCities Is Nothing, False, Model.SelectedCities.Contains(entity.Id)),
htmlListInfo, Function(htmlAttribute) New With {.class = "chkBoxList"})

Related

Ef core could not translate my custom sql server STRING_AGG function

String.Join in efcore not support and I want to get list of string with separator like sql function String_Agg
I tried to create custom sql server function but i get this error:
The parameter 'columnPartArg' for the DbFunction 'QueryHelper.StringAgg(System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=]],System.String)' has an invalid type 'IEnumerable'. Ensure the parameter type can be mapped by the current provider.
This is my function and OnModelCreatingAddStringAgg for register it in my dbcontext
public static string StringAgg(IEnumerable<string> columnPartArg, [NotParameterized] string separator)
{
throw new NotSupportedException();
}
public static void OnModelCreatingAddStringAgg(ModelBuilder modelBuilder)
{
var StringAggFuction = typeof(QueryHelper).GetRuntimeMethod(nameof(QueryHelper.StringAgg), new[] { typeof(IEnumerable<string>), typeof(string) });
var stringTypeMapping = new StringTypeMapping("NVARCHAR(MAX)");
modelBuilder
.HasDbFunction(StringAggFuction)
.HasTranslation(args => new SqlFunctionExpression("STRING_AGG",
new[]
{
new SqlFragmentExpression((args.ToArray()[0] as SqlConstantExpression).Value.ToString()),
args.ToArray()[1]
}
, nullable: true, argumentsPropagateNullability: new[] { false, false }, StringAggFuction.ReturnType, stringTypeMapping));
}
and this code run above function
_context.PersonnelProjectTimeSheets.GroupBy(c => new { c.Date.Date, c.PersonnelId, c.Personnel.PersonnelCode, c.Personnel.FirstName, c.Personnel.LastName})
.Select(c => new PersonnelProjectTimeOutputViewModel
{
IsConfirmed = c.Min(c => (int)(object)(c.IsConfirmed ?? false)) == 1,
PersonnelDisplay = c.Key.PersonnelCode + " - " + c.Key.FirstName + " " + c.Key.LastName,
PersonnelId = c.Key.PersonnelId,
Date = c.Key.Date,
ProjectName = QueryHelper.StringAgg(c.Select(x=>x.Project.Name), ", "),
TotalWorkTime = 0,
WorkTimeInMinutes = c.Sum(c => c.WorkTimeInMinutes),
});
And also i change my StringAgg method input to
string columnPartArg
and change SqlFunctionExpression of OnModelCreatingAddStringAgg to
new[]
{
new SqlFragmentExpression((args.ToArray()[0] as
SqlConstantExpression).Value.ToString()),
args.ToArray()[1]
}
and change my query code to
ProjectName = QueryHelper.StringAgg("Project.Name", ", ")
now when run my query, sql server could not recognize the Project
i guess the parameter 'columnPartArg' of dbfunction 'STRING_AGG' is varchar or nvarchar. right?
most database function or procedure has not table value as parameter.
in this case,use EFCore's 'client evaluation' is good sulution. linq like below:
_context.PersonnelProjectTimeSheets.GroupBy(c => new { c.Date.Date, c.PersonnelId, c.Personnel.PersonnelCode, c.Personnel.FirstName, c.Personnel.LastName})
.Select(c => new PersonnelProjectTimeOutputViewModel
{
IsConfirmed = c.Min(c => (int)(object)(c.IsConfirmed ?? false)) == 1,
PersonnelDisplay = c.Key.PersonnelCode + " - " + c.Key.FirstName + " " + c.Key.LastName,
PersonnelId = c.Key.PersonnelId,
Date = c.Key.Date,
ProjectName = string.Join(", ",c.Select(x=>x.Project.Name)),//Client evaluation
TotalWorkTime = 0,
WorkTimeInMinutes = c.Sum(c => c.WorkTimeInMinutes),
});

How to set content into mui-rte with selenium webdriver in python?

I am using mui-rte rich text editor (https://github.com/niuware/mui-rte) in a react project. I am not able to figure out how to input text to the rte input area when writing a selenium webdriver integration test.
As I understand correctly, mui-rte is a materia-ui wrapper of draftjs. The react code is simply:
<MUIRichTextEditor
onChange={onChange}
value={initial}
{...rest}
/ >
This generates the following html elements:
<div id="mui-rte-container" class="MUIRichTextEditor-container-73">
<div id="mui-rte-toolbar" class="MUIRichTextEditor-toolbar-84">
...
</div>
<div id="mui-rte-editor" class="MUIRichTextEditor-editor-75">
<div id="mui-rte-editor-container" class="MUIRichTextEditor-hidePlaceholder-79 MUIRichTextEditor-editorContainer-76">
<div class="DraftEditor-root">
<div class="DraftEditor-editorContainer">
<div aria-describedby="placeholder-9mnek" class="notranslate public-DraftEditor-content" role="textbox" spellcheck="false" style="outline:none;user-select:text;-webkit-user-select:text;white-space:pre-wrap;word-wrap:break-word" contenteditable="true">
<div data-contents="true"><div class="" data-block="true" data-editor="7kjuh" data-offset-key="8a2rc-0-0">
<div data-offset-key="8a2rc-0-0" class="public-DraftStyleDefault-block public-DraftStyleDefault-ltr">
<span data-offset-key="8a2rc-0-0">
<br data-text="true">
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I can easily find any of the element but when I try this for example:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.by import By
rte_editor = WebDriverWait(self.driver, 2).until(
EC.presence_of_element_located((By.ID, id))
)
rte_input = bio_rte.find_element_by_xpath("//div[#role='textbox']")
rte_input.send_keys("Hello")
I get:
E selenium.common.exceptions.ElementNotInteractableException: Message: Element <div class="notranslate public-DraftEditor-content"> is not reachable by keyboard
With all elements that I have tried.
What is the correct way to input text into draft.js rte with selenium-webdriver in python? I am quite new to selenium+webdriver and any help will be appreciated, be it in python, JavaScript or other flavor of selenium-webdriver API.
I have a sample project here: https://github.com/vessper/formik-mui-rte-example
update:
Including the stack trace from the error:
self = <test.TestBase testMethod=test_input_text_in_rte>
def test_input_text_in_rte(self):
rte_input = WebDriverWait(self.driver, 20).until(
EC.element_to_be_clickable(
> (By.XPATH, '//div[#class="notranslate public-DraftEditor-content" and #role="textbox"]'))
)
test.py:25:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <selenium.webdriver.support.wait.WebDriverWait (session="38c21bf5-27ea-499d-9831-e8755a10f57a")>
method = <selenium.webdriver.support.expected_conditions.element_to_be_clickable object at 0x7f7115fe7198>, message = ''
def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is not False."""
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
> raise TimeoutException(message, screen, stacktrace)
E selenium.common.exceptions.TimeoutException: Message:
../../../.virtualenvs/ml2/lib/python3.7/site-packages/selenium/webdriver/support/wait.py:80: TimeoutException
================================================================= 1 failed in 24.70s ==================================================================
In my case it was a draft.js rich text editor with a contenteditable div
async sendKeysToContentEditableDiv(element, text) {
const script = `var txtarea = arguments[0],txt = arguments[1];
txtarea.dispatchEvent(new Event("focus"));
var txtEvt = document.createEvent("TextEvent");
txtEvt.initTextEvent("textInput", true, true, null, txt);
txtarea.dispatchEvent(txtEvt);
txtarea.dispatchEvent(new Event("blur"));`;
await this.driver.executeScript(script, element, text);
}
The desired element is a ReactJS enabled element so to locate and send a character sequence to the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following solutions:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.notranslate.public-DraftEditor-content[role='textbox']"))).send_keys("Vess_Perfanov")
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[#class='notranslate public-DraftEditor-content' and #role='textbox']"))).send_keys("Vess_Perfanov")
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Update
As the click() is still not invoked with WebDriverWait you can use ActionChains as follows:
Using CSS_SELECTOR:
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.notranslate.public-DraftEditor-content[role='textbox']"))).send_keys("Vess_Perfanov")
ActionChains(driver).move_to_element(element).click(element).send_keys("Vess_Perfanov").perform()
Using XPATH:
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[#class='notranslate public-DraftEditor-content' and #role='textbox']"))).send_keys("Vess_Perfanov")
ActionChains(driver).move_to_element(element).click(element).send_keys_to_element(element, "Vess_Perfanov").perform()
There is an inline label element from Material-UI that needs to be clicked first to uncover the underlying text field. So the following work for me.
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import unittest
class TestBase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get(URL)
def tearDown(self):
self.driver.close()
def get_by_id(self, id):
return WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.ID, id))
)
def test_input_text_in_rte(self):
description_msg = "Hello There"
rte_container = self.get_by_id('mui-rte-container')
rte_label = rte_container.find_element_by_xpath("//*[contains(text(), 'Description:')]")
actions = ActionChains(self.driver)
actions.move_to_element(rte_label)
actions.click(rte_label)
actions.perform()
rte_input = WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.XPATH,
'//div[#class="notranslate public-DraftEditor-content" and #role="textbox"]'))
)
rte_input.send_keys(description_msg)
Thanks to #DebanjanB for the suggestions that are incorporated in the code above.

Show the particular component of the screen when backed

I've a screen with a list of components. When I scroll down the screen, go to the next screen from a button (lets say 20th component) and go back to the previous screen with back btn, the previous screen (with list of components) displays with the first component there. How can I show the screen with 20th component when backed?
Look at the video here
Container mainContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
mainContainer.setScrollableY(true);
for (Map<String, Object> entrySet : protectedPlantsList) {
String title = entrySet.get("title").toString();
String sname = entrySet.get("sname").toString();
String nname = entrySet.get("nname").toString();
Label plantSpeciesLabel = new Label(title);
TextArea family = new TextArea(sname);
TextArea nepaliName = new TextArea(nname);
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Button infoIcon1 = new Button("", "TextField");
infoIcon1.addActionListener(e -> {
new ThreatCategory(res, threatData1.getName(), infoIcon1.getName(), threatList).show();
});
mainContainer.add(BorderLayout.centerEastWest(plantSpeciesLabel, ...., .....));
}
Update 1:
ProtectedPlantAndSpecies class:
Container mainContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
mainContainer.setScrollableY(true);
for (Map<String, Object> entrySet : protectedPlantsList) {
String title = entrySet.get("title").toString();
String sname = entrySet.get("sname").toString();
String nname = entrySet.get("nname").toString();
Label plantSpeciesLabel = new Label(title);
TextArea family = new TextArea(sname);
TextArea nepaliName = new TextArea(nname);
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Button infoIcon1 = new Button("", "TextField");
infoIcon1.addActionListener(e -> {
Form myDestinationForm = new ThreatCategory(res, cat, cat_description, threatList);
myDestinationForm.addShowListener(f -> infoIcon1.requestFocus());
myDestinationForm.show();
});
mainContainer.add(BorderLayout.centerEastWest(plantSpeciesLabel, ...., .....));
}
ThreatCategory class:
- - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
Command backCommand = new Command("Back", backFontImage) {
#Override
public void actionPerformed(ActionEvent evt) {
new ProtectedPlantAndSpecies(res, true).show();
}
};
- - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
Do something like this:
Form hi = new Form("Last", BoxLayout.y());
Button t = new Button("Next");
hi.add(t);
t.addActionListener(e -> {
Form f = new Form("Showing Last", BoxLayout.y());
for(int iter = 0 ; iter < 20 ; iter++) {
f.add(new Button("Button " + iter));
}
Button last = new Button("Last");
f.add(last);
f.addShowListener(ee -> last.requestFocus());
f.show();
});

Picker issue in codenameone

I have two pickers. The 2nd picker should be active as soon as the 1st picker is selected. But If the 2nd picker is clicked at first, the empty picker string is opened and then dialog stating choose the 1st picker is shown. How can I not show the empty picker string list if the first picker is not selected ?
Picker datePicker = new Picker();
datePicker.addActionListener(e -> {
SimpleDateFormat sf = new SimpleDateFormat("y");
String a = sf.format(datePicker.getDate());
SimpleDateFormat sf1 = new SimpleDateFormat("M");
String b = sf1.format(datePicker.getDate());
SimpleDateFormat sf2 = new SimpleDateFormat("d");
String c = sf2.format(datePicker.getDate());
getStartDate = a + "-" + b + "-" + c;
});
stationPicker.addActionListener(e -> {
if (!getStartDate.equals("")) {
_ _ _ _ _ _ _ _ _ ___ _
_ _ _ _ _ _ _ _ _ ___ _
}else{
Dialog.show("Warning", "Please choose the date first", "ok", null);
stationPicker.setSelectedString("Select the service center");
}
});
Have a look at the video so that the issue is more clear.
https://www.youtube.com/watch?v=Fmg13qm08Is

How to get names of all sheets in excel

I want to create a method to get names of all sheets in a workbook. My workbook has 7 sheets. If I want to read and save names of sheets to the variable excelSheets, I receive 9 names, where two names response to non-exists sheets ("lists$" and "TYPAB").
I don't understand where is the problem? How can I get names only the existing sheets?
public List<string> NamesOfSheets(string filename)
{
string con = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=Yes;'";
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
List<string> excelSheets;
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheets = dt.Rows.Cast<DataRow>()
.Select(i => i["TABLE_NAME"].ToString()).ToList();
return excelSheets;
}
catch (Exception)
{
throw new Exception("Failed to get SheetName");
}
}
}
Oscar, thanks for your help, but office interlop doesn't solve my problem.
I found that "lists$" is hidden sheet, so only name TYPAB doesn't respond to any existing sheet.
So I added clause where and problem is solved. :)
public List<string> NamesOfSheets(string filename)
{
string con = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=Yes;'";
List<string> excelSheets;
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheets = dt.Rows.Cast<DataRow>()
.Where(i => i["TABLE_NAME"].ToString().EndsWith("$") || i["TABLE_NAME"].ToString().EndsWith("$'"))
.Select(i => i["TABLE_NAME"].ToString()).ToList();
return excelSheets;
}
catch (Exception)
{
throw new Exception("Failed to get SheetName");
}
}
}
Why not use Office Interop for this?
foreach (Excel.Worksheet displayWorksheet in Globals.ThisWorkbook.Worksheets)
{
Debug.WriteLine(displayWorksheet.Name);
}
https://msdn.microsoft.com/en-us/library/59dhz064.aspx

Resources