WPF and MVVM

I am going to assume you know WPF and C# fairly well and going to speak about MVVM design pattern and how these blend together.
I will first expose the reasons behind all the hassle. The reason is that we want to separate between the UI and the functionality and the logic. UI can be very volatile, changing often and can involve complex designing and we don’t want the functionalities and logic to be UI dependent.

Design patterns can provide us the means to do that,however, in simple applications, the use of design pattern can turn into a real useless headache therefore design patterns are particular useful and should be used for business applications, large applications in general.
The MVVM(Model-View-ViewModel) was developed by Microsoft and makes full advantage of the WPF technologies. The keyword in MVVM is binding, as the view bind to properties of a ViewModel which in turn exposes data contained in model objects to the view. If a property value changes in the ViewModel, those new values automatically propagate to the view due to the data binding.
When a button is clicked in the View, a command on the ViewModel performs the requested action. The ViewModel performs data operations, never the View.
This is often called loosely coupled design because the View is not aware of the ViewModel and the ViewModel doesn’t care how the data is displayed and as well as the fact that you don’t have to write extra code to update the view when the data changes.
Another huge advantage of this approach is that writing unit tests are fairly easy, as they are written on the ViewModel and you don’t interact with the UI and makes the testing of functionality easy and natural.

So the ViewModel is basically a class which implements properties and command to which the view can bind and notifies the view of any state change through change notification events.
The properties and commands from the ViewModel define the functionalities to be offered by the UI, but the View determines how the functionality is going to be rendered.
The ViewModel can manipulate the model data so that it can be easily consumed by the View. It can also define additional properties to support the view, but those would normally not belong to the model. For example it can define a property that combines the first name and last name into one property to make it easier for the view to display it.
Another functionality of the ViewModel is validation logic to ensure data consistency.
To summarize, the view model has the following key characteristics:

  • The view model is a non-visual class and does not derive from any WPF base class. It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model.
  • The view model typically does not directly reference the view. It implements properties and commands to which the view can data bind. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
  • The view model coordinates the view’s interaction with the model. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
  • The view model may define logical states that the view can represent visually to the user.

The Model is also a class that encapsulates business logic and data. By business logic I mean any rules, restrictions and management of the data that a particular business has.
The Model offers support for property and collection changed notification though the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Model classes that are collections usually derive from the ObservableCollection class which already implements the INotifyCollectionChanged interface.

To wire up everything together WPF uses data bindings and provides really powerful capabilities. Data bindings are either one-way or two-way: one-way refers that the UI simply reflects the value of underlying data but the two-way automatically updates the UI when the data is changed(using the above mentionated interfaces).
WPF data binding supports binding to nested properties via the Path property.

This is just an introduction to the MVVM pattern use within WPF and does not cover a very important chapter: data bindings. Maybe I’ll cover it on another post.

Windows 8 Apps Development

This is somehow related to the previous C# articles but also speaks about Windows 8 (8.1.) environment.

As you probably know already Windows 8 has it’s own store and and as it is quite new it can be a good way to make your entry in mobile devices world.
I will briefly present what languages are at your disposal when developing Windows 8 apps and get more into C# and .NET.

Windows 8 start screen supports a tiled layout, where each tile represents an application installed on the machine. Unlike a typical Windows desktop application, Windows 8 applications are built for touch-screen interactions. They are also run in full-screen renderings and lack the usual “chrome” (e.g., menu systems, status bars, and toolbar buttons) we see in many desktop applications.
Building a Windows 8 application requires developers to adhere to an entirely new set of UI design guidelines, data storage methodologies, and user input options. To be sure, a Win8 app is much more than a tile installed on the Windows 8 start screen.

Creating and running a Windows 8 application is only possible on Windows 8 and is not supported under Windows 7. In fact, if you install Visual Studio on Windows 7 (or earlier), you will not even see Windows 8 project templates appear in the New Project dialog box.

So as I previously mentioned we can develop applications in .NET (mostly any .NET aware language) and XAML which is not quite new as we do have XAML in Silverlight and WPF.
There’s HTML5 and CSS3, there is Javascript and that awesome bouncing back language, what was it? Oh, C++.

Coding a Little C++
Why C++ ?
It is much closer to the operating system than .NET and gives very fine-grained control over the UI and device interactions.
It is possible — even recommended — to build Windows 8 application logic in C++. Games, especially, benefit from the large amount of existing code in the community and strong library support. C++ applications are likely faster than HTML5 or .NET, providing an outlet for very processor-heavy tasks. And, as with .NET, C++ libraries can be consumed by HTML5 Windows 8 applications, too.

So back to the .NET and C#

Programming a Windows 8 application requires developers toR tap into an entirely new runtime layer termed (appropriately enough) Windows Runtime (WinRT). Be very aware that WinRT is not the .NET CLR, however it does offer some similar services such as garbage collection.

In addition, these applications are created using a completely new set of namespaces, all of which begin with the root name Windows.
The Windows.* namespaces offer functionality that mirrors many APIs of the .NET base class libraries. In fact, from a programming point of view, building an application for WinRT feels very similar to building a .NET application for the CLR.
As well, many of the Windows.* namespaces offer similar (though not identical) functionality as is found in the .NET base class libraries.

In addition to the Windows.* namespaces, Windows 8 applications can also make use of a large subset of the .NET platform. Collectively, the .NET APIs for Windows 8 applications, provide support for generic collections, LINQ, XML document processing, I/O services, security services etc.
Just keep in mind that .NET proper is not used to build Windows 8 applications. Rather, you will make use of new libraries (Windows.*), a new runtime (WinRT), and a subset of .NET proper (the .NET APIs) to create such a program.

The keyword here is “subset” as from my own personal experience I learned that you have limited access to what you were used to from WPF and WF applications. One simple example I can think of is that in WinRT you are not able to access an SQL Server which I find rather disturbing as not everyone has an Azure subscription and the SQLite is no match for SQL Server.

Sadly I am unable to provide you free books on this matter as there are not any good free books. However you can find plenty of resources on ACM learning platform if you have a subscription.
For that reason I will try to write more articles on this field, including Hands-ON articles to get you started as well as recommendation of other resources on this area.

About C++

Today, I am going to speak up for C++ and the importance I see it has nowadays. I am going to assume you are fairly familiar with C/C++.

Some people say that learning C++ today is a waste of time and quite useless as we have much more powerful languages such as Java and C#, well I am against that wave. Though I agree that both above mentioned languages have more productivity and are somehow more powerful than C++ I still think that people should learn C++ no matter what.

The reason I think that is that C++ is so permissive and have so many concepts which in higher abstracted languages are invisible for the programmer that any coder should be really familiar with them.
Some other people say it’s just too hard. Well, I am not going to argue it’s easy but once mastered you can jump to other languages in a heartbeat so keep that in mind.

I will not bring up the “speed” argument because as of today both Java and C# are very fast, equally fast to C++ and even faster than C++ in some aspects. Though I have to say that using C++ you will be able to target a specific hardware and make necessary optimizations so that the execution speed would be truly amazing.

And now comes that awful and painful moment(for others not for me) to speak about pointers. Well, pointers are the crown of C++ as most people have a hard time with them and even very experienced programmers get their necks twisted in large programs.
Because of the so permissive C++ compiler and the manual memory management pointers have given programmers lots of headaches. There are advantages and disadvantages of pointers and just to be clear you don’t have to deal with them in C# or Java for that manner.

As I previously said, Java and C# are more productive due to their huge libraries. You can do complex things with just a few lines of code whereas in C++ the same effect would need a up to 10x more code lines, but some things are harder to code in Java or C# than in C++. Here are some examples I could find:

  1. Generics are not as powerful as templates (try to write an efficient generic Parse method (from string to T), or an efficient equivalent of boost::lexical_cast in C# to understand the problem)
  2. RAII remains unmatched (GC still can leak (yes, I had to handle that problem) and will only handle memory. Even C#’s using is not as easy and powerful because writing a correct Dispose implementations is difficult)
  3. C# readonly and Java final are nowhere as useful as C++’s const(*) (There’s no way you can expose readonly complex data (a Tree of Nodes, for example) in C# without tremendous work, while it’s a built-in feature of C++. Immutable data is an interesting solution, but not everything can be made immutable, so it’s not even enough, by far).

Of course if you want to develop end users apps with GUI probably C# WPF or JAVA Swing is the the way you want to do it though C++ also offer the QT library, however it’s less intuitive and fun than the other two.
For servers, C++ is still the best bet because there every millisecond counts and you really need to max out the performance.

So why do I recommend people to get started with C++ and master it:

  • because it’s helping you thinking of optimizations
  • it’s sometimes faster
  • pointers – we love them !!
  • understanding of low level PC arhitecture

It’s much easier for someone to switch languages if you know how data is represented in hardware and how things are going “under the hood” and as I always say use the right tool(PL) for the right job, you should not be restricted by a programming language when you have to solve a task.

There is also the matter of static compiler vs JIT about which you can read about here.
You can also find more opinions on this matter
here.

So maybe C++ is old and “not cool” but is still alive and kicking (pretty hard if you ask me) and you should get a few keyboard smashed before going up for some of the more enjoyable languages out there.
PS: There are probably more things to say on this topic so feel free to share!

Object oriented programming

Lately I’ve seen a lot of people struggling with this concept and being the very base of modern programming I think I should talk about it.
OOP, formally called Object Oriented Programming it’s a paradigm that helps the programmer to express himself in a more natural way with concepts he already knows from daily life. This also dramatically increases the level of understanding of the code written, maintainability and further code addition.

Basically you have classes with methods, properties and member variables to designate objects. This principle is called encapsulation. Methods are functions through which the user interacts with the object. Note the difference between properties and member variables. Though it’s language dependent, a property often designates a variable with GET and SET (mutator and accessor functions) and does not have memory allocated on its own however the associated filed does and a member variable or field designates a class variable. Look at the example below:
[gist id=8675207 file=OOP]

We also have at least two special functions(methods) in a class, those are the constructor and destructor, their role is to initialize the object(allocate memory in non managed languages – C++ and members initialization) and to destroy the object(free allocated memory in non managed languages, not really used in managed languages) respectively. The compiler provides an empty constructor and destructor by default, they don’t anything. Pay attention that a constructor has the same name as the class and it does not return anything. The destructor has a “~” in front and has the same name as the class. The destructor makes no sense in managed languages because the garbage collector is in charge of when an object is destroyed.

Another principle of OOP is security. Often we use access modifiers to accomplish this (private, protected, public and internal in C#).

  • public – can be accessed by anyone in or outside the class.
  • protected – can be accessed by anyone in the same class or in a class that inherits the containing class.
  • private – can be accessed by anyone in the same class.
  • internal (C# specific) – can be accessed only from the same assembly, but not other assemblies. Java has this by default in packaging.

As I already stated abstraction was the main reason of OOP, because a more natural, faster and easier way to code was needed. Programmers needed to avoid “spaghetti code” to make their programs easier to understand and easier to maintain. I will talk about inheritance a bit later as it is a vast subject and it’s language dependent(C++ allows native multiple inheritance while C# and Java require Interface to accomplish this).

Will talk about polymorphism, abstract classes, overloading and templates on a future article.
Finally some of the OOP languages out there are: C++ (C is not), PHP, Java, C#, Ruby, Python etc.

If you are anxious and want to learn faster you can find a good resource here

Further intro to C#

I’ve got some positive feedback on the article with C# so I decided to do a bit more digging into the subject.

So, you’re interested in coding in C# but you are not really sure what is best for you. Supposedly you are not interested in Console Applications and you want something with a nice interface you have to choices: Windows Forms and WPF. In the following lines I’ll speak about the two.

Windows Forms it’s definitely easy: easy to learn, easy to use and  has huge documentation, support and APIs, being here for quite a while now. There are also a lot more devs on Windows Forms than on WPF. It’s easy to learn and use because of “Drag and Drop” feature by which you can build a functional application very fast. If you are in need of an app that does something and you are not really interested on how does it look you can go for Windows Forms.
Usually, you’re using Windows Forms to do something (internal) and you don’t have much time at disposal.

Windows Presentation Foundation(WPF) on the other hand is newer, fewer devs working with it and it’s a bit harder to learn to new comers. In WPF you have much more freedom of design and if you would wanted a professional app (i.e. for clients) you should go for WPF. The look and feel is just great, it looks modern and behave accordingly. In WPF you can add lots of animations, transitions, making it suitable for end-users UI. However there is a bit of a trouble to new comers, why is that exactly?
Well, because there is an XML (XAML) component which is in charge of design and not many people are used to it first hand, but once you get used it, it’s really great: it is more maintainable, cleaner and you can control your elements very precisely.
There is also the advantage of data binding, as WPF is great with it having behind it the MVVM pattern (Model – View View – Model) .
Also, if you’re learning WPF now it’s going to be much easier for you to design and code Windows 8 (8.1) Apps or Windows Phone apps as those apps have similar behavior.

EDIT: What I forgot to mention is that Windows Forms is portable to other platforms through the Mono Project but WPF is not.

Code snippets:

[gist id=8639173 file=WindowsForms]

[gist id=8639173 file=WPF]

 

To summarize, you use Windows Forms when you want something fast and you don’t care that much about the interface and WPF when you want something more elaborate and UI is a decisive factor. Keep in mind that Windows Forms it’s easier to learn and use and WPF represents somehow the future.

 

Simple Share Buttons