ASP MVC to Silverlight MVVM issues - silverlight

I am converting an asp.net MVC application to silverlight, and due to the fact I was doing some 'non-standard' things in my mvc app, I am having a hard time trying to work out how to implement it in Silverlight MVVM.
Basically I was generating all my views from metadata, including links, buttons etc. One example of this that I can't get my head around how to do in Silverlight is that I passed in an action collection to my view, and had a html helper class that then converted these actions into links
public static string GenericLinks(this HtmlHelper htmlHelper, int location, bool inTable, int? parentRecordId, List<ModelAction>
actions)
{
int actionNo = 1;
StringBuilder text = new StringBuilder();
foreach (var action in actions)
{
if (action.LocationType == location)
{
if (inTable)
text.Append("<td>");
else
if (actionNo > 1)
text.Append(" | ");
text.Append(htmlHelper.ActionLink(action.Label, action.ActionTypeLookup.CodeName, new { actionId = action.ModelActionId,
parentRecordId = parentRecordId }));
if (inTable)
text.Append("</td>");
actionNo++;
}
}
return text.ToString();
}
This really worked well in MVC.
What would the equivent be in MVVM?
I would expect I could do something much more eligent, more along the lines of creating my actions in my viewmodel, and somehow binding to those actions in my view...

For something like that you would probably need to create a custom control. Then you could put it in your view and bind it to the collection of Actions which would exist in your ViewModel.

Related

Xamarin.Forms Caliburn.Micro - Associate multiple Views with a single ViewModel

I am looking for some guidance on how to Associate multiple Views with a single ViewModel. We are developing an app using Xamarin.Forms Portable (VS.NET 2017) and Caliburn.Micro as an MVVM framework.
The View would appear as /Views/DemoView.Xaml
The ViewModel would appear as /ViewModels/DemoViewModel.cs
In App.cs, DemoView is invoked via the below line and everything works fine:
DisplayRootView<(DemoView)>();
Now, the issue is that we need to load different Views for Mobile and Tablet. I created a new folder structure under /Views as follows:
- /Views/Demo/Mobile.xaml
- /Views/Demo/Tablet.xaml
The question is how to load the relevant View based on a condition (Device.Idiom), knowing that there needs to be a way to associate the above 2 views with DemoViewModel.
Does this mean I would still require a /Views/DemoView.Xaml (knowing that is it already associated to /ViewModels/DemoViewModel.cs) that would behave as an intermediary and load the correct View based on the the condition mentioned?
I should flag that the Views we seek to load are Tabbed Pages that will load other pages in it in the DemoViewModel (which implements Conductor.Collection.OneActive) by adding other ViewModels to the Items collection.
Thanks,
P.
You will have to setup some custom conventions.
If you always need to load different views for phone and tablet, then you can configure the area where Caliburn searches for the View or ViewModels by configuring the Type Mappings.
App.xaml.cs
protected override void Configure()
{
TypeMappingConfiguration config = null;
if( Device.Idiom == TargetIdiom.Tablet)
{
config = new TypeMappingConfiguration
{
DefaultSubNamespaceForViews = "Tablet.Views",
DefaultSubNamespaceForViewModels = "Common.ViewModels"
};
}
else
{
config = new TypeMappingConfiguration
{
DefaultSubNamespaceForViews = "Mobile.Views",
DefaultSubNamespaceForViewModels = "Common.ViewModels"
};
}
if(config != null)
{
ViewLocator.ConfigureTypeMappings(config);
}
}
If you share most Views across idioms, then you can specify Views for specific View Models
protected override void Configure()
{
if( Device.Idiom == TargetIdiom.Tablet)
{
ViewLocator.AddNamespaceMapping("Common.ViewModels.Demo", "Tablet.Views");
}
else
{
ViewLocator.AddNamespaceMapping("Common.ViewModels.Demo", "Mobile.Views");
}
}
This will map
Tablet: Common.ViewModels.DemoViewModel to Tablet.Views.DemoView
Mobile: Common.ViewModels.DemoViewModel to Mobile.Views.DemoView
And you can always do a hybrid of these.

Calling DAL from ViewModel asynchronously

I am building composite WPF application using MVVM-light. I have Views that have ViewModels injected into them using MEF:
DataContext = App.Container.GetExportedValue<ViewModelBase>(
ViewModelTypes.ContactsPickerViewModel);
In addition, I have ViewModels for each View (Screens and UserControls), where constructor usually looks like this:
private readonly ICouchDataModel _couchModel;
[ImportingConstructor]
public ContactsPickerControlViewModel(ICouchDataModel couchModel)
{
_couchModel = couchModel;
_couchModel.GetContactsListCompleted+=GetContactsListCompleted;
_couchModel.GetConcatcsListAsync("Andy");
}
Currently, I have some performance issues. Everything is just slow.
I have 2 kind of related questions
What is the right way of calling DAL methods asynchronously (that access my couchdb)? await/async? Tasks? Because currently I have to write a lot of wrappers(OnBegin, OnCompletion) around each operation, I have GetAsyncResult method that does some crazy things with ThreadPool.QueueUserWorkItem , Action etc.
I hope there is the more elegant way of calling
Currently, I have some screens in my application and on each screen, there are different custom UserControls, some of them need same data (or slightly changed) from DB.
Questions: what is the right way to share datasource among them? I am mostly viewing data, not editing.
Example: On Screen A: I have Contacts dropdown list user control (UC1), and contact details user control(UC2). In each user control, their ViewModel is calling DAL:
_couchModel.GetConcatcsListAsync("Andy");
And on completion I assign result data to a property:
List<ContactInfo> ContactsList = e.Resuls;
ContactsList is binded to ItemsSource of DropDownListBox in UC1. The same story happens in UC2. So I end up with 2 exactly same calls to DB.
Also If I go to Screen B, where I have UC1, I’ll make another call to DB, when I’ll go to Screen B from Screen A.
What is the right way to making these interaction ? e.g. Getting Data and Binding it to UC.
Thank you.
Ad.1
I think you can simply use Task.Factory to invoke code asynchronously (because of that you can get rid off OnBegin, OnCompletion) or if you need more flexibility, than you can make methods async.
Ad. 2
The nice way (in my opinion) to do it is to create DatabaseService (singleton), which would be injected in a constructor. Inside DatabaseService you can implement some logic to determine whether you want to refresh a collection(call DAL) or return the same (it would be some kind of cache).
Then you can call DatabaseService instead of DAL directly and DatabaseService will decide what to do with this call (get collection from DB or return the same or slightly modified current collection).
Edit:
DatabaseService will simply share a collection of objects between ViewModels.
Maybe the name "DBCacheService" would be more appropriate (you will probably use it only for special tasks as caching collections).
I don't know your architecture, but basically you can put that service in your client application, so the plan would be:
Create DatabaseService.cs
[Export(typeof(IDatabaseService))]
public class DatabaseService : IDatabaseService
{
private List<object> _contacts = new List<object>();
public async Task<List<object>> GetConcatcsList(string name)
{
if (_contacts.Count == 0)
{
//call DAL to get it
//_contacts = await Task.Factory.StartNew(() => dal.GetContactsList(name));
}
else
{
//refresh list if required (there could be some condition)
}
return _contacts;
}
}
Add IDatabaseService to your ViewModel's constructor.
Call IDatabaseService instead of DAL.
If you choose async version of DatabaseService, then you'll need to use await and change your methods to async. You can do it also synchronously and call it (whenever you want it to be asynchronous) like that:
Task.Factory.StartNew(() =>
{
var result = dbService.GetContactsList("Andy");
});
Edit2:
invoking awaitable method inside Task:
Task.Factory.StartNew(async () =>
{
ListOfContacts = await _CouchModel.GetConatcsList ("Andy");
});

Binding an MVVM IEnumerable<POCO> to MyGeneration BLL entities (real-time)

I am working on my first WPF project using MVVM. I have successfully managed to abstract away my service layer so that I could use (for instance) XML files to store the data. Using IEnumerable collections of my POCO's, any changes to the table on the GUI automaticaly propagated to repository.
Now I'm trying to switch over to using our company DB2 database instead. We use MyGeneration dOOdads to generate DAL's and BLL's for our DB2 database. The DAL's have built-in CRUD and other utility methods.
One of my colleagues has managed to successfully bind the MyGeneration BLL DataView to his WPF application (he did not use MVVM) so that it too could make real-time changes to the DataView (only requiring a call to the BLL's SaveChanges method).
My problem is that in the translation between the MyGeneration DataView, and my collection of POCO's, I would need to explicitly update any changes at this layer.
Am I approaching this the wrong way? Would something like AutoMapper be an answer to my problem, or would I still not have real-time mapping?
public override IEnumerable<PromotionPlanHeader> ReadAll()
{
foreach (DataRow row in bll_PROMPLANH.DefaultView.Table.Rows)
{
yield return new PromotionPlanHeader
{
PlanNumber = Convert.ToInt32(row["PLANNUMBER"]),
Active = (row["ACTIVE"].ToString() == "1"),
Capturer = row["CAPTURER"].ToString(),
Region = row["REGION"].ToString(),
Cycle = row["CYCLE"].ToString(),
Channel = row["CHANNEL"].ToString(),
StartDate = ConvertDb2Date(row["STARTDATE"].ToString()),
EndDate = ConvertDb2Date(row["ENDDATE"].ToString()),
AdvertStartDate = ConvertDb2Date(row["ADVERTSTARTDATE"].ToString()),
AdvertEndDate = ConvertDb2Date(row["ADVERTENDDATE"].ToString()),
BpcsDealNumber = Convert.ToInt32(row["BPCSDEALNUMBER"]),
Description = row["DESCRIPTION"].ToString(),
DeactivationReason = row["DEACTIVATIONREASON"].ToString(),
LastSavedUsername = row["LASTUSER"].ToString(),
LastSavedDateTime = ConvertDb2DateTime(row["LASTDATE"].ToString(), row["LASTDATE"].ToString().PadLeft(6, '0'))
};
}
}
The "WPF DataGrid Practical Examples" walkthrough has really cleared up some things for me. Particularly, the Binding in a Layered Application chapter, which demonstrates how you handle Updates and Inserts with an IEditableObject interface.
Although that makes me wonder if a BindingList is not better(?)

WPF: Binding TreeView in MVVM way step by step tutorial

See the next post. This original one question content has been removed, as doesn't have any sense. Briefly, I asked how to bind XML (which I generated by mistake while parsing DLL assembly) to TreeView using XmlDataProvider in MVVM way. But later I understood that this approach was wrong, and I switched to generation of data entity model (just write classes which represent all the entities I would like to expose in the tree) instead of XML.
So, the result in the next post. Currently from time to time I update this "article", so F5, and
Enjoy reading!
Introduction
The right way I had found reading this article
It's a long story, most of you just can skip it :) But those, who want to understand the problem and solution, must read this all !
I'm QA, and some time ago had become responsible for Automation of the product I clicks. Fortunately, this automaton takes place not in some Testing Tool, but in Visual Studio, so it is maximally close to development.
For our automation we use a framework which consist of MbUnit (Gallio as runner) and of MINT (addition to MbUnit, which is written by the customer we work with). MbUnit gives us Test Fixtures and Tests, and MINT adds additional smaller layer -- Actions inside tests. Example. Fixture is called 'FilteringFixture'. It consist of amount of tests like 'TestingFilteringById', or 'TestingFilteringWithSpecialChars', etc. Each test consist of actions, which are atomic unit of our test. Example of actions are - 'Open app (parameter)', 'OpenFilterDialog', etc.
We already have a lot of tests, which contain a lot of actions, it's a mess. They use internal API of the product we QA. Also, we start investigation a new Automation approach - UI automation via Microsoft UI Automation (sorry for tautology). So the necessity of some "exporter", or "reporter" tool became severe for managers.
Some time ago I have got a task to develop some application, which can parse a DLL (which contains all the fixtures, tests and actions), and export its structure in the human readable format (TXT, HTML, CSV, XML, any other). But, right after that, I went to vacation (2 weeks).
It happens so, that my girlfriend went to her family until vacation (she also got it), and I remained at home so alone. Thinking what me to do all this time (2 weeks), I remember about that "write exporter tool task" and how long I have been planning to start learning WPF. So, I decided to make my task during vacation, and also dress a application to WPF. At that time I heard something about MVVM, and I decided to implement it using pure MVVM.
DLL which can parse DLL with fixrtures etc had been written rather fast (~1-2 days). After that I had started with WPF, and this article will show you how it ended.
I have spent a major part of my vacation (almost 8 days!), trying to sorted it out in my head and code, and finally, it is done (almost). My girlfriend would not believe what I was doing all this time, but I have a proof!
Sharing my solution step by step in pseudo code, to help others avoid similar problems. This answer is more looks like tutorial =) (Really?). If you are interested what were the most complicated things while learning WPF from scratch, I would say -- make it all really MVVM and f*g TreeView binding!
If you want an archived file with solution, I can give it a bit later, just when I have made a decision, that it is worth of that. One limitation, I'm not sure I may share the MINT.dll, which brings Actions, as it has been developed by the customer of our company. But I can just remove it, and share the application, which can display information about Fixtures and Tests only, but not about actions.
Boastful words. With just a little C# / WinForms / HTML background and no practice I have been able to implement this version of the application in almost 1 week (and write this article). So, impossible is possible! Just take a vacation like me, and spend it to WPF learning!
Step by step tutorial (w/o attached files yet)
Short repetition of the task:
Some time ago I have got a task to develop an application, which can parse a DLL (which contains test fixtures, test methods and actions - units of our unit testing based automation framework), and export its structure in the human readable format (TXT, HTML, CSV, XML, any other). I decided to implement it using WPF and pure MVVM (both were absolutely new things for me). The 2 most difficult problems for me became MVVM approach itself, and then MVVM binding to TreeView control. I skip the part about MVVM division, it's a theme for separate article. The steps below are about binding to TreeView in MVVM way.
Not so important: Create DLL which can open DLL with unit tests and finds fixtures, test methods and actions (more smaller level of unit test, written in our company) using reflection. If you are interested in how it had been done, look here: Parsing function / method content using Reflection
DLL: Separated classes are created for both fixtures, tests and actions (data model, entity model?).We'll use them for binding. You should think by yourself, what will be an entity model for your tree. Main idea - each level of tree should be exposed by appropriate class, with those properties, which help you to represent the model in the tree (and, ideally, will take right place in your MVVM, as model or part of the model). In my case, I was interested in entity name, list of children and ordinal number. Ordinal number is a number, which represents order of an entity in the code inside DLL. It helps me show ordinal number in the TreeView, still not sure it's right approach, but it works!
public class MintFixutre : IMintEntity
{
private readonly string _name;
private readonly int _ordinalNumber;
private readonly List<MintTest> _tests = new List<MintTest>();
public MintFixutre(string fixtureName, int ordinalNumber)
{
_name = fixtureName;
if (ordinalNumber <= 0)
throw new ArgumentException("Ordinal number must begin from 1");
_ordinalNumber = ordinalNumber;
}
public List<MintTest> Tests
{
get { return _tests; }
}
public string Name { get { return _name; }}
public bool IsParent { get { return true; } }
public int OrdinalNumber { get { return _ordinalNumber; } }
}
public class MintTest : IMintEntity
{
private readonly string _name;
private readonly int _ordinalNumber;
private readonly List<MintAction> _actions = new List<MintAction>();
public MintTest(string testName, int ordinalNumber)
{
if (string.IsNullOrWhiteSpace(testName))
throw new ArgumentException("Test name cannot be null or space filled");
_name = testName;
if (ordinalNumber <= 0)
throw new ArgumentException("OrdinalNumber must begin from 1");
_ordinalNumber = ordinalNumber;
}
public List<MintAction> Actions
{
get { return _actions; }
}
public string Name { get { return _name; } }
public bool IsParent { get { return true; } }
public int OrdinalNumber { get { return _ordinalNumber; } }
}
public class MintAction : IMintEntity
{
private readonly string _name;
private readonly int _ordinalNumber;
public MintAction(string actionName, int ordinalNumber)
{
_name = actionName;
if (ordinalNumber <= 0)
throw new ArgumentException("Ordinal numbers must begins from 1");
_ordinalNumber = ordinalNumber;
}
public string Name { get { return _name; } }
public bool IsParent { get { return false; } }
public int OrdinalNumber { get { return _ordinalNumber; } }
}
BTW, I also created an interface below, which implement all the entities. Such interface can help you in the future. Still not sure, should I was also add there Childrens property of List<IMintEntity> type, or something like that?
public interface IMintEntity
{
string Name { get; }
bool IsParent { get; }
int OrdinalNumber { get; }
}
DLL - building data model: DLL has a method which opens DLL with unit tests and enumerating data. During enumeration, it builds a data model like below. Real method example is given, reflection core + Mono.Reflection.dll are used, don't be confused with complexity. All that you need - look how the method fills _fixtures list with entities.
private void ParseDllToEntityModel()
{
_fixutres = new List<MintFixutre>();
// enumerating Fixtures
int f = 1;
foreach (Type fixture in AssemblyTests.GetTypes().Where(t => t.GetCustomAttributes(typeof(TestFixtureAttribute), false).Length > 0))
{
var tempFixture = new MintFixutre(fixture.Name, f);
// enumerating Test Methods
int t = 1;
foreach (var testMethod in fixture.GetMethods().Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0))
{
// filtering Actions
var instructions = testMethod.GetInstructions().Where(
i => i.OpCode.Name.Equals("newobj") && ((ConstructorInfo)i.Operand).DeclaringType.IsSubclassOf(typeof(BaseAction))).ToList();
var tempTest = new MintTest(testMethod.Name, t);
// enumerating Actions
for ( int a = 1; a <= instructions.Count; a++ )
{
Instruction action = instructions[a-1];
string actionName = (action.Operand as ConstructorInfo).DeclaringType.Name;
var tempAction = new MintAction(actionName, a);
tempTest.Actions.Add(tempAction);
}
tempFixture.Tests.Add(tempTest);
t++;
}
_fixutres.Add(tempFixture);
f++;
}
}
DLL: Public property Fixtures of the List<MintFixutre> type is created to return just created data model ( List of Fixtures, which contain lists of tests, which contains lists of Actions ). This will be our binding source for TreeView.
public List<MintFixutre> Fixtures
{
get { return _fixtures; }
}
ViewModel of MainWindow (with TreeView inside): Contains object / class from DLL which can parse unit tests DLLs. Also exposes Fixtures public property from the DLL of List<MintFixutre> type. We will bind to it from XAML of MainWindow. Something like that (simplified):
var _exporter = MySuperDllReaderExporterClass ();
// public property of ViewModel for TreeView, which returns property from #4
public List<MintFixture> Fixtures { get { return _exporter.Fixtures; }}
// Initializing exporter class, ParseDllToEntityModel() is called inside getter
// (from step #3). Cool, we have entity model for binding.
_exporter.PathToDll = #"open file dialog can help";
// Notifying all those how are bound to the Fixtures property, there are work for them, TreeView, are u listening?
// will be faced later in this article, anticipating events
OnPropertyChanged("Fixtures");
XAML of MainWindow - Setup data templates: Inside a Grid, which contains TreeView, we create <Grid.Resources> section, which contains a set of templates for our TreeViewItems. HierarchicalDataTemplate (Fixtures and Tests) is used for those who have child items, and DataTemplate is used for "leaf" items (Actions). For each template, we specify which its Content (text, TreeViewItem image, etc.), ItemsSource (in case of this item has children, e.g. for Fixtures it is {Binding Path=Tests}), and ItemTemplate (again, only in case this item has children, here we set linkage between templates - FixtureTemplate uses TestTemplate for its children, TestTemplate uses ActionTemplate for its children, Action template does not use anything, it is a leaf!). IMPORTANT: Don't forget, that in order to "link" "one" template to "another", the "another" template must be defined in XAML above the "one"! (just enumerating my own blunders :) )
XAML - TreeView linkage: We setup TreeView with: linking with data model from ViewModel (remember public property?) and with just prepared templates, which represent content, appearance, data sources and nesting of tree items! One more important note. Don't define your ViewModel as "static" resource inside XAML, like <Window.Resources><MyViewModel x:Key="DontUseMeForThat" /></Window.Resources>. If you do so, then you won't be able to notify it on property changed. Why? Static resource is static resource, it initializes ones, and after that remains immutable. I might be wrong here, but it was one of my blunders. So for TreeView use ItemsSource="{Binding Fixtures}" instead of ItemsSource="{StaticResource myStaticViewModel}"
ViewModel - ViewModelBase - Property Changed: Almost all. Stop! When user opens an application, then initially TreeView is empty of course, as user hasn't opened any DLL yet! We must wait until user opens a DLL, and only then perform binding. It is done via OnPropertyChanged event. To make life easier, all my ViewModels are inherited from ViewModelBase, which right exposes this functionality to all my ViewModel.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, args);
}
}
XAML - OnPropertyChanged and commanding. User clicks a button to opens DLL which contains unit tests data. As we using MVVM, then click is handled via commanding. At the end of the OpenDllExecuted handler OnPropertyChanged("Fixtures") is executed, notifying the Tree, that the property, to which it is bind to has been changed, and that now is time to refresh itself. RelayCommand helper class can be taken for example from there). BTW, as I know, there are some helper libraries and toolkits exist Something like that happens in the XAML:
And ViewModel - Commanding
private ICommand _openDllCommand;
//...
public ICommand OpenDllCommand
{
get { return _openDllCommand ?? (_openDllCommand = new RelayCommand(OpenDllExecuted, OpenDllCanExecute)); }
}
//...
// decides, when the <OpenDll> button is enabled or not
private bool OpenDllCanExecute(object obj)
{
return true; // always true for Open DLL button
}
//...
// in fact, handler
private void OpenDllExecuted(object obj)
{
var openDlg = new OpenFileDialog { ... };
_pathToDll = openDlg.FileName;
_exporter.PathToDll = _pathToDll;
// Notifying TreeView via binding that the property <Fixtures> has been changed,
// thereby forcing the tree to refresh itself
OnPropertyChanged("Fixtures");
}
Final UI (but not final for me, a lot of things should be done!). Extended WPF toolkit was used somewhere: http://wpftoolkit.codeplex.com/

Silverlight And DataAnnotations

When I am not using data controls like the DataForm and DataGrid is there any use for the attributes like [Required], [StringLength] on my entities? Can these be used for validation outside of the above mentioned data controls?
If so, could you point me to some examples or documentation. I would like to prevent users from pressing the OK button if there are any validation errors and would like to avoid the throwing of exceptions from the setters(possible?).
Yes, those can be used for validation without using UI controls. Brad Abrams has a blog post with details on using those attributes for data forms, but seems like you should be able to separate the UI portion of his post from the core validation logic.
From the post, here's a sample property with validation logic added manually.
[DataMember()]
[Key()]
[ReadOnly(true)]
public int EmployeeID
{
get
{
return this._employeeID;
}
set
{
if ((this._employeeID != value))
{
ValidationContext context = new ValidationContext(
this, null, null);
context.MemberName = "EmployeeID";
Validator.ValidateProperty(value, context);
this._employeeID = value;
this.OnPropertyChanged("EmployeeID");
}
}
}

Resources