Monday, December 5, 2011

thumbnail

The Model View ViewModel (MVVM)

is an architectural pattern used in software engineering that originated from Microsoft which is specialized in the Presentation Model design pattern. It is based on the Model-view-controller pattern (MVC), and is targeted at modern UI development platforms (WPF and Silverlight) in which there is a UX developer who has different requirements than a more "traditional" developer. MVVM is a way of creating client applications that leverages core features of the WPF platform, allows for simple unit testing of application functionality, and helps developers and designers work together with less technical difficulties.

MODEL: A Model is responsible for exposing data in a way that is easily consumable by WPF. It must implement INotifyPropertyChanged and/or INotifyCollectionChanged as appropriate. 

VIEW: A View is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding.  

VIEWMODEL: A ViewModel is a model for a view in the application or we can say as abstraction of the view. It exposes data relevant to the view and exposes the behaviors for the views, usually with Commands.

Getting Started:
  • Creating a WPF Project. Open Visual Studio 2010.
  • Go to File => New => Project
  • Select Window in installed templates
  • Select WPF Application
  • Enter the Name and choose the location.
  • Click OK
Now create three folders in root application. Name should be Model,View,ViewModel and now add a new class in Model folder. My class name is User and add this namespace using System.ComponentModel;

User.cs
public class User : INotifyPropertyChanged    {
       private int userId;
       private string firstName;
       private string lastName;
       private string city;
       private string state;
       private string country;
       public int UserId
       {
           get           {
               return userId;
           }
           set           {
               userId = value;
               OnPropertyChanged("UserId");
           }
       }
       public string FirstName
       {
           get           {
               return firstName;
           }
           set           {
               firstName = value;
               OnPropertyChanged("FirstName");
           }
       }
       public string LastName
       {
           get           {
               return lastName;
           }
           set           {
               lastName = value;
               OnPropertyChanged("LastName");
           }
       }
       public string City
       {
           get           {
               return city;
           }
           set           {
               city = value;
               OnPropertyChanged("City");
           }
       }
       public string State
       {
           get           {
               return state;
           }
           set           {
               state = value;
               OnPropertyChanged("State");
           }
       }
       public string Country
       {
           get           {
               return country;
           }
           set           {
               country = value;
               OnPropertyChanged("Country");
           }
       }                  
       #region INotifyPropertyChanged Members
       public event PropertyChangedEventHandler PropertyChanged;
       private void OnPropertyChanged(string propertyName)
       {
           if (PropertyChanged != null)
           {
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
           }
       }
       #endregion
    }

Now right click on ViewModel folder and add a new class.

UserViewModel.cs
using System.Windows.Input;using System.ComponentModel;
 
class UserViewModel    {
        private IList<User> _UsersList;
        public UserViewModel()
        {
            _UsersList = new List<User>
            {
                new User{UserId = 1,FirstName="Nasri",LastName="Ali",City="Dubai",State="Dubai",Country="UAE"},
                new User{UserId=2,FirstName="Mark",LastName="henry",City="New York", State="NY", Country="USA"},
                new User{UserId=3,FirstName="Mahesh",LastName="Chand",City="Philadelphia", State="PHL", Country="USA"},
                new User{UserId=4,FirstName="Hassan",LastName="Khan",City="Sharjah", State="Sharjah", Country="UAE"},
         
            };
        }
        public IList<User> Users
        {
            get { return _UsersList; }
            set { _UsersList = value; }
        }
        private ICommand mUpdater;
        public ICommand UpdateCommand
        {
            get            {
                if (mUpdater == null)
                    mUpdater = new Updater();
                return mUpdater;
            }
            set            {
                mUpdater = value;
            }
        }
        private class Updater : ICommand        {            #region ICommand Members
            public bool CanExecute(object parameter)
            {
                return true;
            }
            public event EventHandler CanExecuteChanged;
            public void Execute(object parameter)
            {
            }
            #endregion        }
    }
Now let's move on View, Add a new windows in View Folder.

MainPage.xaml
<Window x:Class="WpfMVVMSample.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="MainWindow" Height="485" Width="525">    <Grid Margin="0,0,0,20">        <Grid.RowDefinitions>            <RowDefinition Height="Auto"/>            <RowDefinition Height="*"/>            <RowDefinition Height="Auto"/>        Grid.RowDefinitions>        <ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13"  ItemsSource="{Binding Users}"  >            <ListView.View>                <GridView x:Name="grdTest">                    <GridViewColumn Header="UserId" DisplayMemberBinding="{Binding UserId}"  Width="50"/>                    <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}"  Width="80" />                    <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" />                    <GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" Width="80" />                    <GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" Width="80" />                    <GridViewColumn Header="Country" DisplayMemberBinding="{Binding Country}" Width="100" />                GridView>            ListView.View>        ListView>        <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" />        <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" />        <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" />        <Label Content="UserId" Grid.Row="1" HorizontalAlignment="Left" Margin="12,12,0,274" Name="label1" />        <Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" />        <Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="label3" VerticalAlignment="Top" />        <Button Content="Update" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate" 
                VerticalAlignment="Top" Width="141"                Command="{Binding Path=UpdateCommad}"  />
        <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,143,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.City, ElementName=UserGrid}" />        <Label Content="Country" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,141,0,0" x:Name="label2_Copy" VerticalAlignment="Top" />        <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Country, ElementName=UserGrid}" />        <Label Content="City" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="label2_Copy1" VerticalAlignment="Top" />        <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" />        <Label Content="State" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="label2_Copy2" VerticalAlignment="Top" />    Grid>
Window>

App.xaml.cs

Bind Application Startup.
protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            WpfMVVMSample.MainWindow window = new MainWindow();
            UserViewModel VM = new UserViewModel();
            window.DataContext = VM;
            window.Show();
        }
Now run the application and see results.

Wednesday, April 20, 2011

thumbnail

Windows Controls in WPF Auto Login Facebook

Xaml

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="TestFacebookLogin" Height="1050" Width="1680">




CS File

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;


namespace Nasrullah.WPF
{
///
/// Interaction logic for TestFacebookLogin.xaml
///

public partial class TestFacebookLogin : Window
{
public TestFacebookLogin()
{
InitializeComponent();

LoginFacebook.Enabled = false;
}



private void LoadFacebook_Click(object sender, EventArgs e)
{
WebBrowser1.Navigate("https://login.facebook.com/login.php?login_attempt=1");
WebBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string s = WebBrowser1.DocumentText;
LoginFacebook.Enabled = true;
}
private void LoginFacebook_Click(object sender, EventArgs e)
{
HtmlElement ele = WebBrowser1.Document.GetElementById("email"); if (ele != null)
ele.InnerText = "nasrullah.mahar@gmail.com";

ele = WebBrowser1.Document.GetElementById("pass"); if (ele != null)
ele.InnerText = "password";

ele = WebBrowser1.Document.GetElementById("Login"); if (ele != null)
ele.InvokeMember("click");
}





}
}

Tuesday, April 12, 2011

thumbnail

Digital Perona Integration with WPF

1. Enrollment

Xaml


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="frmEnrollment" Height="700" Width="1000">







Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;

using Nasrullah.Properties;
using Nasrullaht.Controller;

namespace Reactive.ActivityControl.Register
{
///

/// Interaction logic for frmEnrollment.xaml
///

public partial class frmEnrollment : Window, DPFP.Capture.EventHandler
{


private DPFP.Capture.Capture Capturer;
delegate void Function();

private DPFP.Processing.Enrollment Enroller;
public delegate void OnTemplateEventHandler(DPFP.Template template);
public event OnTemplateEventHandler OnTemplate;

private Int32 customerId;

public frmEnrollment(pCustomer customer)
{
customerId = customer.ID;

InitializeComponent();

Init();

Enroller = new DPFP.Processing.Enrollment(); // Create an enrollment.

Start(); // Start
}

protected virtual void Init()
{
try
{
Capturer = new DPFP.Capture.Capture(); // Create a capture operation.

if (null != Capturer)
Capturer.EventHandler = this; // Subscribe for capturing events.
else
SetPrompt("Can't initiate capture operation!");
}
catch
{
SetPrompt("Can't initiate capture operation!");
}
}

protected void Process(DPFP.Sample Sample)
{
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Enrollment);


// Check quality of the sample and add to enroller if it's good
if (features != null) try
{
SetPrompt("The fingerprint feature set was created.");
Enroller.AddFeatures(features); // Add feature set to template.
}
finally
{

// Check if template has been created.
switch (Enroller.TemplateStatus)
{
case DPFP.Processing.Enrollment.Status.Ready: // report success and stop capturing
// OnTemplate(Enroller.Template);
// Call Login and pass in template.
SetPrompt("Click Close, and then click Fingerprint Verification.");
Stop();

// Set stream for array of bytes
MemoryStream ms = new MemoryStream(Enroller.Template.Bytes);

bool status = false;

pCustomerDetail icustomerdetailobj = new pCustomerDetail();
icustomerdetailobj.CustomerID = customerId;
icustomerdetailobj.FingerTemplate = ms.ToArray(); // save array of bytes in DB

bCustomerDetail bCustomerdetailobj = new bCustomerDetail();
status = bCustomerdetailobj.SaveCustomerDetail(icustomerdetailobj);
if (!status)
MessageBox.Show("Information not saved successfully");
else
{
MessageBox.Show("Information saved successfully");

//Closet the current window
this.Dispatcher.Invoke(new Function(delegate()
{
Stop();
this.Close();

}));
}


break;

case DPFP.Processing.Enrollment.Status.Failed: // report failure and restart capturing
Enroller.Clear();
Stop();
OnTemplate(null);
Start();
break;
}
}
}

protected void Start()
{
if (null != Capturer)
{
try
{
SetPrompt("Using the fingerprint reader, scan your fingerprint.");
Capturer.StartCapture();
}
catch
{
SetPrompt("Can't initiate capture!");
}
}
}

protected void Stop()
{
if (null != Capturer)
{
try
{
Capturer.StopCapture();
}
catch
{
SetPrompt("Can't terminate capture!");
}
}
}

#region EventHandler Members
public void OnComplete(object Capture, string ReaderSerialNumber, DPFP.Sample Sample)
{
SetPrompt("The fingerprint sample was captured.");
Process(Sample);
}

public void OnFingerGone(object Capture, string ReaderSerialNumber)
{
SetPrompt("The finger was removed from the fingerprint reader.");
}

public void OnFingerTouch(object Capture, string ReaderSerialNumber)
{
SetPrompt("The fingerprint reader was touched.");
}

public void OnReaderConnect(object Capture, string ReaderSerialNumber)
{
SetPrompt("The fingerprint reader was connected.");
}

public void OnReaderDisconnect(object Capture, string ReaderSerialNumber)
{
SetPrompt("The fingerprint reader was disconnected.");
}

public void OnSampleQuality(object Capture, string ReaderSerialNumber, DPFP.Capture.CaptureFeedback CaptureFeedback)
{
if (CaptureFeedback == DPFP.Capture.CaptureFeedback.Good)
SetPrompt("The quality of the fingerprint sample is good.");
else
SetPrompt("The quality of the fingerprint sample is poor.");
}
#endregion

protected DPFP.FeatureSet ExtractFeatures(DPFP.Sample Sample, DPFP.Processing.DataPurpose Purpose)
{
DPFP.Processing.FeatureExtraction Extractor = new DPFP.Processing.FeatureExtraction(); // Create a feature extractor
DPFP.Capture.CaptureFeedback feedback = DPFP.Capture.CaptureFeedback.None;
DPFP.FeatureSet features = new DPFP.FeatureSet();
Extractor.CreateFeatureSet(Sample, Purpose, ref feedback, ref features); // TODO: return features as a result?
if (feedback == DPFP.Capture.CaptureFeedback.Good)
return features;
else
return null;
}



private void SetPrompt(string Text)
{
this.Dispatcher.Invoke(new Function(delegate()
{
textBox1.Text = Text;
}));
}


}
}


2. Verification

Xaml

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Verification" Height="700" Width="1000">






About me

simple one.