Guidewire : Refresh List view when the button is clicked - guidewire

The Listview(partial page) is not getting refreshed when I click the button. It keeps on adding the rows whenever the buttons are clicked.
Below are the functions for adding the drivers.
function getDriversFromPolicy_CA7() : CA7CommAutoDriver[] {
var drivers = this.Policy.LatestPeriod.CA7Line.Drivers // **this** Contingency Entity
var excludeDrivers = this.ExcludeDrivers_CA7.toList() // Contingency entity has a ExcludeDrivers_CA7 array
if(excludeDrivers.Empty) {
drivers?.each(\driver -> this.addToExcludeDrivers_CA7(driver) )
} else {
drivers.each(\driver -> {
if (excludeDrivers.where(\elt -> elt.LicenseNumber == driver.LicenseNumber).toList().Count == 0) {
this.addToExcludeDrivers_CA7(driver)
}
})
}
return this.ExcludeDrivers_CA7
}
function getDriversFromTransaction_CA7() : CA7CommAutoDriver[] {
var drivers = this.PolicyPeriod.CA7Line.Drivers.toList()
var excludeDrivers = this.ExcludeDrivers_CA7.toList()
if(this.ExcludeDrivers_CA7.IsEmpty) {
drivers?.each(\driver -> this.addToExcludeDrivers_CA7(driver) )
} else {
// this.ExcludeDrivers_CA7.toList().retainAll(drivers.toList())
drivers.each(\driver -> {
if (excludeDrivers.where(\elt -> elt.LicenseNumber == driver.LicenseNumber).toList().Count == 0) {
this.addToExcludeDrivers_CA7(driver)
}
})
}
return this.ExcludeDrivers_CA7
}
function removeDrivers_CA7(driver : CA7CommAutoDriver) {
this.removeFromExcludeDrivers_CA7(driver)
}
pcf screenshot for reference
UI screenshot for reference

Related

Publish background context Core Data changes in a SwiftUI view without blocking the UI

After running a background-context core data task, Xcode displays the following purple runtime warning when the updates are published in a SwiftUI view:
"[SwiftUI] Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."
Besides the ContentView.swift code below, I also added container.viewContext.automaticallyMergesChangesFromParent = true to init in the default Persistence.swift code.
How can I publish the background changes on the main thread to fix the warning? (iOS 14, Swift 5)
Edit: I've changed the code below, in response to the first answer, to clarify that I'm looking for a solution that doesn't block the UI when a lot of changes are saved.
struct PersistenceHelper {
private let context: NSManagedObjectContext
init(context: NSManagedObjectContext = PersistenceController.shared.container.viewContext) {
self.context = context
}
public func fetchItem() -> [Item] {
do {
let request: NSFetchRequest<Item> = Item.fetchRequest()
var items = try self.context.fetch(request)
if items.isEmpty { // Create items if none exist
for _ in 0 ..< 250_000 {
let item = Item(context: context)
item.timestamp = Date()
item.data = "a"
}
try! context.save()
items = try self.context.fetch(request)
}
return items
} catch { assert(false) }
}
public func updateItemTimestamp(completionHandler: #escaping () -> ()) {
PersistenceController.shared.container.performBackgroundTask({ backgroundContext in
let start = Date(), request: NSFetchRequest<Item> = Item.fetchRequest()
do {
let items = try backgroundContext.fetch(request)
for item in items {
item.timestamp = Date()
item.data = item.data == "a" ? "b" : "a"
}
try backgroundContext.save() // Purple warning appears here
let interval = Double(Date().timeIntervalSince(start) * 1000) // Artificial two-second delay so cover view has time to appear
if interval < 2000 { sleep(UInt32((2000 - interval) / 1000)) }
completionHandler()
} catch { assert(false) }
})
}
}
// A cover view with an animation that shouldn't be blocked when saving the background context changes
struct CoverView: View {
#State private var toggle = true
var body: some View {
Circle()
.offset(x: toggle ? -15 : 15, y: 0)
.frame(width: 10, height: 10)
.animation(Animation.easeInOut(duration: 0.25).repeatForever(autoreverses: true))
.onAppear { toggle.toggle() }
}
}
struct ContentView: View {
#State private var items: [Item] = []
#State private var showingCoverView = false
#State private var refresh = UUID()
let persistence = PersistenceHelper()
let formatter = DateFormatter()
var didSave = NotificationCenter.default
.publisher(for: .NSManagedObjectContextDidSave)
// .receive(on: DispatchQuene.main) // Doesn't help
var body: some View {
ScrollView {
LazyVStack {
Button("Update Timestamp") {
showingCoverView = true
persistence.updateItemTimestamp(completionHandler: { showingCoverView = false })
}
ForEach(items, id: \.self) { item in
Text(formatter.string(from: item.timestamp!) + " " + (item.data ?? ""))
}
}
}
.id(refresh)
.onAppear {
formatter.dateFormat = "HH:mm:ss"
items = persistence.fetchItem()
}
.onReceive(didSave) { _ in
items = persistence.fetchItem()
}
.fullScreenCover(isPresented: $showingCoverView) {
CoverView().onDisappear { refresh = UUID() }
}
}
}
Since you are performing a background task, you are on a background thread - rather than the main thread.
To switch to the main thread, change the line producing the runtime warning to the following:
DispatchQueue.main.async {
try backgroundContext.save()
}
You should use Combine and observe changes to your background context and update State values for your UI to react.
#State private var coreDataAttribute = ""
var body: some View {
Text(coreDataAttribute)
.onReceive(
CoreDataManager.shared.moc.publisher(for: \.hasChanges)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.global())
.map{_ in CoreDataManager.shared.fetchCoreDataValue()}
.filter{$0 != coreDataAttribute}
.receive(on: DispatchQueue.main))
{ value in
coreDataAttribute = value
}
}

concurrent query and insert have any side effect in android with objectbox?

In my android project, I use objectbox as database, if I insert with lock and query without lock, is there any side effect ? such as crash and so on.
fun query(uniqueId: String = ""): MutableList<T> {
if (box.store.isClosed) return mutableListOf()
val query = box.query()
withQueryBuilder(query, uniqueId)
//开始
return query.build().find()
}
private fun putInner(entity: T): Long {
synchronized(box.store) {
if (box.store.isClosed) return -1
if (entity.unique.isBlank()) {
entity.unique = entity.providerUnique()
}
entity.timestamp = System.currentTimeMillis()
return try {
box.put(entity).let { id -> entity.id = id }
entity.id
} catch (ex: Exception) {
-1
}
}
}

pasting the elements multiple times in rappid js

I am using joint js and rappid with the angular 8 and I have done most of the tasks but in using keyboard events there seems to be a issue. When I copy an element and pasted it on graph it works fine. But for the next element selected it is pasting that new element multiple times.
Here is my code.
var keyboard = this.keyboard = new joint.ui.Keyboard();
var clipboard = this.clipboard = new joint.ui.Clipboard();
selection.collection.on('reset add remove', this.onSelectionChange.bind(this));
paper.on('element:pointerdown', function(elementView: joint.dia.ElementView,evt: joint.dia.Event) {
clipboard.clear();
keyboard.on({
'ctrl+c': function(evt) {
selection.collection.reset();
//clipboard.clear();
selection.collection.add(elementView.model);
clipboard.copyElements(selection.collection, paper.model);
//console.log(clipboard);
},
'ctrl+v': function(evt) {
//console.log(clipboard);
var pastedCells = clipboard.pasteCells(graph, {
translate: { dx: 20, dy: 20 },
useLocalStorage: true
});
var elements = _.filter(pastedCells, function(cell) {
return cell.isElement();
});
//console.log(elements);
// Make sure pasted elements get selected immediately. This makes the UX better as
// the user can immediately manipulate the pasted elements.
selection.collection.reset(elements);
},
});
});
onSelectionChange() {
const { paper, selection,clipboard } = this;
const { collection } = selection;
//console.log(collection.models.child);
// collection.models.forEach(function(model: joint.dia.Element) { if(!model.collection) { clipboard.clear();}});
paper.removeTools();
joint.ui.Halo.clear(paper);
joint.ui.FreeTransform.clear(paper);
joint.ui.Inspector.close();
if(collection.first() == undefined){
clipboard.clear();
}
if (collection.length === 1) {
var primaryCell = collection.first();
var primaryCellView = paper.requireView(primaryCell);
selection.destroySelectionBox(primaryCell);
this.selectPrimaryCell(primaryCellView);
} else if (collection.length === 2) {
collection.each(function(cell) {
selection.createSelectionBox(cell);
});
}
}
selectPrimaryCell(cellView) {
var cell = cellView.model
if (cell.isElement()) {
this.selectPrimaryElement(cellView);
} else {
this.selectPrimaryLink(cellView);
}
//this.createInspector(cell);
}
selectPrimaryElement(elementView) {
var element = elementView.model;
console.log(element.collection);
new joint.ui.FreeTransform({
cellView: elementView,
allowRotation: false,
preserveAspectRatio: !!element.get('preserveAspectRatio'),
allowOrthogonalResize: element.get('allowOrthogonalResize') !== false
}).render();
}
I have different thing like resetting the clipboard , resetting the selection and resetting the keyboard but nothing seems to be working.

Grails security filter all action but except one

I'm gonna create a security filter for my project. I check if !session.user then redirect to action error.
Here is my current code:
all(controller: 'accounting|installation|installer|sales|service|serviceOrder|document', action: '*') {
before = {
if (!session.user) {
redirect(controller: 'installation', action: 'errors')
return false
}
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
However the point is that session.user being created in controller 'installation' and action 'index'. So how can I filter without index action?
Any suggestions will be appreciated. Thanks.
You can use invert:true
e.g
def filters = {
allExceptIndex(controller:"installation",action:"index",invert:true) {
before = {
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
}
For further reference see Blog
Try this
all(controller: 'accounting|installation|installer|sales|service|serviceOrder|document', action: '*') {
before = {
if (!(controllerName == 'installation' && actionName == 'index')) {
if (!session.user) {
redirect(controller: 'installation', action: 'errors')
return false
}
}
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
Hope I have understood your question ,Since you want to exclude action index then ,try this ..
all(controller: 'accounting|installation|installer|sales|service|serviceOrder|document', action: '*',actionExclude:'index'){....
Regards

Add tab to the tabpanel on mvc

I have a menu and some menu items.when I clcik to menu item I create new panle codebehind and add it to main tabpanel.so far so good ,but it seems for every click on the menu,panel created from the begining,plus,change place of the the tabs.how can I solve this.
here is the my Index.cshtml
<body>
#Html.X().ResourceManager()
#(
Html.X().Viewport()
.Layout(LayoutType.Border)
.Items(
Html.X().Panel()
.Region(Region.West)
.Title("main menu")
.Width(200)
.Collapsible(true)
.Split(true)
.MinWidth(175)
.MaxWidth(400)
.MarginSpec("5 0 5 5")
.Layout(LayoutType.Accordion)
.Items(
Html.X().MenuPanel()
.Collapsed(true)
.Icon(Icon.Note)
.AutoScroll(true)
.Title("menu")
.ID("PNL34")
.BodyPadding(0)
.Menu(menu => {
menu.Items.Add(Html.X().MenuItem().ID("1a").Text("test1").Icon(Icon.Anchor)
.DirectEvents(m => { m.Click.Url = "Desktop/AddTab";
m.Click.ExtraParams.Add(new { conid = "TabPanel1" ,pnlid="tabpnl10",viewname="Urunler"});
}));
menu.Items.Add(Html.X().MenuItem().ID("2a").Text("test2").Icon(Icon.Anchor)
.DirectEvents(m =>
{
m.Click.Url = "Desktop/AddTab";
m.Click.ExtraParams.Add(new { conid = "TabPanel1", pnlid = "tabpnl11", viewname = "Siparisler" });
}));
})
)
,
Html.X().TabPanel()
.ID("TabPanel1")
.Region(Region.Center)
.Title("E-TICARET")
.MarginSpec("5 5 5 0")
))
and codebehind controller
public ActionResult AddTab(string conid,string pnlid,string viewname)
{
var cmp = this.GetCmp<Panel>(pnlid);
var cmp2 = this.GetCmp<TabPanel>(conid);
if (cmp.ActiveIndex==-1)
{
var result = new Ext.Net.MVC.PartialViewResult
{
ViewName = viewname,
ContainerId = conid,
RenderMode = RenderMode.AddTo,
WrapByScriptTag = false
};
cmp2.SetActiveTab(pnlid);
return result;
}
else
{
return null;
}
}
This is not going to work.
if (cmp.ActiveIndex == -1)
In WebForms it is retrieved from the Post data. There is no a WebForms-like Post in MVC. You should send all the required information with a request.
Also if you don't need a tab to be rendered if it is already exists, just stop a request. You can determine on client if a tab is already there or not.

Resources