UWP - Proper way of passing parameters between pages - windows-10

Suppose I want to pass one object (reference) through several pages. I can navigate and pass parameters via Frame.Navigate(typeof(FirstPage), object). But how to pass the reference back on back press properly?
protected override void OnNavigatedTo(NavigationEventArgs e) {
if (e.Parameter is SomeClass) {
this.someObject = (SomeClass)e.Parameter;
}
else {
this.someObject = new SomeClass();
}
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
SystemNavigationManager.GetForCurrentView().BackRequested += OnHardwareButtonsBackPressed;
base.OnNavigatedTo(e);
}
private void OnHardwareButtonsBackPressed(object sender, BackRequestedEventArgs e) {
// This is the missing line!
Frame.Navigate(typeof(FirstPage), this.someObject);
}
But when I press back button it goes back to the FirstPage OnNavigatedTo with no parameter, and then back to the SecondPage OnHardwareButtonsBackPressed and then back to FirstPage OnNavigatedTo with filled parameter.
Could you please advice me some better approach?

In your back handler, don't navigate forwards again, just call GoBack -- and it's typically easier if you handle that at a global level rather than at a page level.
You can store your application state (the things you want to persist across page navigations) in global / static objects, or you could directly modify the object that was passed from the initial navigation (if the calling page still has a reference, it will be able to see the changes).
I would consider doing a search for "MVVM Windows Apps" and looking at some of the results to learn about a common way of building XAML apps.

Related

How do I clear the input of a Smart Panel dialog (PXFilter)?

I have created a smart panel in a custom screen to ask for user input that is used to facilitate moving stock from normal inventory into an isolation area. My original smart panel example that I always use is the Copy Order in the SOOrderEntry graph (SO301000). In this case, I need to do a bit of validation, and the user may very well decide to close the smart panel and update the document in the screen before reopening the smart panel again. If the user clicks the cancel button, I need the smart panel to reset back to defaults every time it is opened.
I thought this might be handled in the ASPX screen definition, but I can't find the right setting for the form itself. I use AutoRefresh on selectors to refresh every time they are opened, but I need the form itself to do the same and refresh back to default every time it is opened. The desired behavior DOES occur automatically when I navigate to another record of the graph's primary DAC, but I cannot seem to force the smart panel to refresh automatically every time it is opened. I looked at the various options for the form in ASPX, but I overlooked it if it is there.
Similarly to CopyOrder on SOOrderEntry, here is my code sample from my graph.
public PXFilter<StockParamFilter> stockparamfilter;
#region AddFromStock
public PXAction<MyTag> addFromStock;
[PXUIField(DisplayName = Messages.AddFromStock, MapEnableRights = PXCacheRights.Insert, MapViewRights = PXCacheRights.Insert)]
[PXButton]
protected virtual IEnumerable AddFromStock(PXAdapter adapter)
{
MyTag tag = Tags.Current;
if (tag?.TranRefNbr != null)
{
throw new PXException(Messages.TagAlreadyReceived);
}
MyTagEntry graph = PXGraph.CreateInstance<MyTagEntry>();
WebDialogResult dialogResult = stockparamfilter.AskExt(setStockStateFilter, true);
if (dialogResult == WebDialogResult.OK || (IsContractBasedAPI && dialogResult == WebDialogResult.Yes))
{
// My Business Logic Here
}
return adapter.Get();
}
#endregion
#region CheckStockParams (OK Button in Smart Panel)
public PXAction<MyTag> checkStockParams;
[PXUIField(DisplayName = "OK", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
[PXLookupButton]
public virtual IEnumerable CheckStockParams(PXAdapter adapter)
{
return adapter.Get();
}
#endregion
#region setStockStateFilter
private void setStockStateFilter(PXGraph aGraph, string ViewName)
{
checkStockStateFilter();
}
#endregion
#region checkStockStateFilter
protected virtual void checkStockStateFilter()
{
// My Business Logic Here to set bool enableStockParams = ???
checkStockParams.SetEnabled(enableStockParams);
}
#endregion
This seems like something I did in the past, but I cannot seem to locate the code. I think it is related to stockparamfilter being a PXFilter instead of a PXSelect (or SelectFrom).
I have tried stockparamfilter.ClearDialog() with no luck. I have tried stockparamfilter.RequestRefresh() with no luck. I even tried stockparamfilter.DeleteCurrent() which seemed to work when I hit Cancel, but then my code did not execute when I hit OK. I also seemed to get the desired results when I used stockparamfilter.Cache.SetDefaultExt<StockParamFilter.locationID>(filter); on every field, until I hit OK which did nothing. It's like every time I try to manipulate the filter, I break the smart panel without any errors in the trace. In fact, here is the list of what I tried unsuccessfully:
StockParamFilter filter = stockparamfilter.Current;
stockparamfilter.View.Clear();
stockparamfilter.View.RequestRefresh();
stockparamfilter.Cache.Clear();
stockparamfilter.View.RequestRefresh();
stockparamfilter.View.RequestFiltersReset();
stockparamfilter.DeleteCurrent();
stockparamfilter.ClearDialog();
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.locationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.toLocationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.qty>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.lotSerialNbr>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.origRefNbr>(filter);
What is the ASPX code or C# Code that will let me reset the smart panel to defaults?
A big thanks to Hughes Beausejour at Acumatica for the offline assist. Posting solution for anyone else that may have this issue.
First, it is important to understand that AskExt generates 2 passes of the code. The first pass prompts the smart panel. Upon response to the smart panel, the code executes again, but in this second context skips the ask. With that in mind, the reason for my code not working became clear, as Hughes explained to me.
To execute the code when the form is initialized, that code must be executed before the ask occurs. Otherwise, the form is presented and then the initializing code is executed too late. Additionally, it must be conditioned such that it only fires when the smart panel was not given an OK response by the user. (Not realizing the code executes twice, I was unaware that I was resetting the fields on both passes. When I could get the form to reset, the subsequent processing would fail becuase I was resetting it on that pass as well.) Following that code, the AskExt can be used to present the form along with the normal processing of the user response.
My code, to show the working example, is as follows:
StockParamFilter filter = stockparamfilter.Current;
// If the user response is anything except an affirmative, default the fields
if (!(stockparamfilter.View.Answer == WebDialogResult.OK || (IsContractBasedAPI && stockparamfilter.View.Answer == WebDialogResult.Yes)))
{
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.locationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.toLocationID>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.qty>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.lotSerialNbr>(filter);
stockparamfilter.Cache.SetDefaultExt<StockParamFilter.origRefNbr>(filter);
}
// Present the Smart Panel Dialog (happens only on the 1st pass - AskExt causes the code to execute twice)
WebDialogResult dialogResult = stockparamfilter.AskExt(setStockStateFilter, true);
// If the response was affirmative, execute the business logic
if (dialogResult == WebDialogResult.OK || (IsContractBasedAPI && dialogResult == WebDialogResult.Yes))
{
// Do Business Logic Based On User Response In Smart Panel
}

create setup form for custom module

I have a custom module getting executed right after the PDFGenerator finished. I followed this guide on how to create a custom module
https://stackoverflow.com/a/55799101/9945420
When processing a batch document I want to manipulate the generated PDF file and add a footer to that file. The content of that footer needs to get configured in the Administration module.
So within my project called "StampOnScanProcess" I added a Folder called "Setup" with two files. A Form called "FrmSetup"
public partial class FrmSetup : Form
{
private IBatchClass batchClass;
public FrmSetup()
{
InitializeComponent();
}
public DialogResult ShowDialog(IBatchClass batchClass)
{
this.batchClass = batchClass;
// Load previous Settings ...
return this.ShowDialog();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
// Save ...
this.Close();
}
}
and a UserControl called "UserCtrlSetup"
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISetupForm
{
[DispId(1)]
AdminApplication Application { set; }
[DispId(2)]
void ActionEvent(int EventNumber, object Argument, out int Cancel);
}
[ClassInterface(ClassInterfaceType.None)]
[ProgId(CUSTOM_MODULE_NAME_SETUP)]
public partial class UserCtrlSetup : UserControl, ISetupForm
{
private const string CUSTOM_MODULE_NAME_SETUP = "StampOnScanProcess.Setup";
private AdminApplication adminApplication;
public AdminApplication Application
{
set
{
value.AddMenu(CUSTOM_MODULE_NAME_SETUP, CUSTOM_MODULE_NAME_SETUP, "BatchClass");
adminApplication = value;
}
}
public void ActionEvent(int EventNumber, object Argument, out int Cancel)
{
Cancel = 0;
if ((KfxOcxEvent)EventNumber == KfxOcxEvent.KfxOcxEventMenuClicked && (string)Argument == CUSTOM_MODULE_NAME_SETUP)
{
FrmSetup form = new FrmSetup();
form.ShowDialog(adminApplication.ActiveBatchClass);
}
}
}
I modified my registration file and added the setup form to it
[Modules]
StampOnScanProcess
[StampOnScanProcess]
RuntimeProgram=StampOnScanProcess.exe
ModuleID=StampOnScanProcess.exe
Description=...
Version=10.2
SupportsNonImageFiles=True
SupportsTableFields=True
SetupProgram=StampOnScanProcess.Setup
[Setup Programs]
StampOnScanProcess.Setup
[StampOnScanProcess.Setup]
Visible=0
OCXFile=StampOnScanProcess.exe
ProgID=StampOnScanProcess.Setup
When launching the Administration module I head over to the Batch Class Properties => Queues and want to call this setup form by clicking the Properties button in the middle.
Unfortunately the properties button is disabled so I can't open the setup form. This form gets added to the context menu of the batch class
How can I bind this form to the properties button instead? And what is the best way to store configured data and access it when the runtime application gets executed?
I need to think about how to store data because some users have user profiles
and the runtime application currently logs in with no credentials.
public void LoginToRuntimeSession()
{
login = new Login();
login.EnableSecurityBoost = true;
login.Login();
login.ApplicationName = CUSTOM_MODULE_ID;
login.Version = "1.0";
login.ValidateUser($"{CUSTOM_MODULE_ID}.exe", false, "", "");
session = login.RuntimeSession;
}
So it might happen that I have to store the credentials on setup too.
How can I bind this form to the properties button instead?
All interactions with menu entries are handled by ISetupForm.ActionEvent. New entries are added with the AddMenu method of the AdminApplication object. Kofax differentiates between multiple entries by name - imagine that you could have multiple menu entries at the same time, one on batch class level, another one on document class level, and another one in the ribbon - just to name a few examples. Kofax uses the same approach in any component that integrates into Administration (e.g. Custom Modules or Workflow Agents).
This is an example from one of our components. Note that three entries are added on BatchClass level and two more on DocumentClass level.
value.AddMenu("BatchClass.GeneralConfig", "Field Panel - General Configuration", "BatchClass");
value.AddMenu("BatchClass.FieldEditor", "Field Panel - Configure Batch Fields", "BatchClass");
value.AddMenu("DocumentClass.FieldEditor", "Field Panel - Configure Index Fields", "DocumentClass");
value.AddMenu("CopyBatchFieldConfig", "Field Panel - Copy Batch Field Configuration", "BatchClass");
value.AddMenu("PasteBatchFieldConfig", "Field Panel - Paste Batch Field Configuration", "BatchClass");
value.AddMenu("CopyIndexFieldConfig", "Field Panel - Copy Index Field Configuration", "DocumentClass");
value.AddMenu("PasteIndexFieldConfig", "Field Panel - Paste Index Field Configuration", "DocumentClass");
Each entry is no identified by its event text, the first parameter. For example, BatchClass.GeneralConfig is intended to open up a generic configuration dialog - on batch class level.
Now, back to our ActionEvent - this is how I distinguish between the entry selected by the user:
if ((KfxOcxEvent)EventNumber == KfxOcxEvent.KfxOcxEventMenuClicked)
{
AdminForm form = new AdminForm();
switch ((string)Argument)
{
case "BatchClass.GeneralConfig":
ConfigureGeneral(kcApp.ActiveBatchClass);
break;
[I] want to call this setup form by clicking the Properties button in
the middle.
I don't know if you can use this button - I would assume yes - yet personally I tend to put settings either on batch or document class level. For example - your PDF annotation settings may different from document class to class - having an entry on this level seems more natural.
And what is the best way to store configured data and access it when
the runtime application gets executed?
Custom Storage Strings, and you can let your imagination run wild here. The most simplistic approach is to store key-value pairs during setup, and retrieve them in runtime. Here's a generic call (BatchClass is an IBatchClass object, i.e. a pointer to the ActiveBatchClass property of the AdminApplication object):
// set a CSS
BatchClass.set_CustomStorageString(name, value);
// get a CSS
BatchClass.get_CustomStorageString(name)
I usually use a single custom storage string only and store custom object - the object is a base64-encoded serialized XML using XmlSerializer - but again, that's up to you. The only recommendation is to rely on CSS only - don't use external files to store configuration parameters. A CSS is an integral part of your batch class - so, when exporting said class and importing it on a different system, your entire configuration will be there.
I need to think about how to store data because some users have user
profiles
Usually, you don't need to worry about that. The properties for user and password in ValidateUser are entirely optional - and since you're planning to write an unattended module - ideally a Windows Service, credentials should be maintained there. Kofax and Windows would automatically make sure the credentials are passed on, and your module will run under this user's context. Just make sure the user has permissions for the module and all associated batch classes. It's different if you're planning to write an attended module, for example an enhanced Validation module.

Data View Customization in Extension

I have overwritten the data view for a custom graph in an extension, which returns the correct data without issue, both by re-declaring the view, and using the delegate object techniques. The issue is that when I do, the AllowSelect/AllowDelete modifications on the view in the primary graph stop working, once I comment out the overwrite, the logic works as normal.
Not sure what I'm missing, but any thoughts would be appreciated
Edit: To clarify, on the main graph, without the extension, the data retrieval and Allow... work without issue
public class FTTicketEntry : PXGraph<FTTicketEntry, UsrFTHeader>
{
public PXSelect<UsrFTHeader> FTHeader;
public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>>> FTGridLabor;
And with the extension, the data is returned correctly from the modified view, but the Allow... do not work from the main graph, only when entered on the extension
public class FTTicketEntryExtension : PXGraphExtension<FTTicketEntry>
{
public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>, And<UsrFTGridLabor.projectID, Equal<Current<UsrFTHeader.projectID>>, And<UsrFTGridLabor.taskID, Equal<Current<UsrFTHeader.taskID>>>>>> FTGridLabor;
I have also tried the other process on the extension with the same results, the data is filtered correctly, but the Allow... commands fail.
public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>>> FTGridLabor;
public virtual IEnumerable fTGridLabor()
{
foreach (PXResult<UsrFTGridLabor> record in Base.FTGridLabor.Select())
{
UsrFTGridLabor p = (UsrFTGridLabor)record;
if (p.ProjectID == Base.FTHeader.Current.ProjectID && p.TaskID == Base.FTHeader.Current.TaskID)
{
yield return record;
}
}
}
My main concern with not wanting to use PXSelectReadOnly, is that there is a status field on the header which drives when certain combinations of the conditions are required and are called on the rowselected events, sometimes all and sometimes none, and the main issue is that I obviously don't want to have to replicate all of the UI logic into the extension, when overwriting the view was the main intent of the extension for the screen.
Appreciate the assistance, and hopefully you see something I'm overlooking or have missed
Thanks
Every BLC instance stores all actual data views and actions within 2 collections: Views and Actions. Whenever, you customize a data view or an action with a BLC extension, the original data view / action gets replaced in the appropriate collection by your custom object declared within the extension class. After the original data view or action was removed from the appropriate collection, it's quite obvious that any change made to the original object will not make any effect, since the original object is not used by the BLC anymore.
The easiest way to access actual object from either of these 2 collections would be as follows: Views["FTGridLabor"].Allow... = value;
Alternatively, you might operate with AllowInsert, AllowUpdate and AllowDelete properties on the cache level: FTGridLabor.Cache.Allow... = value;
By changing AllowXXX properties on the cache level, you completely eliminate the need for setting AllowXXX on the data view, since PXCache.AllowXXX properties have higher priority when compared to identical properties on the data view level:
public class PXView
{
...
protected bool _AllowUpdate = true;
public bool AllowUpdate
{
get
{
if (_AllowUpdate && !IsReadOnly)
{
return Cache.AllowUpdate;
}
return false;
}
set
{
_AllowUpdate = value;
}
}
...
}
With all that said, to resolve your issue with UI Logic not applying to modified view, please consider one of the following options:
Set AllowXXX property values in both the original BLC and its extensions via the object obtained from the Views collection:
Views["FTGridLabor"].Allow... = value;
operate with AllowXXX property values on the cache level: FTGridLabor.Cache.Allow... = value;
First check if your DataView should/should not be a variant of PXSelectReadonly.
Without more information my advice would be to set the Allow properties in Initialize method of your extension:
public override void Initialize()
{
// This is similar to PXSelectReadonly
DataView.AllowDelete = false;
DataView.AllowInsert = false;
DataView.AllowUpdate = false;
}

Orchard CMS front-end all possible content filtering by user permissions

Good day!
In my Orchard, I have several content types all with my custom part attached. This part defines to what users this content is available. For each logged user there is external service, which defines what content user can or cannot access. Now I need access restriction to apply everywhere where orchard display content lists, this includes results by specific tag from a tag cloud, or results listed from Taxonomy term. I seems can’t find any good way to do it except modifying TaxonomyServices code as well as TagCloud services, to join also my part and filter by it. Is this indeed the only way to do it or there are other solutions? I would like to avoid doing changes to built-in modules if possible but cannot find other way.
Thanks in advance.
I'm currently bumbling around with the same issue. One way I'm currently looking at is to hook into the content manager.
[OrchardSuppressDependency("Orchard.ContentManagement.DefaultContentManager")]
public class ModContentManager : DefaultContentManager, IContentManager
{
//private readonly Lazy<IShapeFactory> _shapeFactory;
private readonly IModAuthContext _modAuthContext;
public ModContentManager(IComponentContext context,
IRepository<ContentTypeRecord> contentTypeRepository,
IRepository<ContentItemRecord> contentItemRepository,
IRepository<ContentItemVersionRecord> contentItemVersionRepository,
IContentDefinitionManager contentDefinitionManager,
ICacheManager cacheManager,
Func<IContentManagerSession> contentManagerSession,
Lazy<IContentDisplay> contentDisplay,
Lazy<ISessionLocator> sessionLocator,
Lazy<IEnumerable<IContentHandler>> handlers,
Lazy<IEnumerable<IIdentityResolverSelector>> identityResolverSelectors,
Lazy<IEnumerable<ISqlStatementProvider>> sqlStatementProviders,
ShellSettings shellSettings,
ISignals signals,
//Lazy<IShapeFactory> shapeFactory,
IModAuthContext modAuthContext)
: base(context,
contentTypeRepository,
contentItemRepository,
contentItemVersionRepository,
contentDefinitionManager,
cacheManager,
contentManagerSession,
contentDisplay,
sessionLocator,
handlers,
identityResolverSelectors,
sqlStatementProviders,
shellSettings,
signals) {
//_shapeFactory = shapeFactory;
_modAuthContext = modAuthContext;
}
public new dynamic BuildDisplay(IContent content, string displayType = "", string groupId = "") {
// So you could do something like...
// var myPart = content.As<MyAuthoPart>();
// if(!myPart.IsUserAuthorized)...
// then display something else or display nothing (I think returning null works for this but
//don't quote me on that. Can always return a random empty shape)
// else return base.BuildDisplay(content, displayType, groupId);
// ever want to display a shape based on the name...
//dynamic shapes = _shapeFactory.Value;
}
}
}
Could also hook into the IAuthorizationServiceEventHandler, which is activated before in the main ItemController and do a check to see if you are rendering a projection or taxonomy list set a value to tell your content manager to perform checks else just let them through. Might help :)

Problems with LWUIT in J2ME on Nokia E72

Well, I'm developing a app in my cellphone that is going to connect to my PC, the problem is that everytime that I return a URLRequest to the cellphone, it shows the previous Form on the screen and not de actual one, for example this is what goes in my actionListener:
public void actionPerformed(ActionEvent ae) {
if (ae.getCommand() == guiaUtil.cSelecionar()) {
LoginRemote loginRemote = new LoginRemote();
try {
//This is the request, returns true or false, does not affect the form
loginRemote.login(tLogin.getText(), tPassword.getText());
} catch (Exception e) {
GuiaUtil.error(e);
return;
}
guiaUtil.mainApp().startMenu();
}
}
Then in the "guiaUtil.mainApp().startMenu()" I have this
public void startMenu() {
if (itemsMenu == null) {
itemsMenu = new List();
itemsMenu.setWidth(320);
itemsMenu.addItem("Sincronize Spots");
itemsMenu.addItem("Find Spots");
itemsMenu.addItem("Work");
itemsMenu.setFocus(true);
this.addComponent(itemsMenu);
this.addCommandListener(this);
this.addCommand(guiaUtil.cSelect());
Form form = new Form();
form.addComponent(itemsMenu);
}
form.show();
}
Anyway, after the request returns, it shows my Login form again, instead of showing the Menu List
Maybe what is going is that you are getting an exception, treating it with GuiaUtil.error and returning from actionPerformed without calling startMenu.
I would move guiaUtil.mainApp().startMenu() inside the try/catch block.
Not sure what happens in loginRemote.login(tLogin.getText(), tPassword.getText());
If you access the network, I would put that part in a different thread.
Inform the main thread by some kind of callback when the "remote login" is done,
you can show the menuForm from the edt then.
You have to put the following code outside the if condition.
Form form = new Form();
form.addComponent(itemsMenu);
You are having two form object. one inside if and another one outside of if. Object created inside the loop will loses the scope inside if. You are showing form object outside if. That's why, menu list screen was not displayed.

Resources