MVP on Asp.Net WebForms - asp.net

I'm not clear about this....
When having a gridview on the View, is the controller who has to set up the Data source, columns, etc? or I just have to expose the DataBinding stuff, fire it from the controller and let the html/codebehind on the view handle all the rendering and wiring up?
To be more precise: on the view should I have
private GridView _gv
public _IList<Poco> Source {
get {_gv.DataSource;}
set {_gv.DataSource = value;
_gv.DataBind();}
}
Or should it be (from MVP pattern - Passive View and exposing complex types through IView (Asp.Net, Web Forms))
private GridView _datasource;
public DataSource
{
get { return _datasource; }
set
{
_datasource = value;
_datasource.DataBind();
}
}
Maybe I'm having it all wrong ....
Where can I find an example that is not a "Hello world" example on MVP for ASP.Net???

Your controller should be in charge of setting the "result" of the databinding. The view is in charge of displaying it propertly.
So for example, your webform/usercontrol (View) could have the data source exposed as an object property that your View should know how to handle when it receives it:
public MyObject DataSource
{
set
{
_datasource = value;
_datasource.DataBind();
}
}
So if you need to have an ItemDataBound event, I would still handle it in the view. Even though there could be business logic in the event. If you need to have business logic in the event, I would put it in the MyObject result before it is passed to the view.
So an example would be to have a property of "MyObject" be "AllowDelete" and in your ItemDataBound, the value of this property determines if a column in the GridView is enabled or not.

Having just listened to a recent Hanselminutes on this topic, it might be worth having a look at the http://webformsmvp.com/ project, which seems to bring a bit of rigidity into separating concerns within WebForms.

Related

How to send stream from ViewModel to the MediaElement on the XAML page?

Just need to speak a text string from the ViewModel (inherited from MVVM Light ViewModelBase) to the MediaElement on the XAML page.
var synthesisStream = await synthesizer.SynthesizeSsmlToStreamAsync(text);
media.AutoPlay = true;
media.SetSource(synthesisStream, synthesisStream.ContentType);
media.Play();
The code above has no separation of ViewModel. We see media is directly handled in code-behind.
In my ViewModel, I stopped at
var synthesisStream = await synthesizer.SynthesizeSsmlToStreamAsync(text);
var msg=new PlaySpeechSynthesisStreamMessage(synthesisStream);
Messenger.Default.Send<PlaySpeechSynthesisStreamMessage>(msg);
For the message:
public class PlaySpeechSynthesisStreamMessage
{
public SpeechSynthesisStream Stream { get; set; }
public PlaySpeechSynthesisStreamMessage(SpeechSynthesisStream stream)
{
Stream = stream;
}
}
Is Messenger the right way to handle this situation? How can we write a RelayCommand or something to pass the stream to media?
A related article MVVM pattern violation: MediaElement.Play() seems to address this issue, but it is not in MVVM Light and there is no way to pass the stream, either.
I think a message is a good solution to handle this kind of situation.
You just have to complement the sending of the message in the ViewModel with the handling of it in the View:
Messenger.Default.Register<PlaySpeechSynthesisStreamMessage>(this, msg => {
media.AutoPlay = true;
media.SetSource(msg.Stream, msg.Stream.ContentType);
media.Play();
});
Alternatively, you can use the event approach described in the question you cited. In this case you will have to define a class that inherits from EventArgs with a property of type SpeechSynthesisStream, then define your event as follow:
public event EventHandler<YourEventArgsClass> PlaySpeechSynthesisStreamEvent;
and raise it this way:
var synthesisStream = await synthesizer.SynthesizeSsmlToStreamAsync(text);
var eventArgs = new YourEventArgsClass(synthesisStream);
if (PlaySpeechSynthesisStreamEvent != null)
PlaySpeechSynthesisStreamEvent(this, eventArgs);
In this case of course you will have to handle the event in the View.
I find the solution with the event handler a little bit trickier than the one with messages, because you will have to wire the event handling to the DataContext of the View and, depending of how the application is structured, the DataContext property of the View could not always be available from the beginning of the View lifetime: for example, in many cases I tend to set it via a Navigation Service and / or Bootstrapper during the navigation to the view: in this case, DataContext is null in the costructor of the View so it is impossible to wire the event handler there. So, you have to find another place to wire it, remembering that methods such OnNavigatedFrom (e.g., in Windows 10 UWP apps) can be called more than once in the life cycle of the view and surely we don't want to wire the event handler more than once.
If the framework exposes it (such in Windows 10 UWP), the DataContextChanged event could be a good place to wire event handlers related to the ViewModel (and possibly to remove previous ones, if an instance of a View can be used with different instance of the ViewModel class during the lifetime of the application).

ObjectDataSource+GridView=fires twice

I have a GridView bound to ObjectDataSource. I see, the SelectMethod and the SelectCountMethod are fired twice.
In the GridView RowDataBound I have gv.ShowFooter = false;
When I comment this line, the events are fires only once. Why is that happening? How to work around it? I don't understand, why hiding one element in the databound control results is rebinding the ObjectDataSource?
RowDataBound event gets fired when GridView gets data bound (that means firing of SelectMethod).
Now, toggling properties like ShowFooter requires grid to re-create rows and it means binding the data again. That's why object data source will get triggered again.
Solution will be to set ShowFooter property earlier (instead of RowDataBound). If that's not feasible then put the logic in your object data source class to the cache the data so that you don't have to visit data store twice. For example,
// Code Behind Class
public partial class MyPage : System.Web.UI.Page
{
private object _data;
public static object SelectData()
{
// get the current page instance
var page = HttpContext.Current.CurrentHandler as MyPage;
if (null != page._data)
{
return page._data;
}
// logic to retrieve the data
...
_data = ...
return _data;
}
...
private void RefreshGrid()
{
_data = null; // force the data-source to go to database again
grid.DataBind();
}
}
Disclaimer: un-tested code only for illustration purpose
So, in above code, a static method for page code-behind is used to getting the data. And a local variable in the page class is used for caching the data. Also note for refreshing the grid, you may need to clear the variable before calling DataBind method on grid.

Silverlight Custom Control and Databinding doesn't work properly in WP7

I'm trying to create my calendar control with databinding.
public partial class Calendar : UserControl
{
public static readonly DependencyProperty DateProperty =
DependencyProperty.Register("Date", typeof(DateTime),
typeof(Calendar), null);
public object Date
{
get { return GetValue(DateProperty); }
set
{
SetValue(DateProperty, value);
OnPropertyChanged("Date");
}
}
public Calendar()
{
// Required to initialize variables
InitializeComponent();
DayText.Text = ((DateTime)Date).ToString("dd");
MonthText.Text = ((DateTime)Date).ToString("MMM");
this.Loaded += new RoutedEventHandler(Calendar_Loaded);
this.GotFocus += new RoutedEventHandler(Calendar_Loaded);
}
void Calendar_Loaded(object sender, RoutedEventArgs e)
{
DayText.Text = ((DateTime)Date).ToString("dd");
MonthText.Text = ((DateTime)Date).ToString("MMM");
}
}
But When I create the listbox with this control, same calndar have the wrong date. I'm sure that the Date passed thorough databinding is correct but I don't understand why same calender show a different day (I'm noticed that is the day of a previous calendar control intance)
Thank you for supporting!
Hmm ... where do we start? Here's a few things I've noticed:
If you're using a dependency property, there's no need to call OnPropertyChanged from the Date property setter.
The dependency property declares the type as DateTime, but your public exposed property is of type object, which then requires you to cast it elsewhere.
If Calendar_Loaded is to be called in more situations than in response to the Loaded event (such as the GotFocus event, then I'd recommend that you call it something else, or create a method with a relevant name (e.g. UpdateDateParts) and call it from properly named separate event handlers.
Using fixed format specifiers when processing date strings does not localize well.
In addition to that, I'd suggest that you could implement the user interface in a manner that supports databinding (and re-templating) by using bindings and exposing the date parts of the Date dependency property instead of manually updating the Text property of some text blocks/boxes in event handlers. In fact, if you derive from Control instead of UserControl then you can create and actuall lookless control that has it's user interface defined by a style in themes\generic.xaml that can be re-defined by users of your control.
As for why the date is incorrect in different instances of your calendar control, we'd need to see some of your XAML/code to see how the control is being used and initialized to be able to provide a better answer. However, I thought the above was worth putting in an Answer, instead of trying to say it in a Comment.

Dynamically bind a DataRepeater (Microsoft.VisualBasic.PowerPacks)

I am using a DataRepeater to show data from a business objects on the screen. I am using windows forms in C# to accomplish this. The datasource is not available at compile time so I want to bind the datasource at runtime.
Here is the simplified scenario. I'm using this business class:
public class Product
{
private double _price;
public double Price
{
get
{
return _price;
}
set
{
_price = value;
}
}
}
I have created a ProductDataSource with the VisualStudio interface and bound the price to a label. Now I filled the datasource of my repeater in code:
dataRepeater1.DataSource = _productDataAgent.GetProducts();
When I startup my application the prices are correctly filled in the labels. So far so good.
Now I want the price labels to be updated when the product is updated. The Visual Studio interface helps me, and let me choose a 'Data Source Update Mode'. So I choose "OnPropertyChanged".
Here comes the tricky part. How does the .NET runtime know that the price property is updated from the backend. So I modify my business class to implement INotifyPropertyChanged. Like this:
public class Product : INotifyPropertyChanged
{
private double _price;
public double Price
{
get
{
return _price;
}
set
{
_price = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Price"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
The problem is this doesn't work. When I update a product it remeanes un-updated in the interface. When I debug and change the property, I see that the PropertyChanged event is null so no one is listening.
Delving a little deeper in to the problem I found the following on the System.Windows.Forms.Binding Constructor page on MSDN:
An event named PropertyNameChanged.
So I tried using a (custom) PriceChanged event, but that did not work.
Am I doing something wrong here? I am comming from using WPF, so maybe this works a little different in Windows Forms? Is this because I am binding at runtime?
Jep found the sollution. Apparently you cannot simply bind to a list of products. You will see the products initially, but they will not be updated when a property is changed. Instead you need to statically bind to a BindingSource. Just create an object datasource using the Visual Studio (in the data menu). Code like this is generated:
private System.Windows.Forms.BindingSource beursProductDisplayBindingSource;
this.beursProductDisplayBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.dataRepeater1.DataSource = this.beursProductDisplayBindingSource;
Now you can dynamically bind like this:
BindingSource productBinding = ((BindingSource)dataRepeater1.DataSource);
_productDataAgent.BeursProducts.ForEach(product => productBinding.Add(product));
Now when implementing INotifyPropertyChanged in your data object like I did is works like expected. Just forgot one step which is not needed when using WPF.

How can I emulate ErrorProvider in .NET Compact Framework?

Since there is no ErrorProvider class in .NETCF, how can I implement similar functionality (not necessarily exactly like ErrorProvider)?
I am using all the regular databinding constructs to bind controls to a datatable, using the DataRow.RowError property and DataRow.SetColumnError method, but I can't find events on any of DataTable, BindingManagerBase, etc. that I can hook into to receive any sort of notification.
Am I stuck calling a method to manually iterate through all the controls on my form and change some look/feel of the bound control?
Thanks,
MrB
The ErrorProvider class seems pretty basic - actually, a little too basic. If you have Red Gate Reflector, I would recommend disassembling the class and looking at it. Otherwise, create a Dictionary<Control, String>.
Here is a quick idea on creating your own provider:
Dictionary<Control, String> ErrorSet = new Dictionary<Control, String>();
public void SetError(Control control, String message)
{
// code for adding error information
ErrorSet.Add(control, message);
}
public String GetError(Control control)
{
// code for retrieving error information
return ErrorSet[control];
}
public String Clear()
{
// code for clearing all errors
}
I don't have R-G reflector here or I would provide more sample methods. But this ought to provide some sort of sample to work from.

Resources