Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Friday, February 6, 2015

Prism MVVM pattern with Applcaition development

Prism is one of the design patterns which defined by Microsoft Patterns and Practices team for building composite Applications in C# , XAML (WPF,Store Applications etc ) .

Why MVVM is not enough ?

When we creating application with MVVM there is few questions and practices we need to figure out. 
  • Should I use Prism to provide support for MVVM?
  • Should I use a dependency injection container?
    • Which dependency injection container should I use?
    • When is it appropriate to register and resolve components with a dependency injection container?
    • Should a component's lifetime be managed by the container?
  • Should the app construct views or view models first?
  • How should I connect view models to views?
    • Should I use XAML or code-behind to set the view's DataContext property?
    • Should I use a view model locator object?
    • Should I use an attached property to automatically connect view models to views?
    • Should I use a convention-based approach?
  • Should I expose commands from my view models?
  • Should I use behaviors in my views?
  • Should I include design time data support in my views?
  • Do I need to support a view model hierarchy?
 (reference https://msdn.microsoft.com/en-us/library/windows/apps/xx130657.aspx )

Why Prism?

Prism contains wire frame which can help to accelerate application development in  MVVM and It already contains commonly required core features in application development.


Let's Start Coding 


Here we are going to create windows store application using Prism

1. Create new windows store application project (Blank application)
2. Go to package manager console or manage nuget packages and install prism nuget to the application

 3. Now starts coding . Here we are using MVVM and I create few folders to isolate resources in the project such as
  • ViewModel - for ViewModel
  • Model - for Model
  • Controles - for BaseControls
  • View - for XAML pages 
  • Enum - for enumerations
  • Interfaces - for Interfaces 
and then put MainPage.xaml  in to teh View Folder (drag and drop)

Now my project like this


















 Code for prism
 Now we have to convert our application to prism
1. App.XAML and App.XAML.cs

<prism:MvvmAppBase
    x:Class="SamplePrism.App"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SamplePrism">
 
</prism:MvvmAppBase> 
 
 
sealed partial class App : MvvmAppBase
   {
       public App()
       {
           this.InitializeComponent();
       }
 
       protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
       {
          //Main is the name of view i need to navigate 
           this.NavigationService.Navigate("Main"null);
 
           return Task.FromResult<object>(null);
       }
   } 


2. Then create PageBase in controls  from Prism MVVM

public abstract partial class PageBasePage,IView
   {
   } 
3. Then Use this page base in our Views, xaml

 Change MainPage.xaml and MainPage.xaml.cs as  follows
<controls:PageBase
    x:Class="SamplePrism.Views.MainPage"
    xmlns:prism="using:Microsoft.Practices.Prism.Mvvm"
    xmlns:controls="using:SamplePrism.Controls"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SamplePrism.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    prism:ViewModelLocator.AutoWireViewModel="True"
    xmlns:designtime="using:SamplePrism.DesignTimeViewModel"
    mc:Ignorable="d">

public sealed partial class MainPage : PageBase
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
    }

4. In here I'm craeting Interface to keep the properties of MainPage But this is optional. You can jsut implement the ViewModel without this interface


Here is My interface


public interface IMainPageViewModel
   {
       string Title { getset; }
   }


5. Lets Starts MainPageViewModel

public class MainPageViewModel : ViewModelIMainPageViewModel
   {
       string _Title = default(string);
       public string Title { get { return _Title; } set { SetProperty(ref _Title, value); } }
 
       public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<stringobject> viewModelState)
       {
           this.Title = "Hello prism";
       }
   }

With prism MVVM it conains basic funtions in store app such like OnNavigatedTo , OnNavigatedFrom etc. You can directly use them inside the ViewModel 

Run and Enjoy the Prism.

It is really easy to build in complex applications in enterprise level. even if you  not like Prism code in specific scenario you can switch with your old MVVM too inside the same project










Full Code 
http://bit.ly/1DL68OI







Tuesday, February 3, 2015

Tips to build Real time Applications (SignalR)

What is real time ? People who use the applications they need to see the actions one it happens . No delays or refreshing even it is desktop application, App , web or some other application.

How its possible ?

There is few options that developer can looking at.
1. Running background thread
2. Use SignalR

1st option that I describe here is not the best option in most of the times. Running background thread all times is resource consuming and it always use pulling (grab the data from the remote). And there is security concerns as well. But believe me there is some applications which we need to use this and thread is worth than other .


Most pf the time best option is SignalR

What is SignalR ?
 SignalR is series of abstractions around various methods of providing persistent Http Connections. Simply it makes real time communication without effort 

 Where ?
SignalR can be in
  1. Web application
  2. Desktop Applicaton 
  3. App (windows /iOs/Android/berry ) 

 It is cross platform tool  (totally open source) which capable of running with any platform.


SignalR is Client Server

To use SignalR you need to have Server (basically you can create serever with asp.net i'll add posts future)

And client application, (if you use javascript no need to have client nuget to consume SignalR) you can make any application by just adding SignalR nugets to your project.

Microsoft Asp.Net SignalR 









Modern servers from Windows Server 2012 is support SignalR (Real time Communication perfectly )

There is life beyond  Web Sockets


Lets meet with handons later :) enjoy

SignalR Coading 

Monday, September 15, 2014

Work with Async

Asynchronous Programming

If you are working with applications such as windows store and Windows Phone applications you may be found lot of functions that with Async keyword. Why Async?
We need async because when working with applications that interact with network (web, local network) , database, Files and reading hardware in the device are much more slower than the usual execution. Because of it communication bottlenecks are occur.

To avoid those communication bottlenecks async is born.

What Async Does ?

Async allows to run those delayed tasks in the background and meanwhile program can do what ever operations that does not depend on the awaited task.
simply,
"With Async Application can continue with other works that doesn’t depend on blocked resource until the blocked task finished"

Asynchronous programming available with .NET framework 4,5 onwards with Visual studio 2012. If you working on visual Studio 2012 without installing any of other libraries you can work on async

Concepts

Task
Task encapsulate all units of works in the async. Task contains following properties

  • State : Running , Finished , Cancelled
  • Result
  • Thrown Exceptions
It will handle each and every exceptions and it throws all exceptions when task is finished.(await finished)


Important

If you really want to implement async methods and use them remember async and await keywords.

async keyword informs the compiler this method need to be handle separately by itself. Await keyword indicate the suspension of relative running async task.

When working with async,
  • Use Async Suffix  | e.g. DownloadAsync
  • Return Task or Task<T> according to situation
  • void for only event handlers  

Example Wpf Code with simple async operation

public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
      private void btnNormal_Click(object sender, RoutedEventArgs e)
      {
          resultTxt.Text = getString("sample");
          independentWork();
      }
      private async void btnAsync_Click(object sender, RoutedEventArgs e)
      {
          resultTxt.Text = await getStringAsync();
      }
      /// <summary>
      /// Method with waiting in synchronize way
      /// ///
      /// </summary>
      /// <returns></returns>
      private string getString(string name)
      {
          //Task.Delay(2000);
          Thread.Sleep(2000);
          return "My String";
      }
      /// <summary>
      /// same method calling from async
      /// </summary>
      /// <returns></returns>
      private async Task<string> getStringAsync()
      {
          Task<string> asyncTask = Task.Factory.StartNew(() => getString("sample"));
          independentWork();
          return await asyncTask;
      }
      
      /// <summary>
      /// this work is independent from others
      /// </summary>
      private void independentWork()
      {
          resultTxt.Text += "\n independent work is done ";
      }
  }





Download Sample Code Here

Saturday, September 13, 2014

Improve Performance of the Application

As and software producer all of us want to do is software product with correct functionality. Is that enough ? No. We need to give product with correct functionality with optimum resource consumption as well.

Today I'm going to tell you some tips and trikes about resource optimization. basically it is about Memory and CPU resources.

1. Switch for multiple If
 When you are using multiple If conditions ( Most of the time more than 2 ) CPU (Registry level) instructions check as far as use much If with code. It consume more registers in CPU. But with switch it just use check and Jump CPU instruction that far more faster than assignments. Using jump tables makes switches much faster than some if-statements

Use switch when ever possible once you find more than two if statements.

2. Use structures according to the situation
Execution of class is much more consume resources than class.  Whenever you don't need to use functions bind with objects and when you don't go with boxing and unboxing much with code.

3. Chunky calls
Don't let your functions to handle lot of task by itself. use modularity to avoid it.

4. Add Collections
Never try to assign collection items one by one to the another collection. Just try to use simple casting and try to add entire collection directly.

5. Working with strings.
When you are working with string most of the cases we try to concatenate string by '+'operator.(including me ). But sad story is there is more optimal solution than that. use string bulider to concatenate strings.

Here for start.

6. Use bits whenever as possible.
I saw most of the programmers use integers/strings to hold the simple states, flags. Please don't do that there is more than 2 states. Just use bit or bool to store states. It will optimize code and resource as well. ( Simply bit is smaller than more bits)

7. Array as possible
When we use simple basic array it will helpful to maintain machine instructions(registry). Other collections need more than array because most of them are derived form it. Array is basic element in modern machine instructions.

8. ObservableCollection vs List
Use List whenever that your items not binded with the UI. Observation collections are derived from List and it also holds the property changed notifications. If there is no use of property change go for List.  ObservableCollection check the property change when it on use and because of that it consume more.

9. For than foreach
Use while, for and do while loops wherever than foreah. foreach has good performance but basic loops are better than it.

10. ToString
Some  programmers use ToString method wherever elements are already strings. Use ToString wherever the element that con the string. don't use ToString as habit. With integers use
ToStringLookup will optimize memory heap that using with converting integer.

11. Don't sort collections already sorted.
Check collection already sorted or not before sort it.

12. Global variables.
Use global variables when you using same type of object frequently

13. Constant and static
Constants are not assignable memories but they are easy to load.

Static is more faster than instant creations. When load statics no need of run time to check the instance



Hope this is helps...



Wednesday, September 10, 2014

Starts with MVVM

With the growth of programming and application development  there are major requrement that emerged the design patterns. Such as MVP(Model View Presentation) and MVC (Model View Controller) are common design patterns that allows developer to isolate codes. Bu the advanced features of XAML such as data biding, data templates, commands and on demand interaction between application and logic's guide world to MVVM (Model View ViewModel)

MVVM basically derived from the MVC design pattern. It clearly  create separation between these MVVM layers more than MVC.














Model contains all abstraction of data  not any logic's behind data. View is contains XAML views still not the logics. Importance is Model and view are not directly inter action with each other.


ViewModel Contains all  business logic's and data bind properties such as Collections. And it will interact with the View and Model. It takes notifications from model and send them to View as well as other way around.

Ex: If new item added to collection in view It automatically notify and update the View without any interaction.

Study Simple MVVM code here










Full Code In Media Fire 
http://bit.ly/MvvMDemo

 






Thursday, July 10, 2014

Multiple inheritance in C#

When we are talking about Object Oriented Programming concepts inheritance is most important concept. C# is that language derived from powerful lanuage C++. But some of the features in C++ such like Multiple inheritance is not allowed with C#.

Instead of multiple inheritance with Classes C# provide multiple inheritance with interfaces. If you have scenario that multiple inheritance need to play role you can go with interfaces with one base class. 

An interface contains only the signatures of methods, properties, events or indexers. A class or Struct that implements the interface must implement the members of the interface that are specified in the interface definition.

You can inherit any number of interfaces but only one base class


public interface demoInterface
   {
       public string interfaceProperty { get; set; }
       public void interfaceMethod();
   }
   public class DemoClass1
   {
       public int demoClassProp1 { get; set; }
   }
   public class DemoMultipleInheritClass:DemoClass1,demoInterface
   {
       private string Property;
       public string interfaceProperty  // read-write instance property
       {
           get
           {
               return Property;
           }
           set
           {
               Property = value;
           }
       }
       public void interfaceMethod()
       {
           int variable1 = this.demoClassProp1;  
       }
   }



Monday, July 7, 2014

Code Optimization with LINQ

What is LINQ ?
Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
(Definition from : msdn)

LINQ With If  Else

//LINQ conditional If
            //if text in textBox1 is a pop up message that found A else pop up not A
            //Usual code
            //if (textBox1.Text.Equals("A"))
            //{
            //    MessageBox.Show("Found 'A'");
            //}
            //else
            //{
            //    MessageBox.Show("Not 'A'");
            //}
            var d = textBox1.Text.Equals("A") ? MessageBox.Show("Found 'A'") :MessageBox.Show("Not 'A'");

With LINQ simple If Else condition is just single line code. isn't it amazing

Getting Elements from User Interface

My interface has four TextBoxes and I need to popup every Textboxe's Text where it strts from 'A' letter.














//Add all items starts with 'A' to List
            var  selectedBoxes = MainGrid.Children.OfType<TextBox>().Where(x=> x.Text.StartsWith("A")).ToList();
            //pop up them
            foreach (var item in selectedBoxes)
            {
                MessageBox.Show(item.Text);
            }


Like this you can traverse any Collection on C# and filter.

And simply Order the elements in Collections with Order By function in LINQ

var  selectedBoxes = MainGrid.Children.OfType<TextBox>().Where(x=> x.Text.StartsWith("A")).OrderBy(x=> x.Text).ToList();

Select
 Just take each of Dealer contract and dealer as two tables in DB

var dealerContracts = DealerContact.Join(Dealer,
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);





Enjoy...