Writing textlist in codesys - codesys

How should I write a text list in CODESYS dynamically at runtime ?
I am using the text list as a source to display in a combo box (drop down list box)
Thanks in advance

First, you need to get the text list factory using the ComponentManager to create an instance:
const Guid TextListFactoryGuid = new Guid("{7a60005b-e690-45b3-8aca-cd15950a3e73}");
var textListFactory = (IObjectFactory)ComponentManager.Singleton.CreateInstance(TextListFactoryGuid);
Then, create an instance of the test list object itself:
var textListObject = (ITextListObject)textListFactory.Create();
The text list object will need to be added to the object manager:
SystemInstances.ObjectManager.AddObject(
SystemInstances.Engine.Projects.PrimaryProject.Handle,
parentGuid,
Guid.NewGuid(),
textListObject,
textListName,
-1);
Finally, now that you have the ITextListObject, you can add strings to it an id and an item:
textListObject.AddEmptyRow();
var textListElement = textListObject.GetTextListRowAt(textListObject.Count - 1);
textListElement.ID = id;
textListElement.Default = item;
Hope that's what you're after

Related

get value for specific question/item in a Google Form using Google App Script in an on submit event

I have figured out how to run a Google App Script project/function on a form submit using the information at https://developers.google.com/apps-script/guides/triggers/events#form-submit_4.
Once I have e I can call e.response to get a FormResponse object and then call getItemResponses() to get an array of all of the responses.
Without iterating through the array and checking each one, is there a way to find the ItemResponse for a specific question?
I see getResponseForItem(item) but it looks like I have to somehow create an Item first?
Can I some how use e.source to get the Form object and then find the Item by question, without iterating through all of them, so I could get the Item object I can use with getResponseForItem(item)?
This is the code I use to pull the current set of answers into a object, so the most current response for the question Your Name becomes form.yourName which I found to be the easiest way to find responses by question:
function objectifyForm() {
//Makes the form info into an object
var myform = FormApp.getActiveForm();
var formResponses = myform.getResponses()
var currentResponse = formResponses[formResponses.length-1];
var responseArray = currentResponse.getItemResponses()
var form = {};
form.user = currentResponse.getRespondentEmail(); //requires collect email addresses to be turned on or is undefined.
form.timestamp = currentResponse.getTimestamp();
form.formName = myform.getTitle();
for (var i = 0; i < responseArray.length; i++){
var response = responseArray[i].getResponse();
var item = responseArray[i].getItem().getTitle();
var item = camelize(item);
form[item] = response;
}
return form;
}
function camelize(str) {
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()#\+\?><\[\]\+]/g, '')
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
//Use with installable trigger
function onSubmittedForm() {
var form = objectifyForm();
Logger.log(form);
//Put Code here
}
A couple of important things.
If you change the question on the form, you will need to update your
code
Non required questions may or may not have answers, so check if answer exists before you use it
I only use installable triggers, so I know it works with those. Not sure about with simple triggers
You can see the form object by opening the logs, which is useful for finding the object names

How to return all entries from specific date in log.nsf

I need to return all entries (collection) from a specific date from the miscellaneus view in log.nsf using SSJS.
The views first category is "text" and the second category is a "date".
I tried to use the methods getAllEntriesByKey(vector) or createViewNavFromCategory(vector) but I got kind of stuck as the categorized columns contain different data types.
how can I do that?
Here is one thing I tried
var logdb = sessionAsSigner.getDatabase("domino01/....","log.nsf");
var logView = logdb.getView("MiscEvents")
var v = new java.util.Vector()
var nav = logView.createViewNavFromCategory("domino01/...\\2019-02-15")
return nav.getCount()
and here is another
var logdb = sessionAsSigner.getDatabase("domino01/...","log.nsf");
var logView = logdb.getView("MiscEvents")
var v = new java.util.Vector()
v.add("domino01/...")
v.add(session.createDateTime("Today").getDateOnly())
var nav = logView.getAllEntriesByKey(v)
return nav.getCount()
Just remove the getDateOnly call from your 2nd example code.
v.add(session.createDateTime("Today"))

Updating column in tableviwer

I have retrieved data from database and i am able to show it in Table of the Table Viewer but my task is on click of a row the data should be appear in another form from where i can edit it and on click of update the view should be updated with the new values.I am using viewer.addSelectionChangedListener to retrieve the selected row but i am not getting how to update the table .Please suggest me few ideas
I have written the below code in the constructor of my class so whenever object is created Table is generated and l1 is list of data which i am passing to another UI
input[i] = new MyModel(persons[i].getDateOfRegistration(), persons[i].getFirstName(),
persons[i].getMiddleName(), persons[i].getLastName(), persons[i].getGender(),
persons[i].getDob(), persons[i].getContactNumber(), persons[i].getMaritalStatus(),
persons[i].getAddress(), persons[i].getCountry(), persons[i].getBloodGroup(),
persons[i].getInsuranceDetails().getPolicyHolderName(),
persons[i].getInsuranceDetails().getPolicyNumber(),
persons[i].getInsuranceDetails().getSubscriberName(),
persons[i].getInsuranceDetails().getRelationshipToPatient());
viewer.setInput(input);
table.setHeaderVisible(true);
table.setLinesVisible(true);
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
StringBuffer sb = new StringBuffer("Selection - ");
int j = 0;
String[] s;
for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
sb.append(iterator.next() + ", ");
System.out.println("Testing::" + sb);
}
System.out.println(sb);
String result[] = new String[18];
List l1 = new ArrayList(100);
String[] parts = sb.toString().split("=");
for (int i = 0; i < parts.length; i++) {
System.out.println("s" + parts[i]);
String[] s1 = parts[i].split(",");
l1.add(s1[0]);
}
SWTPatientRegistrationUpdatePageEventView swtPatientRegistrationUpdatePageEventView = new SWTPatientRegistrationUpdatePageEventView();
swtPatientRegistrationUpdatePageEventView.openParentUpdateShell(l1);
// viewer.refresh();
//flag=false;
//refreshingData(list);
}
});
Make sure we will follow table viewer MVC architecture all the time. Steps we can do to resolve your issue isas follow:
Create proper datastructure(Model Class) to hold the data. and use the same in array which you set in viewer.setInput()
When you click/double click on table row, fetch the data and save it in datastructure created(with new object).
Pass that data structure to your form dialog.
when you are done with update in form. Fill the updated data in new Model object again.
And after form close, pass that model object back to parent.
updated the corresponding array element with object received from Form Dialog and just refresh the tableviewer.
Please let me know if you need some code module. Thanks

How to set default select in TwinColSelect Vaadin

I want preselect items in the containerAllClienteByAsociado, I try to preselect the same items in the containerAllCliente but also not found, sorry for bad english.
TwinColSelect colListClientes = new TwinColSelect();
private generateColListClientes(Asociado asociadoInstance){
clienteController = new ClienteController();
//Obtenemos el container con los datos
BeanItemContainer<Cliente> containerAllCliente = new BeanItemContainer<Cliente>(Cliente.class);
containerAllCliente.addAll(clienteController.getCollectionCliente());
BeanItemContainer<Cliente> containerAllClienteByAsociado = new BeanItemContainer<Cliente>(Cliente.class);
containerAllClienteByAsociado.addAll(asociadoInstance.getClientes());
colListClientes.setMultiSelect(true);
colListClientes.setImmediate(true);
colListClientes.setContainerDataSource(containerAllCliente);
colListClientes.setLeftColumnCaption("Listado de Clientes");
colListClientes.setRightColumnCaption("Clientes del Asociado");
colListClientes.setMultiSelect(true);
for (clienteTotales in containerAllCliente){
colListClientes.setValue(clienteTotales);
}
return colListClientes;
}
Instead of this:
`BeanItemContainer<Cliente> containerAllCliente = new BeanItemContainer<Cliente>(Cliente.class);`
Use this:
`BeanContainer<String,Cliente> containerAllCliente = new BeanContainer<String,Cliente>(Cliente.class);`
Also, while populating your twin-select, set its "id" property to be some identifying member variable/property of the Cliente.class
After populating, you can use:
twin-select.setValue(<value of identifying member data of the particular Cliente instance>);
This link might be of help:
https://dev.vaadin.com/svn/doc/book-examples/trunk/src/com/vaadin/book/examples/datamodel/BeanContainerExample.java
I hope it helps.
Instead of using setValue(...) for each item, just use it once and pass the whole collection as argument.
When using setValue(...) with single items, it deselects the previously selected values.
This is my solution, work fine in my code.
private generateColListClientes(Asociado asociadoInstance){
clienteController = new ClienteController();
//DEFINITION OF CONTAINERS
HashSet<Cliente> containerAllCliente = new HashSet<Cliente>();
containerAllCliente.addAll(clienteController.getCollectionCliente());
HashSet<Cliente> containerAllClienteByAsociado = new HashSet<Cliente>()
containerAllClienteByAsociado.addAll(asociadoInstance.getClientes())
//DEFINITION OF TWINCOLUMN
colListClientes.setLeftColumnCaption("Listado de Clientes");
colListClientes.setRightColumnCaption("Clientes del Asociado");
colListClientes.setMultiSelect(true);
colListClientes.setWidth("350px");
colListClientes.setImmediate(true);
HashSet<Cliente> preselected = new HashSet<Cliente>();
//TOUR TOTAL CLIENTS
for (Cliente cliente : containerAllCliente){
colListClientes.addItem(cliente);
//WE COMPARE TOTAL CLIENTS TO ASOCIADO.CLIENTES
for(Cliente clienteAsociado : containerAllClienteByAsociado) {
//COMPARE IDS AND PRESELECT IF IS THE SAME
if(cliente.id==clienteAsociado.id){
preselected.add(cliente);
}
}
}
colListClientes.setValue(preselected);
return colListClientes;
}

Using Drag-Sort ListView with SQLite DB

I'm trying to create a simple to-do-list app with an SQLite DB and a Drag-Sort ListView.
Right now I am binding data from an SQLite database cursor into a ListView using a SimpleCursorAdapter and adding items with an EditText view as explained in this tutorial.
I have moved everything into one activity and I have swapped the plain ListView with a Drag-Sort ListView. My issue is connecting the DB and Drag-Sort ListView together. The DLSV demos use a predefined array to fill fill the DSLV.
Snippet form DSLV:
DragSortListView lv = (DragSortListView) getListView();
lv.setDropListener(onDrop);
lv.setRemoveListener(onRemove);
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(this, R.layout.list_item1, R.id.text1, list);
setListAdapter(adapter);
Snippet from my existing code:
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
...
mDbHelper.createNote(noteName, "");
fillData();
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
Thank you and sorry if this doesn't make all that much sense.
Since you cannot reorder the items in a Cursor, you have to create a mapping between Cursor positions and ListView positions. This is done for you by the DragSortCursorAdapter class and subclasses so that the drag and drop reordering is maintained visually. If you need the new orders persisted (like to your database), then you must implement that logic yourself. The method getCursorPositions() will help you with this.
I have made use of Drag sort list view. Its amazing! but instead of using the dragsortcursoradapter i created my own trick. here it is.
What i have done is that whenever i swapped any item, i passed the new swapped list in an array to the database, deleted the table and recreated the new updated table. here is my code
here is the code snippet from my database handler
public void onUpdateToDoTable(ArrayList<Task> taskList) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKTODO);
String CREATE_TASK_TODO_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_TASKTODO + "(" + SEQ_ID + " INTEGER PRIMARY KEY,"
+ TASK_NAME + " TEXT )";
db.execSQL(CREATE_TASK_TODO_TABLE);
for (int i = 0; i < taskList.size(); i++) {
ContentValues values = new ContentValues();
values.put(TASK_NAME, taskList.get(i).getTask());
db.insert(TABLE_TASKTODO, null, values);
}
db.close();
}
then on using drop listener
i called the above method..
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
#Override
public void drop(int from, int to) {
Task item = adapter.getItem(from);
adapter.notifyDataSetChanged();
adapter.remove(item);
adapter.insert(item, to);
db.onUpdateToDoTable(list);
Log.d("LIST", db.getAllToDoTasks().toString());
}
};
db is my object of database handler. whole source code is available at dragdroplistview. amazing example. this was a life saver for me. Ciao!
There is a github project available at https://github.com/jmmcreynolds/dslv-db-demo
This demo includes a working example of how to setup a DragSortListView that will save the changes that you make to the list (position, add/delete) to a database.
I have used it just now. Its perfect demo project available for using DSLV with SQLiteDB.
Thanks to github user jmmcreynolds.