mydotnetblog.org

Arjun's Blog on .Net

Silverlight 4: Developing with Managed Extensibility Framework (MEF) preview 9, MVVM pattern(Visual Basic)

clock April 9, 2010 01:38 by author Arjun Paudel

What is MVVM, Managed Extensibility Framework (MEF)

1.       Create a Silverlight Application(Version 4). Add web project to it when prompted (call it MySLApplication).

2.       Add a folder called Models in your server project(MySLApplication.Web)

3.       Add an interface called IModel which will be interface for your data Model.

Public Interface IModel

    Function GetData() As List(Of String)

    Sub AddData(ByVal Title As String)

End Interface

4.       Add 2 references to MyApplication.Web, Download MEF Preview 9(link at top) if you have not done already and decompress it, add reference to System.ComponentModel.Composition(which will be in bin\sl\ folder)  

 

5.       Add a class implementing IModel as follow in same Model Folder you can add another class in same file to instantiate MyDataModel


<Export(GetType(IModel))>

Public Class MyDataModel

    Implements IModel

 

    Private ReturnData As New List(Of String)

    Public Sub New()

        'Adding data mnaully but you might get it form your database

        ReturnData.Add("Learn Silverlight")

        ReturnData.Add("MEF in Silverlight")

 

    End Sub

    Public Sub AddData(ByVal Title As String) Implements IModel.AddData

        ReturnData.Add(Title)

    End Sub

 

    Public Function GetData() As List(Of String) Implements IModel.GetData

        Return ReturnData

    End Function

End Class

 

 

Now we have data model ready which is going to be consumed by  a listbox in our silverlight application. We are going to implement Model View View Model pattern to display our data.

6.       So in silverlight client project(MyApplication), Add a folder called ViewModels

7.       Now we are adding a base class for our ViewModels implementing INotifyPropertyChanged. So add a class called ViewModelBase in ViewModels Folder as below

Imports System.ComponentModel

Public Class ViewModelBase

    Implements INotifyPropertyChanged

    Sub New()

        'Anything we want to intialize for all our viewmodels

    End Sub

    Protected Sub OnPropertyChanged(ByVal PropertyName As String)

        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))

    End Sub

 

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As _

System.ComponentModel.PropertyChangedEventArgs) Implements _

System.ComponentModel.INotifyPropertyChanged.PropertyChanged

End Class

 

 

8.  In ViewModels folder lets create a class called MainPageViewModel which we are going to bind to our MainPage

Imports System.ComponentModel.Composition

'probably using constant is better for attribute value

<Export("MainPageViewModel")>

Public Class MainPageViewModel

    Inherits ViewModelBase

    'Name MyModel can be anything, only interface IModel is used to find data

    <Import()>

    Public Property MyModel As IModel

    Sub New()

        CompositionInitializer.SatisfyImports(Me)

        Books = MyModel.GetData()

    End Sub

    Public Property Books As List(Of String)

End Class

9.   

10.   Open MainPage.xaml file and add a list box with binding it to Books

<ListBox Height="100" ItemsSource="{Binding Books}" HorizontalAlignment="Left" Margin="132,98,0,0" Name="ListBox1" VerticalAlignment="Top" Width="120" />

11.   Open MainPage.xaml.cs and modify Sub New as following

Public Sub New()

        InitializeComponent()

        CompositionInitializer.SatisfyImports(Me)

    End Sub

    <Import("MainPageViewModel")>

    Public WriteOnly Property MainPageViewModel As Object

        Set(ByVal value As Object)

            Me.DataContext = value

        End Set

    End Property

 

12.   Build your application and run it, you will be able to see 2 books listed in listbox

 

 

 

In my next blog I will write about how to handle commands in ViewModel and  also about WCF RIA WCF services.

 Download source application below.

MySLApplication.zip (1.02 mb)

 



Single Instance Application in Visual Basic without using Application Framework

clock February 13, 2010 18:31 by author Arjun Paudel

A simple method using semaphore class(creating object to satisfy one request) in Application Startup's event(Go to Project Properties, Application Tab, View Application Events). 


Partial Friend Class MyApplication
        Dim AmINew As Boolean
        Dim sp As New System.Threading.Semaphore(0, 1, "MyUniqueApplicationName", AmINew)
        Private Sub CheckingPrevInstance(ByVal s As Object, ByVal e As ApplicationServices.StartupEventArgs) Handles Me.Startup
            If AmINew Then
                MessageBox.Show("Yes")
            Else
                MessageBox.Show("I cannot co-exist ")
                e.Cancel = True
            End If
        End Sub
    End Class



VB 2010: Collection Initializer for Stack and Queue

clock November 1, 2009 20:06 by author Arjun Paudel

VB 2010 has provided a great way of intilizing collections, thats helps our code to be more redable, compact etc.

 

 

Dim users As New List(Of String) From {"Jack", "Ferdinand"}

 

 

But if I type
Dim BillPayers As New Queue(Of String) From {"George", "Anthony"}
I get an instant error
System.Collections.Generic.Queue(Of String)' with a collection initializer because it does not have an accessible 'Add' method.
Wow! Thats helpful, it says we cannot use collecion intializer since Queue does not have an Add method. Now here comes extension method to rescue

 

Module

Extensions
    <Extension()> Sub Add(Of t)(ByVal InitializableQ As Queue(Of t), ByVal ToAddValue  As t)
      InitializableQ.Enqueue(ToAddValue)
      End Sub
End
Module

 

 

Voila, You are done!!

Keep testing...........



How to bind Data to User Control using Visual Basic .Net

clock October 26, 2009 20:04 by author Arjun Paudel

Following example shows an usercontrol whose property, PropertyValue is bindable. This value is shown in usercontrol using a TextBox(tbPropertyValue). To use this control create a user control in your project, copy/paste the following code, build your application, drop the usercontrol from toolbox to your application, use databindings property to assign binding field to PropertyValue.

Imports System.ComponentModel
Friend Class BindableControl
    Public Event ValueChanged As PropertyChangedEventHandler

    <System.ComponentModel.Bindable(True, BindingDirection.TwoWay)> _
    Public Property PropertyValue() As String
        Get
            Return tbPropertyValue.Text
        End Get
        Set(ByVal value As String)
            Dim ppe As PropertyChangedEventArgs = New PropertyChangedEventArgs("PropertyValue")
            OnValueChanged(ppe)
            tbPropertyValue.Text = value
        End Set
    End Property

    Public Sub OnValueChanged(ByVal e As System.ComponentModel.PropertyChangedEventArgs)
        RaiseEvent ValueChanged(Me, e)
    End Sub
    Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbPropertyValue.TextChanged
        PropertyValue = tbPropertyValue.Text
    End Sub
End Class



Get a list of Installed Programs using WMI Query and Uninstall

clock October 13, 2009 19:57 by author Arjun Paudel

Following code shows how to get a list of programs into listview using wmi query. Drop 2 buttons and a listview into a Windows Form and test it


Public Class Form1

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

  ListView1.View = View.Details
  ListView1.Columns.AddRange(New ColumnHeader() {New ColumnHeader() With {.Text = "Caption", .Width = 150}, _
  New ColumnHeader() With {.Text = "Vendor", .Width = 150}, _
  New ColumnHeader() With {.Text = "Version", .Width = 200}})

 End Sub

 Private Sub btnGetProgram_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetProgram.Click

  Dim searcher As New ManagementObjectSearcher("root\cimv2", "SELECT * FROM Win32_Product")
  For Each queryObj As ManagementObject In searcher.Get()
   Dim li As ListViewItem = ListView1.Items.Add(queryObj.Item("Caption").ToString)
   li.SubItems.Add(queryObj.Item("Vendor").ToString)
   li.SubItems.Add(queryObj.Item("Version").ToString)
  Next
 End Sub

 Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
  Dim searcher As New ManagementObjectSearcher("root\cimv2", String.Format("SELECT * FROM Win32_Product where caption='{0}' and Version ='{1}'", ListView1.SelectedItems(0).Text, ListView1.SelectedItems(0).SubItems(2).Text))

  For Each queryObj As ManagementObject In searcher.Get()

   queryObj.InvokeMethod("Uninstall", Nothing)
  Next
 End Sub


End Class

 

 



Edit SubItems in ListView Control

clock July 22, 2009 19:54 by author Arjun Paudel

This is just a simple example of how to edit Sub Items in ListView. If you need such things frequently then just create an user control inheriting ListView and incorporate the idea, you can read column names dynamically and create context menu as shown in the example, you can find source project at the bottom of this post, please download it. I am providing 2 methods

1. Using ContextMenu

   Private WithEvents EditBox As New TextBox

    Private WithEvents EditMenu As New ContextMenu

    Private SelectedItem As ListViewItem

    Private EditingcolumnIndex As Integer = 0

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        For i As Integer = 1 To ListView1.Columns.Count - 1

            Dim EditCoulmn1 As New MenuItem(String.Format("Edit {0}", ListView1.Columns(i).Text), AddressOf EditMenu_click)

            EditMenu.MenuItems.Add(EditCoulmn1)

        Next

    End Sub

 

    Private Sub EditMenu_click(ByVal S As Object, ByVal e As EventArgs)

        Dim clickedmenu As MenuItem = CType(S, MenuItem)

        EditingcolumnIndex = (From c As ColumnHeader In ListView1.Columns Where c.Text = clickedmenu.Text.Replace("Edit ", String.Empty) Select c).First.Index

        EditBox.Bounds = SelectedItem.SubItems(EditingcolumnIndex).Bounds

        EditBox.Text = SelectedItem.SubItems(EditingcolumnIndex).Text

        EditBox.Visible = True

        EditBox.Select()

    End Sub

    Private Sub Editbox_Leave() Handles EditBox.Leave

        SetValues()

    End Sub

    Private Sub EditBox_KeyUp(ByVal s As Object, ByVal e As KeyEventArgs) Handles EditBox.KeyUp

        If e.KeyCode = Keys.Enter Then

            SetValues()

        ElseIf e.KeyCode = Keys.Escape Then

            EditBox.Visible = False

        End If

    End Sub

    Private Sub SetValues()

        SelectedItem.SubItems(EditingcolumnIndex).Text = EditBox.Text

        EditBox.Visible = False

    End Sub

    Private Sub ListView1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseClick

        Dim item = ListView1.GetItemAt(e.X, e.Y)

        If item IsNot Nothing Then

            If e.Button = Windows.Forms.MouseButtons.Right Then

                SelectedItem = item

                EditMenu.Show(ListView1, e.Location)

            End If

        End If

        EditBox.Visible = False

        ListView1.Controls.Add(EditBox)

    End Sub

2. HitTest Method

Public Class Form1

    Private WithEvents EditBox As New TextBox

    Private SelectedItem As ListViewItem.ListViewSubItem

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        EditBox.Visible = False

        ListView1.Controls.Add(EditBox)

        ListView1.FullRowSelect = True

    End Sub

Private Sub Editbox_Leave() Handles EditBox.Leave

        SetValues()

    End Sub

    Private Sub EditBox_KeyUp(ByVal s As Object, ByVal e As KeyEventArgs) Handles EditBox.KeyUp

        If e.KeyCode = Keys.Enter Then

            SetValues()

        ElseIf e.KeyCode = Keys.Escape Then

            EditBox.Visible = False

        End If

    End Sub

    Private Sub SetValues()

        SelectedItem.Text = EditBox.Text

        EditBox.Visible = False

    End Sub

    Private Sub ListView1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseClick

        Dim info As ListViewHitTestInfo = ListView1.HitTest(e.X, e.Y)

        If info.Item IsNot Nothing AndAlso info.SubItem.Bounds.X > 10 Then

 

            EditBox.Bounds = info.SubItem.Bounds

            EditBox.Text = info.SubItem.Text

            SelectedItem = info.SubItem

            EditBox.Visible = True

            EditBox.Select()

 

 

        End If

    End Sub

End Class

 

 

 

EditSubItemHitTest.zip (118.95 kb)

 

EditSubItem.zip (121.08 kb)



Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Sign In