Where do the Context fit between the GridField and the GridTab in Idempiere/Adempiere - adempiere

I m trying to grasp the purpose of the following 3 concepts ( classes ) that are core functionalities in Idempiere/Adempiere.
Based on code description
I do understand that GridTab have the state of the model representing the ad_tab which is the ViewModel Part of any ad_table. simple said we will found the data bound to the ad_table.
First, for the GridField I believe is the model of the view, if I can abuse it is like the the DOM state: what do we have as fields, values of fields and events, I believe that is template view centric.
Dicovering this two ( if I m not mistaken in my analyses ) made me wonder. What do really the Ctx stands for? what state is it representing ?
The code is not commenting on this , can any body answer me?
Thanks .

In iDempiere the context is a Properties object that is global to the whole application.
You can think about the context as a global set of variables that you can access from any point of the system.
The context variables can be viewed clicking on the iDempiere icon, then navigating to the Errors tab, and then clicking on the View button, you'll find there the variables after the line:
=== Context ===
Within the context you can find a lot of information:
Login variables: some of those starting with #, like #AD_Role_ID
Defaults: records that are marked as default, also starting with #, like #C_BP_Group_ID
Accounting related variables: those starting with $, like $C_Currency_ID
Global Preferences: starting with P like P|AutoCommit
Window Preferences: starting with P and a number, example P132|GL_Category_ID
And then, the context variables that you're interested in, the value of each field on the windows that are open:
Window fields: those starting with a number, like 1|DiscountSchema - this means the field DiscountSchema in the first window opened
Tab fields: those starting with two numbers, like 1|2|DatePromised - this means the field DatePromised in the third tab (the number 2, tabs are numbered from zero) of the first window opened (the number 1)
You can access those context variables using Env.getContext... methods, and you can also add and delete your own variables with methods Env.setContext...

The use and intent of Context in ADempiere is the same as described by Carlos except for the access. In the web you can access the context from the top right of the window as shown below.
Another example of how the context provides global state is in testing. Here is a snippet from a test setup class that initializes the context with the time and login information. The context can then be accessed by test classes performing integration tests with a database as if they were in actual use. The context here is limited to login information but it could be extended to include any other element of the context required for the tests.
#BeforeAll
public static void setUpBeforeClass() {
today = TimeUtil.getDay(System.currentTimeMillis());
ctx = Env.getCtx();
ctx.setProperty("#AD_Org_ID", Integer.toString(AD_ORG_ID));
ctx.setProperty("#AD_User_ID", Integer.toString(AD_USER_ID));
ctx.setProperty("#AD_Client_ID", Integer.toString(AD_CLIENT_ID));
ctx.setProperty("#Date", TimeUtil.getDay(System.currentTimeMillis()).toString());
ctx.setProperty("#AD_Language", "en");
Ini.setClient (IS_CLIENT);
Ini.loadProperties(false);
org.compiere.Adempiere.startup(IS_CLIENT);
trxName = Trx.createTrxName("TestRun_" + randomString(4));
trx = Trx.get(trxName, false);
try {
mainSavepoint = trx.setSavepoint("AllTests_" + randomString(4));
} catch (SQLException e) {
fail(e.getMessage());
}
}
#AfterAll
public static void tearDownAfterClass() {
try {
tryToRollback(mainSavepoint);
trx.close();
}
catch(SQLException e) {
fail("Unable to rollback. " + e.getMessage());
}
finally {
trx.close();
trx = null;
ctx = null;
}
}

Related

Unit testing a custom control in a windows store project

I want to unit test the custom controls I create for a windows store project. Just simple things like "there is a button when X is true".
However, I can't seem to even instantiate the controls in a testing context. Whenever I try to invoke the constructor, I get an exception related to not being run in the UI context. I've also been unable to create coded UI test projects that target windows store projects.
How do I programmatically instantiate a control to test? How do I create a WinRT UI synchronization context?
How do I programmatically send "user" command events to a control?
How do I programmatically instantiate/teardown the entire application?
I've found a hacky way to make non-interactive parts work: with the function Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync.
Obvious, right? However, this still leaves open the question of how to emulate user actions.
/// Runs an action on the UI thread, and blocks on the result
private static void Ui(Action action) {
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => action()
).AsTask().Wait();
}
/// Evaluates a function on the UI thread, and blocks on the result
private static T Ui<T>(Func<T> action) {
var result = default(T);
Ui(() => { result = action(); });
return result;
}
[TestMethod]
public void SliderTest() {
// constructing a Slider control is only allowed on the UI thread, so wrap it in UI
var slider = Ui(() => new Slider());
var expected = 0;
// accessing control properties is only allowed on the UI thread, so same deal
Assert.AreEqual(expected, Ui(() => slider.Value));
}

ViewModels and IsolatedStorageSettings

Im working on a MVVM Windows phone app that displays weather info.
When the app loads up it opens MainPage.xaml. It makes a call the the service to get weather info and binds that data to the UI. Both Fahrenheit and Celcius info are returned but only one is displayed.
On the setting page, the user can select to view the temp in either Fahrenheit or Celcius.
The user can change this setting at any time and its stored in IsolatedStorageSettings.
The issue Im having is this:
when the user navigates to the Settings page and changes their preference for either Fahrenheit or Celcius, this change is not reflected on the main page.
This issue started me thinking about this in a broader context. I can see this being an issue in ANY MVVM app where the display depends on some setting in IsolatedStorage. Any time any setting in the IsoStore is updated, how does the ViewModels know this? When I navigate back in the NavigationStack from the settings page back to MainPage how can I force a rebind of the page?
The data in my model hasnt changed, only the data that I want to display has changed.
Am I missing something simple here?
Thanks in advance.
Alex
Probably you have code like this:
public double DisplayTemperature
{
get { return (IsCelsium) ? Celsium : Fahrenheit; }
}
And IsCelsium is:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set { settings["IsCelsium"] = value; }
}
So you need to add NotifyPropertyChanged event to notify UI to get new values from DisplayTemperature property:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set
{
settings["IsCelsium"] = value;
NotifyPropertyChanged("DisplayTemperature");
}
}
Take a look at Caliburn Micro. You could implement something similar or use CM itself. When using CM I don't even think about this stuff, CM makes it so simple.
When your ViewModel inherits from Screen there are life-cycle events that fire that you can override. For example, OnInitialize fires the very first time the ViewModel is Activated and OnActivate fires every time the VM is activated. There's also OnViewAttached and OnViewLoaded.
These methods are the perfect place to put logic to populate or re-populate data.
CM also has some special built in features for allowing one to easily tombstone a single property or an entire object graph into Iso or phone state.
ok, so Ive come up with a solution. Before I get to it, let me provide some background. The app that Im working on uses both MVVM Light and WP7Contrib. That being the case, I am using Funq for DI and the MVVMLight Toolkit. After I posted my initial question, I gave the question a bit more thought. I remembered a video that I watched a while back from MIX2011 called Deep Dive MVVM with Laurent Bugnion
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
In it, he talks about just this problem (view models not living at the same time) on Windows Phone. The part in question starts around the 19 minute mark.
Anyway, after I remembered that and realized that the ViewModel locator is exposed in App.xaml, this became a trivial problem to solve. When the user changes the Fahrenheit/Celcius option on the setting page, I simply get a reference to the MainViewModel via the ViewModelLocator and reset the collection that is bound to the UI thus causing the bindings to update.
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (settings.Contains(Key))
{
// If the value has changed
if (settings[Key] != value)
{
// Store the new value
settings[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public bool ImperialSetting
{
get
{
return GetValueOrDefault<bool>(ImperialSettingKeyName, ImperialSettingDefault);
}
set
{
if (AddOrUpdateValue(ImperialSettingKeyName, value))
{
Save();
RaisePropertyChanged("ImperialSettingText");
var vml = new ViewModelLocator();
vml.MainViewModel.Cities = (App.Current as App).Cities;
}
}
}
It was a mistake on my part not to realize that I could get access to the viewModel via the ViewModelLocator. Hopefully this post saves someone else the time I burned on this issue.

Visual Studio 2010 plugin / code to clear "Error List" warnings before each build

VS2010 is driving me nuts: whenever I rebuild, the "Error List" warnings from the previous compilation are persisted and any new warnings are simply added to the end of the list. Over time, this list becomes ridiculously long and unwieldy.
I'm using the Chirpy 2.0 tools to run JSHint and JSLint on my JS files, and these tools generate a lot of false positives.
I've been looking for an easy way to clear the contents of this window, but the only manual mechanism that works 100% of the time is to close and re-open the solution. Not very elegant.
I'd like to write a small VS Plug-In or some code that gets called right before a compilation to clear out this list so I can focus only on new warnings for the currently loaded file(s).
I see a .Clear() method for the Output window but not for the Error List. Is this doable?
Once upon a time I was an Add-In/VSIX Package/MEF developer ...
The answer is shortly no, but I have to do it on the long way:
Add-Ins, packages (Managed or not) have access to the VS service level separatedly. Every error belongs to the reporter (If they are manage them as Chirpy do), so you can not handle the errors created by Chirpy 2.0
I take a several look to it's source code and it is persist it's erros gained by the tools in a Singleton collection called TaskList.
The deletion of the collection elements is happening in several point of code in the latest release through the RemoveAll method:
First: after the soulution is closed.
by this:
private static string[] buildCommands = new[] { "Build.BuildSelection", "Build.BuildSolution", "ClassViewContextMenus.ClassViewProject.Build" };
private void CommandEvents_BeforeExecute(string guid, int id, object customIn, object customOut, ref bool cancelDefault) {
EnvDTE.Command objCommand = default(EnvDTE.Command);
string commandName = null;
try {
objCommand = this.App.Commands.Item(guid, id);
} catch (System.ArgumentException) {
}
if (objCommand != null) {
commandName = objCommand.Name;
var settings = new Settings();
if (settings.T4RunAsBuild) {
if (buildCommands.Contains(commandName)) {
if (this.tasks != null) {
this.tasks.RemoveAll();
}
Engines.T4Engine.RunT4Template(this.App, settings.T4RunAsBuildTemplate);
}
}
}
}
As you may see, clear of results depends on many thigs.
First on a setting (which I don't know where to set on GUI or configs, but seems to get its value form a check box).
Second the array of names which are not contains every build commands name.
So I see a solution, but only on the way to modify and rebuild/redepeloy your own version from Chirpy (and make a Pull request):
The code souldn't depend on the commands, and their names. (rebuilds are missing for example)
You could change the method above something like this:
this.eventsOnBuild.OnBuildBegin += ( scope, action ) =>
{
if (action != vsBuildAction.vsBuildActionDeploy)
{
if (this.tasks != null)
{
this.tasks.RemoveAll();
}
if (settings.T4RunAsBuild && action != vsBuildAction.vsBuildActionClean)
{
Engines.T4Engine.RunT4Template(this.App, settings.T4RunAsBuildTemplate);
}
}
};
Or with something equivalent handler method instead of lambda expression.
You shold place it into the subscription OnStartupComplete method of Chirp class.
The unsubscription have to placed into OnDisconnection method in the same class. (As for all other subscribed handlers...)
Update:
When an Add-In disconneced, it isn't means the Studio will be closed immediately. The Add-In could be unloaded. So you should call the RemoveAll from OnDisconneconnection too. (Or Remove and Dispose the TaskList...)
Update2:
You can also make a custom command, and bind it to a hotkey.

Trying to change value cells in a background worker thread

I'm trying to update a Ultragridrow cell in a background worker, but this is throwing a InvalidOperation Exception when this is called more than 1 time.
Here you have the method that starts the RunWorkerAsync.
private void RefreshGridCacheStart()
{
try
{
if (this.uGridCache.Rows.Count == 0)
{
return;
}
if(!workerThread.IsBusy)
{
workerThread.DoWork += LookUpHostnames;
workerThread.ProgressChanged += UpdateCacheHostCell;
workerThread.RunWorkerCompleted += WorkerCompleted;
workerThread.WorkerReportsProgress = true;
workerThread.RunWorkerAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + "\n" + ex.Source + "\n" + ex.ToString());
}
}
This is the DoWork method:
private void LookUpHostnames(object sender, DoWorkEventArgs e)
{
var rowValues = new object[2];
try
{
foreach (UltraGridRow row in uGridCache.Rows)//here is were I get an invalid operation exception
{
string cellValue = row.Cells["Host"].Text;
if (Globals.cNet.isValidIP(cellValue))
{
rowValues[0] = row;
rowValues[1] = cellValue;
workerThread.ReportProgress(0, rowValues);
string resolvedHostname = Globals.cIPLookup.LookupHostFromIP(cellValue);
rowValues[1] = resolvedHostname;
workerThread.ReportProgress(0, rowValues);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + "\n" + ex.Source + "\n" + ex.ToString());
}
}
And this is the Report Progress method:
private void UpdateCacheHostCell(object sender, ProgressChangedEventArgs e)
{
var rowValues = e.UserState as object[];
var row = (UltraGridRow) rowValues[0];
var sMesage = (string) rowValues[1];
row.Cells["Host"].Value = sMesage;
}
You can find your answer here Different question but ultimately the same problem. Your are changing data inside a foreach loop which invalidates the enumerator.
There are 2 possible solutions I see from reading your code
Save all changes that need to be made to an List of changes and only report progress once after the foreach loop. This might not be a very good solution though since you are processing in the background. If there is other code running that could also change the data in the grid you would get the same error again.
Since you are not adding rows you could easily change the foreach to a for loop. This might also lead to an issue if code on the main thread could add, or worse, remove rows
Sounds like something must be changing the underlying row collection hence invalidating your enumerable.
If you convert your enumerable to a list using .ToList() (this will cause the enumerable to iterate and give you a new list containing the items in the original) you will be able to iterate over this new enumerable and changes in the source won't affect you.
foreach (UltraGridRow row in uGridCache.Rows.ToList())
{
....
workerThread.ReportProgress(0, rowValues);
}
You will have to be aware that if something else is changing the rows on the grid, your ReportProgress might be reporting progress of something that no longer exists in the grid, you might want to check in your ReportProgress handler whether reporting on progress for that item is still valid before doing whatever you do.
The MSDN documentation on DoWork states the following:
"You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the BackgroundWorker events.".
You can view the full details of the DoWork method here:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx
Accessing the UltraGridRows from this event is causing you to access the UltraGrid from another thread and windows forms controls aren't thread safe.
Note that this isn't limited to accessing properties of the control. If you were to set values in the data source that the UltraGrid is bound to you would have the same issue as the change notifications would then happen on the background thread and the UI would still be manipulated from the background thread.
Note that there are only a few members that are actually thread safe on windows forms controls and these are documented in the section on Thread Safety for Control on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx
Safe, Simple Multithreading in Windows Forms is a good resource for threading in windows forms even though it is older:
Part 1: http://msdn.microsoft.com/en-us/library/ms951089.aspx
Part 2: http://msdn.microsoft.com/en-us/library/ms951109.aspx
Part 3: http://msdn.microsoft.com/en-us/library/ms993020.aspx
How to: Make Thread-Safe Calls to Windows Forms Controls is also a good resource
http://msdn.microsoft.com/en-us/library/ms171728.aspx

Composite WPF: Showing/Hiding Views?

I am getting up to speed on Composite WPF, building a small demo app to work through the issues. My app has one region, and two modules, Module A and Module B. Each module contains a simple "Hello World" text block. Both modules are set up as load-on-demand, as per this MSDN How-To.
The shell has two buttons, "Load Module A" and "Load Module B". When a button is clicked, the corresponding module is loaded. So, lets say I click "Load Module A", then "Load Module B". Module A, then Module B load as expected. But if I click "Load Module A" again, nothing happens.
I'm stuck at this point. I think my problem is that I need to activate and deactivate the views in the modules, rather than using load-on-demand. But I have no idea how to do that, and I can't find any documentation or blogs that talk about it.
So, here's my question: How to I load/unload (or show/hide) views? If someone can point me to sample code, I'd really appreciate it. Thanks for your help.
I found my answer. Here is the approach: Load all the modules at startup, then activate and deactivate views as you need them. I am going to write this issue up as a CodeProject article, but here is an outline of how to do it:
(1) In the module Initialize() method, add the module, but don't activate it:
public void Initialize()
{
// Get main region
var mainRegion = m_RegionManager.Regions["MainRegion"];
// Load Module B
var newView = new ModuleBView();
mainRegion.Add(newView, "ModuleA.ModuleAView");
}
Note that the Add() method has two parameters. The second parameter is the name of the view, which we set to the value produced by the ToString() method of the view. We'll see why in the next step.
(2) When activating a view, we need to deactivate the previous view. But we may not know the name of the view, so we deactivate all active views:
public static void ClearRegion(IRegion region)
{
// Get existing view names
var oldViewNames = new List<string>();
foreach (var v in region.Views)
{
var s = v.ToString();
oldViewNames.Add(s);
}
// Remove existing views
foreach (var oldViewName in oldViewNames)
{
var oldView = region.GetView(oldViewName);
region.Deactivate(oldView);
}
}
Since we set the name of each view equal to its ToString() value, we can get the names easily without knowing anything about them in advance.
(3) Now we activate the new view. I do it in an MVVM ICommand.Execute() method:
public void Execute(object parameter)
{
// Get main region
var mainRegion = m_ViewModel.RegionManager.Regions["MainRegion"];
// Clear region
ModuleServices.ClearRegion(mainRegion);
// Activate Module A view
var moduleAView = mainRegion.GetView("ModuleA.ModuleAView");
mainRegion.Activate(moduleAView);
}
Hopefully, that will be enough to get you going. Like I said, I plan to do a more complete writeup, with demo code, for CodeProject.
David Veeneman
Foresight Systems

Resources