Tuesday, 10 November 2015

Intro to MVVM light

Let us discuss about MVVM light used in the windows phone applications. This MVVM light was implemented to reduce the time to add code to the project. It is a toolkit which is developed to help the beginners to how to code in MVVM pattern. The definition of MVVM light is to accelerate the creation and development of MVVM applications in WPF, Silver-light, Windows Store, Windows Phone and Xamarin. You can refer the full document in this link.

The MVVM Light Toolkit adds the helper classes to the ViewModel by default when you install the MVVM package from the Nuget manager. It has ViewModelLocator and MainViewModel classes which helps the project to code in cleaner and easier. This MVVM light is easy to extend and manage the classes. It also creates testable applications and allows you to have thinner user interface in the view. It also maintains good security standards with some namespaces added to the library. This toolkit also help to open and edit the user interface into Blend. 

Difference between MVVM and MVVM light 

MVVM is a design pattern which is used to add code as per the patterns. i.e Our MainPage.xaml, BlankPage.xaml will be placed in View folder, Main_ViewModel.cs placed in ViewModel folder and Model.cs placed in Model folder. DataContext of the View is set with ViewModel class. MVVM is not only just file organization but also ensuring the code, is written as per the pattern too (separation of logic and all the nice stuff which should be implemented as per the pattern). We doesn't need any reference to design MVVM for our project

MVVM Light is mainly used when we need to communicate between multiple ViewModels. And we also have add on helper classes when we install MVVM light from Nuget manager as we already discussed above, given with a ViewModel folder.

How to install MVVM light to the existing project.

In your solution explorer - Add Reference - Manage Nuget packages - search for MVVM light and install to your project.

When you select install button after installing MVVM to the project it popups a dialog box with Accept and Decline button. This is to add the libraries to the project. Just select accept button.

You can see the references and classes added to the solution explorer.


Just extend your project with views and models. :)

Monday, 9 November 2015

Simple example for Observable collection

In our previous example we discussed about the simple examples of INotifyPropertyChanged, ICommand which are used in MVVM layout. Today let us discuss about Observable collection.

Observable Collection is nothing but it represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list will be refreshed. Follow this link to refer the description about Observable collection in MSDN.

There are two sentences we should consider here, “dynamic data collection”, and “provides notifications when items get added…”.

  1. Dynamic data is nothing but a list.  A collection of generic type <T> objects,  i.e it can keep a collection of any objects.
  2.  It provides notifications when items get added. This definition looks similar to INotifyPropertyChanged. It also notifies when the change is updated. ObservableCollection class is a built in implementation of a data collection that implements INotifyPropertyChanged.

If we use a list we should simply push notifications manually. Mainly  ObservableCollection itself only notifies for changes to the collection,. It is not for property changes of the individual objects in the collection.

Let us illustrate an example for Observable collection. In the previous example of INotifyPropertyChanged we created a Notify class and implemented interface. We gonna use the same class to extend our application to use Observable collection. Refer this link for the INotify class and add the below code


class Observ : ObservableCollection<Notify>
{
this.Add(new Notify { Title = "Myname", Desc = "fine", Year = 2014 });
this.Add(new Notify { Title = "Yourname", Desc = "good", Year = 2014 });
this.Add(new Notify { Title = "Yourday", Desc = "bad", Year = 2014 });
}


We should update our UI to display these items in the list view. So drag and drop the list view control. Add a data template to the listview to bind the text to the text blocks. Add the following code to list view control.

 <DataTemplate x:Key="MyDataTemp">
<StackPanel>
<TextBlock Text="{Binding Title}"/>
<TextBlock Text="{Binding Desc}"/>
<TextBlock Text="{Binding Year}"/>
</StackPanel>
</DataTemplate>

And just refer the key to the data template with the control name. It looks like
<ListView ItemTemplate="{StaticResource ListViewDataTemplate}" x:Name="lv1"/>

And the final step is done in code behind file. We should add the item source of the listview to the class..

Observ ob = new Observ();
lv1.ItemsSource = ob;

So in this way we can add the static data to the observable collections. It is the simplest way. We can also add the dynamic data using some api's where the data will be from requested url.

Thursday, 5 November 2015

Simple example for INotifyPropertyChanged

Data binding plays a vital role in developing applications with rich UI and neat coding. Data binding is the process that establishes a connection between the application UI(view) and main logic/business logic(i.e view model). Today let us discuss about some advanced concepts in data binding like INotifyPropertyChanged which is used in MVVM architecture. A interface which is used to update the UI with respect to the code using two way binding. Business logic/Main logic is the data which should be displayed on the UI and the also can be managed.

We can configure our data binding in four different ways

  • One way - causes changes to source
  • Two way - causes changes to source and target too.
  • Oneway to source  - reverse of one way binding
  • One time  - causes the source to initialize the target property, but changes do not propagate 

INotifyPropertyChanged uses System.ComponentModel namespace.

Create a class and add the below code

class Notify:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string title { get; set; }
        private int year { get; set; }
        private string desc { get; set; }

        public string Title
        {
            get { return title; }
            set{
                title = value;
                NotifyPropertyChanged("Title");
            }
        }
        public int Year
        {
            get { return year; }
            set
            {
                year = value;
                NotifyPropertyChanged("Year");
            }
        }
        public string Desc
        {
            get { return desc; }
            set
            {
                desc = value;
                NotifyPropertyChanged("Desc");
            }
        }
        protected void NotifyPropertyChanged(string propertyname)
        {
            if(PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); 
            }
        }

    }

When we add INotifyPropertyChanged after to the class name we can implement the interface by clicking below the blue dotted line. When we implement INotifyPropertyChanged we can see one event implemented

public event PropertyChangedEventHandler PropertyChanged;

We should bind these strings to the UI. Add the below code in the XAML file(Add your own properties for better view )

        <TextBlock Text="{Binding Title}"  Margin="22,10,0,35.75"/>
        <TextBlock Text="{Binding Desc}" Margin="22,10.25,0,35.5"/>
        <TextBlock Text="{Binding Year}" Margin="22,9.5,0,35.667"/>
        <Button Content="Click Me" Click="Button_Click" Margin="137,134.5,133,-109.333"/>
        <TextBox Text="{Binding Title, Mode=TwoWay}" />
        <TextBox Text="{Binding Desc, Mode=TwoWay}"  />
        <TextBox Text="{Binding Year, Mode=TwoWay}"  />
    </Grid>

Now to display the data in the page loaded add the below code.

        Notify n = new Notify();
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            
            n.Title = "X-Men";
            n.Year = 2015;
            n.Desc = "good";
            this.DataContext = n;
        }

When we see the output the values will be displayed in the text box and text blocks. When we edit some thing in the text box the change will be affected in the text block, this is because of two way binding

We can also update our text in some button click events. While we work on real time data it will be more useful updating the values in the controls.

Tuesday, 3 November 2015

Simple example similar to MVVM layout

Today let us discuss  about a simple example in windows phone 8.1 apps with MVVM layout.

MVVM is mainly to separate the user interface ie view and the view model. This can be achieved by data binding. There are many classes used to maintain the standards of MVVM flow. Most of the developers use this MVVM architecture to design the applications mainly for some reasons. The code can be reusable. The unit testing is very easy if an application follows MVVM. Updates can be easily managed in the code.

It is possible to show a message dialog in a button click. This is done by generating a click event. But with out this click event we can display the message dialog by using command interfaces.

Similar to this example the developers follow this kind of models and views.

Drag and drop a button to the designer in windows phone 8.1 MainPage.xaml

Create a new class file and name it.

Now add the below code to the class file

In the below code CommandEx is the name of my class and ICommand is the interface. When we click on the blue dotted line down to the text we can implement the interface in our code. It adds CanExecute and Execute method with EventHandler.


class CommandEx:ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (parameter != null)
            {
                return true;
            }
            else
                return false;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var msd = new MessageDialog(parameter.ToString()).ShowAsync();
        }
    }


So with the help of binding the code in the command will be executed.


    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
    <Page.Resources>
        <local:CommandEx x:Key="ll"/>
    </Page.Resources>

    <Grid>
        <Button Content="Click"
                HorizontalAlignment="Left"
                Command="{StaticResource ll}"
                CommandParameter="Hello World"
                Margin="60,164,0,0"
                VerticalAlignment="Top"
                Height="42"
                Width="158"/>

    </Grid>

In the XAML code add page resource to use the class (CommandEx). Define a key and use that key in the button, binding to the command. Here the command parameter is from the execute method defined in the class.

Monday, 2 November 2015

Introduction to MVVM for Windows phone 8.1


Model-View-ViewModel is developed by Ken Cooper and Ted Peters. It is mainly developed to simplify the event driven programming(i.e the mouse buttons clicks, key down, key up events)etc. 

Why MVVM?

It is mainly to separate the view and model in the applications. When our application needs to be changed without changing design of our application we can change the model. 

For example: When an application is updated from one version to other if the application uses MVVM architecture it happens easy to modify their code. 

Reusability of the classes, make the code light and efficient, bind the data from view to model and make the updates to the design with out  any changes.

It is easy to test the application when the developers follow MVVM architecture.

For a simple application it is not necessary to use MVVM architecture while it makes the code very complex. Assume an application with a buuton and textblock to display the text in button click it is not necessary to follow MVVM architecture. Because we are not adding any values or not updating the view.

In MVVM the data gets from other source like database, webservice or while we bind the data in the ViewModel to the view.

While we explain about MVVM these terms play a crucial role. They are
Model
View
ViewModel



Model is the core that implements the main logic of the view and view model. For example some classes defined in the model is used in the viewmodel.  

View is the user interface of the application.Data Binding plays the vital role .

View model is the layer of abstraction between the view and model. The entire logic is done in this view model.

Thursday, 27 August 2015

C# - Overview

As we know C# was developed together with .Net framework most of them refer this C# language as .Net language. This C# language is designed in the way that it is simple, easy and type safe. It acquires most of the concepts of the other high level language. It mainly supports Object oriented programming concepts. We should bother about memory leaks particularly in this language. It has a rich class library with many classes, methods and many functions that can be implemented easily. If you need to run your application with C# language that platform should particularly have .Net framework in that platform. It also has a good support of distributed systems. It also supports reusable concepts. This language is used to write programs for many different kind of applications like Windows desktop applications, Windows store applications, Web service and many more.



Some of the features of C# are

Security is the main feature which was implemented in this C# language by Microsoft. The concepts of delegates also implemented.
Backward Compatibility is very good in C#. It supports the windows applications in the cross platform portability
Programming support  with respect to C# is high compared to other languages. It supports the wide concepts from most of the programming languages.
C# can be used to write wide range of applications due to their portability, from simple desktop widgets to high end web service. We can also write applications with respect to secure systems programming and even robotics.

So we have most of the features in other languages but why should we prefer C# rather than other languages. 


  • Mainly when we work with Windows platform applications we should particularly choose this C# language while it has the rich libraries particularly when we develop applications with respect to Windows.
  • Even we have other programming languages like VB.Net similar to this. But C# is more compatible compared to this language.
  • Once while we begin to understand programming and using this C#, the learning procedure with c# will be much shorter compared to other languages.
  • We can say C# is a loose language while compared to VB.Net
  • We use delegates in C#, encapsulated signatures which enables type safe.
  • It supports all the concepts of Object Oriented Concepts like inheritance, polymorphism, encapsulation.

C# is more powerful language compared to Java. The code written in Java can be written easily in C# and many features such as linq, lambda is impossible in Java. And we also know that C# language is type safe. It is easy to write programs compared to Java. Most of the features were covered in C# with respect to Java and it is easy compared to Java to access the most of the features. Even C# language also face some problems. It should be particularly executed if and only if the operating system installed with .Net framework

Wednesday, 26 August 2015

Intro to Visual Studio

We discussed many concepts about .Net framework. With Common language runtime, base class libraries and many other concepts. You can also refer the official website of Microsoft in order to have a good and full knowledge about this .Net technology. To get the full details of the .Net technology please click here. You can also download the latest version of Visual Studio 2015 Community. To download the freeware of Visual Studio 2015 just click here.

We can implement these Microsoft languages in Visual Studio. It is the Integrated development environment for Microsoft. By using this tool we can work on different kinds of applications such as Windows store applications, Windows phone applications, Windows form applications nothing but our windows desktop applications, web applications, WPF applications etc. We can develop all these applications by using this particular development tool. We should install this Visual Studio tool into our PC. So to access this particular tool we need some requirements for our computer. Our computer should be configured with more than 1 GB of RAM and minimum of 20 GB of space. We can get freeware of this tool in official Microsoft account.


So let us start how to code using this .Net framework. Microsoft designed many languages to use them in the programming. Most of the familiar languages used in .Net world are C#, VB.Net, F#, ASP.Net etc.

We choose C# language in order to program using this Visual Studio 2013. So in order to code in this Visual Studio we should need a basic knowledge of programming concepts. C# language is a combination of both C and C++. It is type safe. It follows the concepts of object oriented programming. It is mainly designed to be simple, general purpose and easy access of the classes. It borrows most of the concepts of other programming language and designed in a simple way. Programs written in C# requires .Net framework to be installed in the computer where you execute the code.  Sometimes C# is referred as .Net language because both C# and .Net framework were designed together.

C# can be written with any text editor, like Windows Notepad, and these programs can be compiled with the help of  C# Command line compiler, csc.exe, which comes with the .NET framework. Most people uses an IDE (Integrated Development Environment)Visual Studio which can be used to work on every application with respect to .Net framework. With the help this C# programming we can develop different kinds of applications like client server applications, web applications, desktop applications, database applications and much more.