webMethods: Show/hide caf_h:panelBlock based on property value of backing bean - webmethods

We have got two caf_h:panelBlock elements (id="panel1" and id="panel2") in a CAF portlet which are supposed to be rendered based on a property of the backing bean (rendered="#{ViewBean.property}" and rendered="#{not ViewBean.property}").
So the XHTML of such a panel locks as follows:
<caf_h:panelBlock id="panel1" rendered="#{ViewBean.property}">
content
</caf_h:panelBlock>
The property of the backing bean is declared as follows:
private java.lang.Boolean property;
And initialized in the bean's Initialize() method:
public String initialize() {
this.property = true;
}
The tricky part comes now: We want to show/hide these panels by clicking on a command link:
<caf_h:commandLink action="#{ViewBean.click}" id="commandLink"></caf_h:commandLink>
The bean method called by this command link, in turn, changes the property's value:
public String click() {
this.property = false;
}
However, the visibility/rendering of the block panels is not affected at all. What might be the reason?

It turned out that the above mentioned way works fine if the ViewBean.property is not changed again later during the portlet life cycle - as we accidentally did in our case in the beforeRenderResponse() method.

Related

Flex 4.6 and AS3 Calling method from another mxml file

I have two files,
FloorplansMaster and Floorplans.
In my FloorplansMaster I have this method inside my script tags:
public function changeView(): void
{
var floorplans:Floorplans = new Floorplans();
floorplans.changeView();
}
and I am trying to call the method changeView in the Floorplans file, which looks like this:
public function changeView():void
{
trace("Here");
}
But I keep getting this error:
Cannot access a property or method of a null object reference.
What am I doing wrong?
In Flex developers often try to access view elements before they're created.
Try calling the method in a creationComplete handler instead.

MvvmCross, Mvx.MvxListView and custom binding in MvxItemTemplate

In a MvvmCross app, I have a page with the classic chat behavior (WhatsApp like): this page shows the history of messages exchanged between two users with the last message at the bottom of the list.
I've successfully implemented the view in Windows Phone 8.1, but I'm struggling with a problem in Android.
I'll give you a short introduction and description of my problem and next I'll go through technical details.
INTRODUCTION
Actually, my need is to apply different style to messages sent by different users: tipically align left messages sent from other user and align right messages sent by me (I do this through the weight property); I need to apply a different drawable background and set different gravity property also.
I use custom binding because, AFAIK, those properties cannot be binded with classic binding: local:MvxBind="Gravity MyPropery" doesn't work because there is no Gravity property.
So, I have of course two axml files:
the first one contains the Mvx.MvxListView
the second one contains the item template for MvxListView
And I've created three different custombinding (for Background, Gravity and Weight) following these guides:
http://slodge.blogspot.it/2013/06/n28-custom-bindings-n1-days-of-mvvmcross.html
In MvvmCross how do I do custom bind properties
THE PROBLEM
I want that, when a user opens the chat View, the list widget shows automatically the last message. To accomplish this, I scroll programmatically the list to the last message and this seems to be the problem.
If I don't scroll programmatically, when I open the page and scroll manually to the end of the page, all custom bindings are applied successfully: I can see messages aligned right and left, with correct background and weight applied.
If I force the scroll programmatically, when I open the page I see a strange behavior: all the messages are present (classic binding, such as Text property, have been successfully applied), but custom bindings are missing. All the messages have the same background and are all left aligned.
BUT, if I scroll manually up and down, the custom binding are processed and the messages are displayed with right style.
DEBUG ANALYSIS
To debug the behaviour I've put a simple static counter in a custom binding procedure to track every time the function is processed.
public class LinearLayoutWeightTargetBinding : MvxAndroidTargetBinding
{
public static int debugCounter = 0;
public LinearLayoutWeightTargetBinding(object target) : base(target)
{
}
protected LinearLayout MyTarget
{
get { return (LinearLayout)Target; }
}
public override Type TargetType { get { return typeof(bool); } }
protected override void SetValueImpl(object target, object value)
{
var ll = (LinearLayout)target;
var itsMe = (bool)value;
var weight = itsMe ? (float)20.0 : (float)5.0;
var layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WrapContent, weight);
ll.LayoutParameters = layoutParams;
Log.Debug("MeeCHAT", string.Format("LinearLayoutWeightTargetBinding::SetValueImpl::ItsMe:{0} - counter:{1}", itsMe, ++debugCounter));
}
public override MvxBindingMode DefaultMode { get {return MvxBindingMode.TwoWay;} }
}
By this way I saw that actually by scrolling up and down the custom bindings are applied (debugCounter increases correctly).
BUT when I apply the programmatically scroll, only the first 10 items are processed by the custom bindings and this seems the reason why I see the messages without the right style. Because I have a long list, only the first 10 items are processed but they are not visible (they are out of the visible area) and the visibile items have not been processed.
TECHNICAL DETAILS
Here are some details related to technical aspects of my app. I try to give you all important aspects.
ORGANIZATION OF THE VIEWS
By following the approach described by Greg Shackles in this article http://gregshackles.com/presenters-in-mvvmcross-navigating-android-with-fragments/ I have just one general Activity for the app and one Fragment for each View; then through a Presenter is possible to activate the right ViewModel and manage the stack of the navigation.
The Fragment for the View where I have the Mvx.MvxListView widget is
public class MyMatchersChatView : MvxFragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignore = base.OnCreateView(inflater, container, savedInstanceState);
var result = this.BindingInflate(Resource.Layout.MyMatchersChatView, null);
var headerFrame = result.FindViewById<FrameLayout>(Resource.Id.headerFrameMyMatchersChatView);
var headerWidget = new HeaderWidget() { ViewModel = this.ViewModel };
var tran = ChildFragmentManager.BeginTransaction();
tran.Add(headerFrame.Id, headerWidget, "headerMyMatchersChat");
tran.Commit();
var listView = result.FindViewById<MvxListView>(Resource.Id.messagesList);
listView.SetSelection(listView.Adapter.Count - 1); // Scroll to the end of the list
return result;
}
}
The statement listView.SetSelection(listView.Adapter.Count - 1); force the list to scroll to the end.
Last two things: how the custom bindings are registered and how are applied in axml file.
REGISTRATION OF CUSTOM BINDING
In Setup.cs I have:
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
base.FillTargetFactories(registry);
registry.RegisterFactory(new MvxCustomBindingFactory<LinearLayout>("CustomWeight",
(b) => new LinearLayoutWeightTargetBinding(b)));
}
APPLYING OF CUSTOM BINDING
In my axml I have:
<LinearLayout
android:orientation="horizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
local:MvxBind="CustomWeight IsCurrentUser">
LISTVIEW AND VIEWMODEL
Here is the code of ListView
<Mvx.MvxListView
android:id="#+id/messagesList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
local:MvxBind="ItemsSource MyMessages"
local:MvxItemTemplate="#layout/mymatcherschatview_itemtemplate" />
and the property in ViewModel
private IEnumerable<MyMatchMessageModel> _myMessages;
public IEnumerable<MyMatchMessageModel> MyMessages
{
get { return _myMessages; }
set
{
_myMessages = value;
RaisePropertyChanged(() => MyMessages);
}
}
ENVIRONMENT
Finally, here is my environment:
Visual Studio 2015
MvvmCross 3.5.1
Core targets: .NET Framework 4.5, Windows 8, ASP.NET Core 5.0, Windows Phone 8.1, Xamarin.Android, Xamarin.iOS, Xamarin.iOS (Classic)
The Android app target is API Level 19 (Xamarin.Android v4.4 Support)
Xamarin 3.11.1450.0
Xamarin.Android 5.1.6.7
Someone can help me to understand if I'm doing something wrong?
Thanks for reading and for any help!
>>EDIT 1<<
I've changed my layout by adding stackFromBottom and transcriptMode properties and by removing the scrolling to below programmatically in Fragment obtaining an auto-scroll behavior, but the problem still remains: to see messages with correct style I have to manually scroll up and down (to activate the custom bindings)
Here is the new axml...
<Mvx.MvxListView
android:id="#+id/messagesList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
local:MvxBind="ItemsSource MyMessages"
local:MvxItemTemplate="#layout/mymatcherschatview_itemtemplate" />
...and the new code in Fragment
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignore = base.OnCreateView(inflater, container, savedInstanceState);
var result = this.BindingInflate(Resource.Layout.MyMatchersChatView, null);
var headerFrame = result.FindViewById<FrameLayout>(Resource.Id.headerFrameMyMatchersChatView);
var headerWidget = new HeaderWidget() { ViewModel = this.ViewModel };
var tran = ChildFragmentManager.BeginTransaction();
tran.Add(headerFrame.Id, headerWidget, "headerMyMatchersChat");
tran.Commit();
return result;
}
First thing I would do is to make sure that your custom binding is always getting called.
Set a breakpoint on the SetValueImpl() method and check it´s getting called on those problematic items. If that happens, then the issue relies on the view no getting updated for any reason and you should work on that. If it doesn´t break, you will know for sure it´s a custom binding problem (possibly a bug) in MvxAdapter.
If you find out it´s the second one. I would suggest getting rid of your custom binding and creating your own ChatListAdapter : MvxAdapter as follows:
public class CoolChatListAdapter : MvxAdapter
{
public CoolChatListAdapter(Context context, IMvxAndroidBindingContext bindingContext) : base(context, bindingContext)
{
}
protected override View GetBindableView(View convertView, object source, int templateId)
{
var item = source as MyMatchMessageModel;
var weight = item.IsCurrentUser ? (float) 20.0 : (float) 5.0;
var ll = (LinearLayout) convertView;
var layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WrapContent, weight);
ll.LayoutParameters = layoutParams;
return base.GetBindableView(convertView, source, templateId);
}
}
Then, in your android view:
var adapter = new ChatListAdapter(this, (IMvxAndroidBindingContext)BindingContext);
_chatList = FindViewById<MvxListView>(Resource.Id.chat_list_view);
_chatList.Adapter = adapter;

ActionScript: making a variable `[Bindable]` causes crashes

I have this singleton that I'm using as a wrapper for global variables and constants, but as soon as I make some [Bindable] I get a crash on start up w/a bunch of red text in my console.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at BrandGlobals$/get COLOUR_EVERYTHING_BACKGROUND()[C:\MyProject\src\BrandGlobals.as:14]
at BrandGlobals$cinit()
at global$init()[C:\MyProject\src\BrandGlobals.as:2]
at _mainWatcherSetupUtil/setup()
at main/initialize()[C:\MyProject\src\main.mxml:0]
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::childAdded()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:2131]
at mx.managers::SystemManager/initializeTopLevelWindow()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:3400]
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:3223]
at mx.managers::SystemManager/docFrameListener()[C:\autobuild\3.5.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:3069]
BrandGlobals:
package {
public final class BrandGlobals {
[Bindable]public static var COLOUR_EVERYTHING_BACKGROUND:uint = 0xE010FF;
If I remove that [Bindable] and turn var to const there's no problem (except the obvious problem of not being able to set the variable outside of this file) but this doesn't work. Also, making the whole class [Bindable] instead of this one didn't work. When I hover my mouse over the COLOUR_EVERYTHING_BACKGROUND definition, it says "<exception thrown by getter>". 'Don't know what to think about that.
I might have guessed it was because it has no package, but I'm using another similar singleton which has [Bindable] variables and seems to work fine.
I never did get that [Bindable] twaddle.
I'm using the Flex 3.5 SDK.
I tried Brian's suggestion below, but it gave me pretty much the same error. I even tried:
{
_COLOUR_EVERYTHING_BACKGROUND = 0xE010FF;
trace("Var set."); //Breakpoint here
bLoadedFerCryinOutLoud = true;
}
[Bindable]private static var _COLOUR_EVERYTHING_BACKGROUND:uint;
private static var bLoadedFerCryinOutLoud:Boolean = false;
public static function get COLOUR_EVERYTHING_BACKGROUND():uint {
trace("Returning EVERYTHING background");
if (bLoadedFerCryinOutLoud)
return _COLOUR_EVERYTHING_BACKGROUND;
else return 0xFFFFFF;
}
What's more, if I put a breakpoint at that trace("Var set.");, Flash Builder complains that a break is not possible, because there is no executable code there.
I also noticed that in that call stack that I'm shown when this crash happens during a set and it seems to be the one that sets _COLOUR_EVERYTHING_BACKGROUND. But the only place where it is set is:
public static function SetBackground(oApp:UBIApplication):void {
_COLOUR_EVERYTHING_BACKGROUND = oApp.nBackgroundColour;
}
and breakpoints indicate that this is never called.
The documentation on using the tag has the following to say:
Using static properties as the source for data binding
You can use a static variable as the source for a data-binding expression. Flex performs the data binding once when the application starts, and again when the property changes.
You can automatically use a static constant as the source for a data-binding expression. Flex performs the data binding once when the application starts. Because the data binding occurs only once at application start up, you omit the [Bindable] metadata tag for the static constant. The following example uses a static constant as the source for a data-binding expression:
<fx:Script>
<![CDATA[
// This syntax casues a compiler error.
// [Bindable]
// public static var varString:String="A static var.";
public static const constString:String="A static const.";
]]>
</fx:Script>
<!-- This binding occurs once at application startup. -->
<s:Button label="{constString}"/>
Edit: You need to make sure that your variable is initialized before you try to read it. A static initializer is the way to go:
package {
public final class BrandGlobals {
{
_COLOUR_EVERYTHING_BACKGROUND = 0xE010FF;
trace("Var set."); //Breakpoint here
}
[Bindable]private static var _COLOUR_EVERYTHING_BACKGROUND:uint;
public static function get COLOUR_EVERYTHING_BACKGROUND():uint {
trace("Returning EVERYTHING background"); //Breakpoint here
return _COLOUR_EVERYTHING_BACKGROUND;
}
Putting in breakpoints in the places specified will let you verify that things are executing in the expected order
It turns out that the problem was assigning COLOUR_EVERYTHING_BACKGROUND to a static const elsewhere in the code, as a temporary measure. Hopefully I'll remember that assigning [Bindable]s to static consts is bad and if I don't, I'll remember the meaning of that particular cryptic reaction Flash Builder had. I'm starting to choke StackOverflow w/my questions about cryptic error messages.

How to do CreateBindingSet() on Windows Phone?

In the N+1 video #34 (Progress), there was an example of using CreateBindingSet() for the Android version, which is not typical. But the narrator also mentioned briefly that the same can be done on the Windows platform.
As much as I tried, however, I am unable to get a View's property to be bound to its ModelView on the Windows Phone. I always get a NullReferenceException.
The closest I came was the code below, including suggestions from ReSharper. Here's my FirstView.xaml.cs:
using Cirrious.MvvmCross.Binding.BindingContext;
using Whatever.ViewModels;
namespace Whatever {
// inheriting from IMvxBindingContextOwner was suggested by ReSharper also
public partial class FirstView : BaseView, IMvxBindingContextOwner {
public class MyBindableMediaElement
{
private string _theMediaSource = "whatever";
public string TheMediaSource
{
get
{
return _theMediaSource;
}
set
{
_theMediaSource = value;
}
}
}
public FirstView()
{
InitializeComponent();
_mediaElement = new MyBindableMediaElement(this.theMediaElement);
var set = this.CreateBindingSet<FirstView, FirstViewModel>();
// the corresponding view model has a .SongToPlay property with get/set defined
set.Bind(_mediaElement).For(v => v.TheMediaSource).To(vm => vm.SongToPlay);
set.Apply();
}
public IMvxBindingContext BindingContext { get; set; } // this was suggested by ReSharper
}
I get a NullReferenceException in MvxBaseFluentBindingDescription.cs as soon as the view is created. The exact location is below:
protected static string TargetPropertyName(Expression<Func<TTarget, object>> targetPropertyPath)
{
var parser = MvxBindingSingletonCache.Instance.PropertyExpressionParser; // <----- exception here**
var targetPropertyName = parser.Parse(targetPropertyPath).Print();
return targetPropertyName;
}
I have not seen a working example of creating a binding set on a Windows Phone emulator. Has anyone gotten this to work? Thanks.
I can confirm that the narrator said that remark a little too flippantly without actually thinking about how he might do it...
However, with a little effort, you definitely can get the CreateBindingSet to work in Windows if you want to.
Before you start, do consider some alternatives - in particular, I suspect most people will use either Windows DependencyProperty binding or some hand-crafted code-behind with a PropertyChanged event subscription.
If you do want to add CreateBindingSet code to a Windows project then:
Add the Binding and BindingEx assemblies to your Ui project - the easiest way to do this is using nuget to add the BindingEx package.
In your Setup class, override InitializeLastChance and use this opportunity to create a MvxWindowsBindingBuilder instance and to call DoRegistration on that builder. Both these first two steps are covered in the n=35 Tibet binding video - and it's this second step that will initialise the binding framework and help you get past your current 'NullReferenceException' (for the code, see BindMe.Store/Setup.cs)
In your view, you'll need to implement the IMvxBindingContextOwner interface and you'll need to ensure the binding context gets created. You should be able to do this as simply as BindingContext = new MvxBindingContext();
In your view, you'll need to make sure the binding context is given the same DataContext (view model) as the windows DataContext. For a Phone Page, the easiest way to do this is probably just to add BindingContext.DataContext = this.ViewModel; to the end of your phone page's OnNavigatedTo method. Both steps 3 and 4 could go in your BaseView if you intend to use Mvx Binding in other classes too.
With this done, you should be able to use the CreateBindingSet code - although do make sure that all binding is done after the new MvxBindingContext() has been created.
I've not got a windows machine with me right now so I'm afraid this answer code comes untested - please do post again if it does or doesn't work.
I can confirm it works almost perfectly; the only problem is, there are no defaults register, so one has to do the full binding like:
set.Bind(PageText).For(c => c.Text).To(vm => vm.Contents.PageText).OneTime();
to fix this, instead of registering MvxWindowsBindingBuilder, I am registering the following class. Note: I have just created this class, and needs testing.
public class UpdatedMvxWindowsBindingBuilder : MvxWindowsBindingBuilder
{
protected override void FillDefaultBindingNames(IMvxBindingNameRegistry registry)
{
base.FillDefaultBindingNames(registry);
registry.AddOrOverwrite(typeof(Button), "Command");
registry.AddOrOverwrite(typeof(HyperlinkButton), "Command");
//registry.AddOrOverwrite(typeof(UIBarButtonItem), "Clicked");
//registry.AddOrOverwrite(typeof(UISearchBar), "Text");
//registry.AddOrOverwrite(typeof(UITextField), "Text");
registry.AddOrOverwrite(typeof(TextBlock), "Text");
//registry.AddOrOverwrite(typeof(UILabel), "Text");
//registry.AddOrOverwrite(typeof(MvxCollectionViewSource), "ItemsSource");
//registry.AddOrOverwrite(typeof(MvxTableViewSource), "ItemsSource");
//registry.AddOrOverwrite(typeof(MvxImageView), "ImageUrl");
//registry.AddOrOverwrite(typeof(UIImageView), "Image");
//registry.AddOrOverwrite(typeof(UIDatePicker), "Date");
//registry.AddOrOverwrite(typeof(UISlider), "Value");
//registry.AddOrOverwrite(typeof(UISwitch), "On");
//registry.AddOrOverwrite(typeof(UIProgressView), "Progress");
//registry.AddOrOverwrite(typeof(IMvxImageHelper<UIImage>), "ImageUrl");
//registry.AddOrOverwrite(typeof(MvxImageViewLoader), "ImageUrl");
//if (_fillBindingNamesAction != null)
// _fillBindingNamesAction(registry);
}
}
This is a skeleton from Touch binding, and so far I have only updated three controls to test out (Button, HyperButton and TextBlock)

Setter isn't always triggered

I use a bindable variable that represents a Model and pass it down thru several nested components.
Top level component is my variable:
[Bindable]
private var meetingInfo:MeetingInfoModel;
I initialize it in the handler for the "preinitialize" event:
meetingInfo = MeetingInfoModel.getInstance();
I then pass it thru to 1 component:
<meetingViewStack:MeetingViewStack meetingInfo="{meetingInfo}"/>
In that component I have the following:
private var _meetingInfo:MeetingInfoModel;
public function set meetingInfo( model:MeetingInfoModel ):void{
_meetingInfo = model;}
[Bindable]
public function get meetingInfo():MeetingInfoModel{
return _meetingInfo;
}
I then pass that variable to another nested component:
<documentShare:DocumentPanel meetingInfo="{meetingInfo}"/>
Where I have the same setter/getter set up. Then I pass it again to another nested component:
<documentShare:AttachmentFilesPanel meetingInfo="{meetingInfo}" />
In that component I have an ItemRenderer for a DataGroup component where it binds to "meetingInfo":
<s:DataGroup id="attachmentsList"
width="100%"
clipAndEnableScrolling="true"
dataProvider="{meetingInfo.docsAndAttachmentsList}"
itemRenderer="com.fmr.transporter.view.documentShare.DocumentUploadRenderer"
visible="{meetingInfo.docsAndAttachmentsList.length > 0}">`enter code here`
As I update the "meetingInfo.docsAndAttachmentsList" ArrayCollection, the setters in each nested component get called correctly, until....
...and this is an AIR app, mind you...
I log out and back in. Then, the setter/getter in the last nested component is not fired this time.
Why, oh why, would this happen?
I've been troubleshooting for a couple days and cannot figure it out for the life of me.
Thanks for any helpful tips!!
The code MeetingInfoModel.getInstance(); hints that MeetingInfoModel is a singleton, is it? If so, setter will be triggered only once, because of the mxmlc generates the check that objects instance changed, the generated code for SDk 4.5.1 will be like this:
[Bindable(event="propertyChange")]
public function set meetingInfo(value:MeetingInfoModel):void
{
var oldValue:Object = this.meetingInfo;
if (oldValue !== value)
{
this._883716727meetingInfo = value;
if (this.hasEventListener("propertyChange"))
this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "meetingInfo", oldValue, value));
}
}
so if you didn't recreate instance of MeetingInfoModel the setter will not be triggered.