Caliburn Micro: querying view-specific data from the VM - caliburn.micro

I'm completely new to CM and also to learn it I'm migrating an application from MVVM light to Caliburn Micro. In my original code, I had a VM which responds to some UI actions (via commands) to replace some text into a string. The position is given by the view, using the textbox selection.
So the VM has (1) a bound string property representing the textbox's text, (2) another bound string property to represent the new text to be added, and (3) needs to know selection start and length in order to replace the right portion of text with the new one.
In my original code, I had a custom DialogMessage-derived object sent in the VM command implementation with a couple of properties for selection data: when the command was issued, the message was sent, and the view received it and filled it with its textbox selection start and length; then the VM was called back and could use these data.
Which would be the best way of implementing this in CM? I'd prefer the VM to remain agnostic of the view, so I don't like too much the idea of accessing the view from it. I'd rather opt for a "message"-based mechanism like the above, but I'm not sure how I can implement it in CM: I would probably look at IResult, but most of the samples I find are related to coroutines and I'm not sure how to relate the void ReplaceText() method of the VM to the view code behind.
Could anyone point me in the right direction, and/or to some code samples about dialog-like interactions between VM 'command' methods and view? Thanks!

I'd probably look at the IResult option. You'll have access to the view so code that you would have had in the code behind can be in your Result and not in your VM.
Here is code from a ShowDialog result. I believe I grabbed it from the CM discussion group. Search the discussion group for ShowDialog for more examples. The GameLibrary sample that comes with CM also has some.
public class ShowDialog : IResult
{
private readonly Type _screenType;
private readonly string _name;
[Import]
public IWindowManager WindowManager { get; set; }
public ShowDialog(string name)
{
_name = name;
}
public ShowDialog(Type screenType)
{
_screenType = screenType;
}
public void Execute(ActionExecutionContext context)
{
var screen = !string.IsNullOrEmpty(_name)
? IoC.Get<object>(_name)
: IoC.GetInstance(_screenType, null);
Dialog = screen;
WindowManager.ShowDialog(screen);
var deactivated = screen as IDeactivate;
if (deactivated == null)
Completed(this, new ResultCompletionEventArgs());
else
{
deactivated.Deactivated += (o, e) =>
{
if (e.WasClosed)
{
Completed(this, new ResultCompletionEventArgs());
}
};
}
}
public object Dialog { get; private set; }
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
public static ShowDialog Of<T>()
{
return new ShowDialog(typeof (T));
}
}
edit: If you extend TextBox you can bind SelectedText.
public class TextBoxEx : TextBox
{
public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.Register("SelectedText", typeof(string), typeof(TextBoxEx), new PropertyMetadata("oa"));
public TextBoxEx()
{
SelectionChanged += UpdateDependencyProperty;
}
private void UpdateDependencyProperty(object sender, RoutedEventArgs e)
{
SelectedText = base.SelectedText;
}
public new string SelectedText
{
get { return GetValue(SelectedTextProperty).ToString(); }
set { SetValue(SelectedTextProperty, base.SelectedText); }
}
}
then:
<SLTest:TextBoxEx x:Name="MyTextBox2"
Grid.Row="1"
Width="200"
SelectedText="{Binding SelectedText, Mode=TwoWay}"
Text="This is some text." />

Related

Passing the search term from SearchHandler to ContentPage in Xamarin Forms 4

I'm trying to make use of the new SearchHandler implemented as part of Xamarin Forms 4. I've found it pretty easy so far to get suggestions populated but now I want to raise an event, or follow the suggested method of handling when a search is confirmed.
public class FoodSearchHandler: SearchHandler
{
IFoodDataStore dataStore = new FoodDataStore();
protected override void OnQueryConfirmed()
{
base.OnQueryConfirmed();
// What to do here?
}
protected override void OnQueryChanged(string oldValue, string newValue)
{
base.OnQueryChanged(oldValue, newValue);
if(!string.IsNullOrWhiteSpace(newValue)
{
// Populate suggestions
ItemsSource = dataStore.GetSuggestions(newValue);
}
else
{
ItemsSource = null;
}
}
}
public partial class FoodsPage : ContentPage
{
ObservableCollection<Food> Foods = new ObservableCollection<Food>();
public ItemsPage()
{
InitializeComponent();
// Wire up the search handler
Shell.SetSearchHandler(this, new FoodSearchHandler());
BindingContext = this;
}
}
Unfortunately, althought the alpha docs mention the search handler they don't contain any details on how to use it and the sample apps only demonstrate populating the suggestions.
Does anyone out there have a pointer to offer on how I should be notifying my ContentPage that my SearchHandler confirmed a search?
So, after reading the Shell docs some more, it seems what I want to do in this situation is use of Shell's new Navigation and navigate to a route passing the search text as a query, for example:
protected override void OnQueryConfirmed()
{
base.OnQueryConfirmed();
var shell = Application.Current.MainPage as Shell;
shell.GoToAsync($"app:///fructika/search?query={Query}", true);
}
N.B. It doesn't look like passing data works right now or if it does I'm doing it wrong but I'll raise a separate question about that.

C# ASP.NET - Controlling/updating a textbox.text value through a class

Newbie here, I need help with a website I'm creating.
I have a class that does some analysis on some text that is input by the user, the class then finds an appropriate answer and sends it back to the textbox. (in theory)
Problem is I don't know how I can control and access the textbox on the default.aspx page from a class, all I get is "object reference is required non static field".
I made the textbox public in the designer file yet still no joy. :(
I've also read this: How can I access the controls on my ASP.NET page from a class within the solution? , which I think is along the lines of what I'm trying to achieve but I need clarification/step by step on how to achieve this.
Hope someone can point me in the right direction.
Many thanks,
Kal
This is the code I have added to the designer.cs file:
public global::System.Web.UI.WebControls.TextBox TextBox3;
public string MyTextBoxText
{
get
{
return TextBox3.Text;
}
set
{
TextBox3.Text = value;
}
}
This is the class method i have created:
public static cleanseMe(string input)
{
string utterance = input;
string cleansedUtt = Regex.Replace(utterance, #"[!]|[.]|[?]|[,]|[']", "");
WebApplication1._Default.TextBox3.text = cleansedUtt;
}
I could just return the cleansedUtt string i know, but is it possible for me to just append this string to the said textbox from this method, within this class?
I also tried it this way, i wrote a class that takes in the name of the textbox and string to append to that textbox. it works BUT only on the default.aspx page and does not recognise the textbox names within the difference classes. The code is as follows:
public class formControl
{
public static void ModifyText(TextBox textBox, string appendthis)
{
textBox.Text += appendthis + "\r\n";
}
I would suggest you that do not access the Page Controls like TextBox in your class. It will be more useful and a good practice that whatever functionality your class does, convert them into function which accept the parameters and returns some value and then on the basis of that value you can set the controls value.
So now you have reusable function that you can use from any of the page you want. You do not need to write it for every textbox.
Here I am giving you a simple example
public class Test
{
public bool IsValid(string value)
{
// Your logic
return true;
}
}
Now you can use it simple on your page like this
Test objTest = new Test();
bool result=objTest.IsValid(TextBox1.Text);
if(result)
{
TextBox1.Text="Everything is correct";
}
else
{
TextBox1.Text="Something went wrong";
}
If you have your class in the same project (Web Project) the following will work:
public class Test
{
public Test()
{
//
// TODO: Add constructor logic here
//
}
public static void ValidateTextBox(System.Web.UI.WebControls.TextBox txt)
{
//validation logic here
if (txt != null)
txt.Text = "Modified from class";
}
}
You can use this from your webform like this:
protected void Page_Load(object sender, EventArgs e)
{
Test.ValidateTextBox(this.txt);
}
If your class is in a different (class project), you would need to add a reference to System.Web to your project.

Whats the point of the ObjectDataSource

Given that every grid, combobox, checkboxlist and in general multi row control supports binding directly to any IEnumerable what is the point of the ObjectDataSource?
Why would one use it as opposed to binding directly to your collection? Particularly if you already have reasonable separation of concerns in your business, presentation and data layers?
I also feel this is an even more relevant question since the introduction of LINQ. I have often found that when binding I would like to perform some further ordering, exclusion and so forth using LINQ and I believe this is not possible when using the ObjectDataSource without creating a specific method for your (potentially single use case)?
So when is it appropriate to use an ObjectDataSource and what are the advantages compared to direct binding to IEnumerable?
First, ObjectDataSource is usually used in ASP.NET WebForms (aspx). ObjectDataSource is located in System.Web.UI.WebControls, as you can see this link on MSDN Library:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx
Using ObjectDataSource to bind your data means you bind you'll have datasource as an object, can be in form of DataSet or any other .NET object that implements IEnumerable. Using ObjectDataSource means you have to perform your own Select, Update, Insert and Delete method that usually found in SqlDataSource.
There's this nice walkthrough in MSDN Library: Walkthrough: Data Binding to a Custom Business Object
But binding to a simple IEnumerable without implementing IListSource (like DataTable has) means you won't have nice feature such as data bindings to a complex data control such as GridView. And you'll lose other feature too, because a simple IEnumerable alone can't be bound in two ways to other list control such as ListView and GridView.
To have your data to be bindable two way, your object must also implement INotifyPropertyChanged interface before added into the IListSource as data item.
Samples:
public class Employee : BusinessObjectBase
{
private string _id;
private string _name;
private Decimal parkingId;
public Employee() : this(string.Empty, 0) {}
public Employee(string name) : this(name, 0) {}
public Employee(string name, Decimal parkingId) : base()
{
this._id = System.Guid.NewGuid().ToString();
// Set values
this.Name = name;
this.ParkingID = parkingId;
}
public string ID
{
get { return _id; }
}
const string NAME = "Name";
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
// Raise the PropertyChanged event.
OnPropertyChanged(NAME);
}
}
}
const string PARKING_ID = "Salary";
public Decimal ParkingID
{
get { return parkingId; }
set
{
if (parkingId != value)
{
parkingId = value;
// Raise the PropertyChanged event.
OnPropertyChanged(PARKING_ID);
}
}
}
}
This is the implementation of INotifyPropertyChanged:
public class BusinessObjectBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
}
You can bind to an enum with it if you dont want codebehind.

Multi-Threading/User Feedback in MVVM

I am new to MVVM and have written a small app to test the waters and get familiar with the pattern. The main function of my app takes too long to not have some sort of user feedback that the process is continuing along. What would be the recommended way to place the call in a separate thread and provide feedback for a progress bar? The ViewModel code for the function is below. Thanks for the help.
public DataView Data
{
get
{
return resultsView;
}
set
{
if (value == resultsView)
{
return;
}
resultsView = value;
RaisePropertyChanged("Data");
}
}
private void SetData()
{
Data = RetrieveData.GetPartData(SelectedTeam, SelectedYear).DefaultView;
}
public RelayCommand GetData
{
get;
private set;
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
// Initializers for other part of ViewModel
// Teams = RetrieveData.GetTeams();
// Years = RetrieveData.GetYears();
GetData = new RelayCommand(SetData);
}
I'm not completely versed on MVVM multi-threading yet, but this link seems quite do-able : WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI.
NOW, what I would try is something like this:
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
Data = RetrieveData.GetPartData(SelectedTeam, SelectedYear).DefaultView;
};

Auto wiring of Property does not work for me

In my Asp.Net project I wanna use Property Auto-wiring, e.g. for my ILogger. Basically I placed it as Property into class where I need to use it. Like below.
public class UserControlBase : UserControl
{
public ILogger CLogger { get; set; }
....
}
public partial class IPTracking : UserControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
//it works
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.LogInfo(string.Format("Client IP: {0}", ip));
//it does not work
CLogger.LogInfo(string.Format("Client IP: {0}", ip));
}
}
}
However when calling in inherited control, logger is null. I checked the container and it'a definitely set as above implementation shows. Below is setting which is called from Global.asax.
public static void SetupForIoC()
{
Debug.WriteLine("SetupForIoC");
ObjectFactory.Initialize(x =>
{
x.FillAllPropertiesOfType<ILogger>().Use<EntLibLogger>();
});
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
Thanks for any advice, tip? X.
Update:
- I didnt mentioned before, but its Asp.Net webforms 3.5.
- I can't see what I am missing. I guess it could be because the injection gets involved later in process and didnt get set in requested class.
Link to desc. of usage: http://structuremap.github.com/structuremap/ConstructorAndSetterInjection.htm#section7
Give something like this a shot.
FillAllPropertiesOfType<ILogger>().AlwaysUnique().Use(s => s.ParentType == null ? new Log4NetLogger(s.BuildStack.Current.ConcreteType) : new Log4NetLogger((s.ParentType)));
Check out another StackOverflow answer I have which discusses using StructureMap to auto wire loggers.
Where do you actually set the CLogger property on the user control? Also, if you wanted to use one logger within the page, you could have the User cotnrol do:
public ILogger CLogger
{
get
{
if (this.Page is PageBase)
return ((PageBase)this.Page).Logger;
else
return null;
}
}

Resources