Thursday, October 8, 2009

WPF : Changing Listview Selected Item color

Hi All,

I am really loving WPF these days, all of the things which looked really tough to me earlier, are not simplified using WPF XAML.

Here is the code for changing the background color of the selected item in a listview :
Code :



< Style TargetType="ListViewItem">
< Style.Resources>
< SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="WhiteSmoke"/>
< SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent"/>




Thanks,
Vikas

Saturday, August 29, 2009

Binding Checkbox with the Listview Item Selection

Hi All,

I know, lot of people juggle around for this. I also did ;)

Have you ever wondered to have a checkbox in a listview item which should be checked/unchecked as per the listviewitem selection and vice versa?

Suppose if you have a checkbox as a listview item, and you want to check/uncheck the checkbox as soon as user selects the listview item. And vice versa, the listview item should be selected as soon as user selects the checkbox. The following line solves this purpose :



HTH,
Vikas Bhandari

Formatting the GridView Column Header in Listview

Hi All,

Please find below the code to set the background color of a GridviewColumnHeader inside a Listview. I will add more to it ;)



Code to set the font size of a GridviewColumnHeader :



Thanks,
Vikas

Monday, August 10, 2009

WPF : Styling a Combobox, Button and Tabcontrol

Hi All,

I am still very much like a novice in my WPF skills. Still, I thought to share something useful with the world. I was looking to create a good looking Combobox style for my project. And (obviously after too much efforts), I created one. I know, it is simple but sometimes a novice like me tries to find an already build style so I thought I will post it here :

I created something like this :



You can download the complete project from here : Click here to download.

Please let me know if you have any questions or suggestions.

Thanks,
Vikas

Tuesday, June 30, 2009

WPF : Hide Headers from a GridviewColumn

Hi,

I know, this is simple but I wasted a bunch of my valuable time in finding a solution while developing my first application in WPF. Include the following line in your < listview> block to get rid of headers in your gridview column.

< ListView.Resources>
< Style x:Key="CustomHeaderStyle" TargetType="{x:Type GridViewColumnHeader}">
< Setter Property="Visibility" Value="Collapsed" />
< /Style>
< /ListView.Resources>

Thanks,
Vikas

Friday, June 26, 2009

Reading Image Metadata Tags with Dot Net

Hi All,

I had to find a way to tag images and then use the tagged images to be searched with the help of tagged keywords. Example, if some images are tagged with the keywords "xxx", then searching for xxx should produce the image with xxx tag in the search results.

I tried with various document management software and all of these are actually very handy tools but they don't add metadata tags to images. Since we are spread all over the word, I thought it will be very often that the images will flow from one corner to other and the tags should flow along with the images. So the document management software approach ended with no benefit. Then I thought to develop a sample on my own.

There was one more reason for developing it. I wanted to search the images and provide a custom task ( eg, Inserting the image in powerpoint) which no software gives.

I download a free tagging software called ITag (Click here for Download). And tag all of images with various keywords using this software. It is really a good tool to add metadata tags.

Now when I added the tags, the following xml was added in the image (you can easily read the tags by editing the image files.)

< rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmpMM:InstanceID="uuid:02ab02d9-02d1-11da-9510-ec7226ba1889" xmpMM:DocumentID="adobe:docid:photoshop:02ab02d2-02d1-11da-9510-ec7226ba1889" tiff:ResolutionUnit="2" tiff:YResolution="72/1" tiff:XResolution="72/1" tiff:Orientation="1" tiff:NativeDigest="256,257,258,259,262,274,277,284,530,531,282,283,296,301,318,319,529,532,306,270,271,272,305,315,33432;F68680A2E9A53199A34ACB3FE0102FCA" xmp:ModifyDate="2005-08-01T17:16:48+05:30" xmp:CreatorTool="Adobe Photoshop 7.0" exif:PixelYDimension="227" exif:PixelXDimension="892" exif:ColorSpace="65535" exif:NativeDigest="36864,40960,40961,37121,37122,40962,40963,37510,40964,36867,36868,33434,33437,34850,34852,34855,34856,37377,37378,37379,37380,37381,37382,37383,37384,37385,37386,37396,41483,41484,41486,41487,41488,41492,41493,41495,41728,41729,41730,41985,41986,41987,41988,41989,41990,41991,41992,41993,41994,41995,41996,42016,0,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,23,24,25,26,27,28,30;1064FAD10D9AAF6E380C481B30061C1D">

< dc:subject>< rdf:Bag xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">< rdf:li>Banking< /rdf:li>< rdf:li>Blinx< /rdf:li>< rdf:li>Burton< /rdf:li>< rdf:li>Wake up< /rdf:li>< /rdf:Bag>

< /dc:subject>< /rdf:Description>


Now the above XML suggests that the image is tagged with 4 tags (Wake up,Blinx,Banking,Burton).

After tagging, I run an indexing code and create a list of files with the tags. The produced output was like following :


< ?xml version="1.0" encoding="UTF-8"?>

< Files>

< File Name="imageName3.png">

< Keyword>Banking< /Keyword>
< Keyword>Sports< /Keyword>

< /File>

< File Name="imageName2.png">

< Keyword>Banking< /Keyword>
< Keyword>AssetManagement< /Keyword>
< Keyword>Sports< /Keyword>

< /File>

< File Name="imageName1.png">

< Keyword>Banking< /Keyword>
< Keyword>AssetManagement< /Keyword>
< Keyword>Sports< /Keyword>

< /File>
< /Files>


Now whenever user will enter a keyword in my search panel, I will just load the items from XML in the Panel and will display the images in a different thread.

HTH,
Vikas Bhandari

Wednesday, June 24, 2009

Use WPF User control to display in a Task Pane

Hi,

Use the following code in your Ribbon OnAction method to display a WPF User control in an office task pane:


Dim pane As WPFUserControlName= Nothing

If pane Is Nothing Then
Dim uControl As New UserControl()
Dim host As ElementHost = New ElementHost()

pane = New WPFUserControlName()

host.Child = pane
host.Dock = DockStyle.Left
host.Width = 200

uControl.Controls.Add(host)

taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(uControl, "Biographies")
taskPane.Visible = True
Else
taskPane.Visible = True
End If

Tuesday, June 23, 2009

Dot Net Color Codes

Hi All,

Please findbelow the dot net color codes. Source :Click here to go to Source Site


AliceBlueHex Code:#F0F8FF
AntiqueWhiteHex Code:#FAEBD7
AquaHex Code: #00FFFF
AquamarineHex Code: #7FFFD4
AzureHex Code: #F0FFFF
BeigeHex Code: #F5F5DC
BisqueHex Code: #FFE4C4
BlackHex Code: #000000
BlanchedAlmondHex Code: #FFEBCD
BlueHex Code: #0000FF
BlueVioletHex Code: #8A2BE2
BrownHex Code: #A52A2A
BurlyWoodHex Code: #DEB887
CadetBlueHex Code: #5F9EA0
ChartreuseHex Code: #7FFF00
ChocolateHex Code: #D2691E
CoralHex Code: #FF7F50
CornflowerBlueHex Code: #6495ED
CornsilkHex Code: #FFF8DC
CrimsonHex Code: #DC143C
CyanHex Code: #00FFFF
DarkBlueHex Code:#00008B
DarkCyanHex Code: #008B8B
DarkGoldenrodHex Code: #B8860B
DarkGrayHex Code: #A9A9A9
DarkGreenHex Code: #006400
DarkKhakiHex Code: #BDB76B
DarkMagentaHex Code: #8B008B
DarkOliveGreenHex Code: #556B2F
DarkOrangeHex Code: #FF8C00
DarkOrchidHex Code: #9932CC
DarkRedHex Code: #8B0000
DarkSalmonHex Code: #E9967A
DarkSeaGreenHex Code: #8FBC8B
DarkSlateBlueHex Code: #483D8B
DarkSlateGrayHex Code: #2F4F4F
DarkTurquoiseHex Code: #00CED1
DarkVioletHex Code: #9400D3
DeepPinkHex Code: #FF1493
DeepSkyBlueHex Code: #00BFFF
DimGrayHex Code: #696969
DodgerBlueHex Code: #1E90FF
FirebrickHex Code: #B22222
FloralWhiteHex Code: #FFFAF0
ForestGreenHex Code: #228B22
FuchsiaHex Code: #FF00FF
GainsboroHex Code: #DCDCDC
GhostWhiteHex Code: #F8F8FF
GoldHex Code: #FFD700
GoldenrodHex Code: #DAA520
GrayHex Code: #808080
GreenHex Code: #008000
GreenYellowHex Code: #ADFF2F
HoneydewHex Code: #F0FFF0
HotPinkHex Code: #FF69B4
IndianRedHex Code: #CD5C5C
IndigoHex Code: #4B0082
IvoryHex Code: #FFFFF0
KhakiHex Code: #F0E68C
LavenderHex Code: #E6E6FA
LavenderBlushHex Code: #FFF0F5
LawnGreenHex Code: #7CFC00
LemonChiffonHex Code: #FFFACD
LightBlueHex Code: #ADD8E6
LightCoralHex Code: #F08080
LightCyanHex Code: #E0FFFF
LightGoldenrodYellowHex Code: #FAFAD2
LightGrayHex Code: #D3D3D3
LightGreenHex Code: #90EE90
LightPinkHex Code: #FFB6C1
LightSalmonHex Code: #FFA07A
LightSeaGreenHex Code: #20B2AA
LightSkyBlueHex Code: #87CEFA
LightSlateGrayHex Code: #778899
LightSteelBlueHex Code: #B0C4DE
LightYellowHex Code: #FFFFE0
LimeHex Code: #00FF00
LimeGreenHex Code: #32CD32
LinenHex Code:#FAF0E6
MagentaHex Code: #FF00FF
MaroonHex Code: #800000
MediumAquamarineHex Code: #66CDAA
MediumBlueHex Code: #0000CD
MediumOrchidHex Code: #BA55D3
MediumPurpleHex Code: #9370DB
MediumSeaGreenHex Code: #3CB371
MediumSlateBlueHex Code: #7B68EE
MediumSpringGreenHex Code: #00FA9A
MediumTurquoiseHex Code: #48D1CC
MediumVioletRedHex Code: #C71585
MidnightBlueHex Code: #191970
MintCreamHex Code: #F5FFFA
MistyRoseHex Code: #FFE4E1
MoccasinHex Code: #FFE4B5
NavajoWhiteHex Code: #FFDEAD
NavyHex Code: #000080
OldLaceHex Code: #FDF5E6
OliveHex Code: #808000
OliveDrabHex Code: #6B8E23
OrangeHex Code:#FFA500
OrangeRedHex Code: #FF4500
OrchidHex Code: #DA70D6
PaleGoldenrodHex Code: #EEE8AA
PaleGreenHex Code: #98FB98
PaleTurquoiseHex Code: #AFEEEE
PaleVioletRedHex Code: #DB7093
PapayaWhipHex Code: #FFEFD5
PeachPuffHex Code: #FFDAB9
PeruHex Code: #CD853F
PinkHex Code: #FFC0CB
PlumHex Code: #DDA0DD
PowderBlueHex Code: #B0E0E6
PurpleHex Code: #800080
RedHex Code: #FF0000
RosyBrownHex Code: #BC8F8F
RoyalBlueHex Code: #4169E1
SaddleBrownHex Code: #8B4513
SalmonHex Code:#FA8072
SandyBrownHex Code: #F4A460
SeaGreenHex Code: #2E8B57
SeaShellHex Code: #FFF5EE
SiennaHex Code: #A0522D
SilverHex Code: #C0C0C0
SkyBlueHex Code: #87CEEB
SlateBlueHex Code: #6A5ACD
SlateGrayHex Code: #708090
SnowHex Code:#FFFAFA
SpringGreenHex Code: #00FF7F
SteelBlueHex Code: #4682B4
TanHex Code: #D2B48C
TealHex Code: #008080
ThistleHex Code: #D8BFD8
TomatoHex Code: #FF6347
TransparentHex Code:#FFFFFF
TurquoiseHex Code: #40E0D0
VioletHex Code: #EE82EE
WheatHex Code: #F5DEB3
WhiteHex Code: #FFFFFF
WhiteSmokeHex Code:#F5F5F5
YellowHex Code: #FFFF00
YellowGreenHex Code: #9ACD32


Thanks,
Vikas Bhandari

Friday, May 22, 2009

WPF Calendar Control

Hi All,

By default, the WPF doesn't have the calendar control. And the toolkit release, it seemeed a little way techy for me. I wanted a simple calendar control and I really couldn't work out how I can use only a single control in my project. I thought, it would be easier for me to create a control of my own. hehe, well said by some one :


"Less Knowledge, less confusion, and No knowledge, no confusion. "


Haha...So I designed something like following image:



I have used Listview to display the dates and the items, like "Sun", "Mon" and the days are nothing but listview items. As soon as user changes the year or month, the method to reload the dates is fired. Very simple approach and very very basic functionality I have tried to put into. So if you want to download the project, then please click Here

Thanks,
Vikas

Tuesday, May 19, 2009

Want to Apply a style to Listview/Combobox Groups? Here is the code:

Hi all,

Have you ever grouped Item in a Combobox? Suppose if I have a list of names, and I want to publish the names grouped with the Initial letters. For example, All names with starting letter as "A" will fall under Group "A" and so on. Like given in the following screenshot :





This is simple. Please download the code from Here

Or check the code which is given below(in images) :

Add the following code to Xaml Window





Friday, May 15, 2009

Using Linq for Filtering File Types etc

Hi,

If you have a List of Type IO.File and you want to filter this list to contain only valid images. Then follow the following approach:

Define your array of Valid extensions :

Private IMAGES() As String = {".JPG", ".PNG", ".GIF", ".JPEG"}

The following function returns a list with Valid Images extensions as mentioned in the above array :

Public Function GetValidImage(ByVal files As List(Of File)) As List(Of File)
Dim tmpList As List(Of File) = New List(Of File)
Dim result = From s In files Group Join p In IMAGES On s.Extension.ToUpper() Equals p.ToUpper() Into Group From p In Group Select s


For Each file As File In result
tmpList.Add(file)
Next file

Return tmpList

End Function

Let me know if you have any other questions.

HTH,
Vikas

Thursday, May 14, 2009

Office 2007 SP2 Release

Hi All,

Though the release has been done almost a month ago...I missed to include it here in my blog.

They(Microsoft) have fixed a bunch of bugs found in SP1...and I am sure, 2007 is going to be stable very very soon. This is the reason that most of big organisations, who work on Office rigorously, for example Investment banks like GS or Morgan stanley, they have been shifting their documents to 2007 versions. The office 2007 is certainly going to be much much more popular than it is right now. Lots of cool features. I love themes by the way.

So lets get back to SP2. Microsoft found so many bugs in the previous versions, which forced them to issue a very heavy service pack because the number of bugs they have fixed is huge. Around 600 they have posted here in the link :

Microsoft Office 2007 SP2 Bug Fixes.

For me, the best thing is the chart object for PowerPoint and Word is unlocked. Now you can format/edit the chart source data etc from PowerPoint only. Earlier, before SP2, for formatting a chart programmatically, one had to take the chart to excel and paste it back to PowerPoint. A big pain for me. Using OpenXML was also a big big Pain.

So now, if you have to delete a Series, you can just create the chart object and then add/delete a series. Bingo :)

I love SP2, and I am sure, it will definitely help the Office developers like me, who have to work hard with Charts in PP/Word.

HTH :)

Thanks,
Vikas

Automatic Updating chart

Hi All,

I was reading a forum : Powerpoint Forum where I found a query. And since I have not tried working rigorously with Charts, I thought it will be a worth trying. A guy in the forum asked a question see the question here :

Click me for the Question

Basically he wants to something like following :

He has a Chart in a PowerPoint Slide, and the series will be added/ removed through click of checkbox buttons as given in the following image







And if user unchecks a checkbox, then the series will be removed from the Chart. For example, if I uncheck the 2nd checkbox, the output will be like following:



The 2nd option is deleted.

I did it...though through a tweak, but yes I did it. I am sure that someone may have a better solution and if someone has then please do forward me @ vikasbhandari2@gmail.com

Would like to add again, that since I don't access a file hosting site so I am adding the code here only. Send me a mail if you want a copy of it. :P

Private Sub CheckBox1_Click()
UpdateChart

End Sub

Private Sub CheckBox2_Click()
UpdateChart
End Sub

Private Sub CheckBox3_Click()
UpdateChart
End Sub

Private Sub CheckBox4_Click()
UpdateChart
End Sub

Private Sub CheckBox5_Click()
UpdateChart
End Sub


Sub UpdateChart()
Dim chrt As Chart
Dim chrtShape As Shape
Dim seriesList As seriesCollection
Dim iSeries As Series
Dim chrtWorkbook As Excel.Workbook
Dim seriesSelected(5) As Boolean
Dim wrkbook As Object

seriesSelected(1) = CheckBox1.Value
seriesSelected(2) = CheckBox2.Value
seriesSelected(3) = CheckBox3.Value
seriesSelected(4) = CheckBox4.Value
seriesSelected(5) = CheckBox5.Value



If seriesSelected(1) = False And seriesSelected(2) = False And _
seriesSelected(2) = False And seriesSelected(2) = False And _
seriesSelected(2) = False Then

MsgBox "No checkbox checked. Exiting sub"
Exit Sub
End If


On Error Resume Next
Set chrtShape = ActivePresentation.Slides(1).Shapes("Chart 3")
Set chrt = chrtShape.Chart
chrt.ChartData.Activate
Err.Clear


Dim xValue As String
Dim rowCounter As Integer
Dim addedOnce As Boolean
Dim frstTime As Boolean
Dim brCounter As Integer
Dim prefixY As String
frstTime = True
addedOnce = False

rowCounter = 1
xValue = "$A$1:$A$6"
brCounter = 0
rowCounter = 1
On Error GoTo 0
Set iSeries = chrt.seriesCollection(1)

For i = 1 To 5
rowCounter = rowCounter + 1

If seriesSelected(i) = False Then
brCounter = rowCounter
If addedOnce Then
If frstTime Then
prefixX = xValue
xValue = ""
frstTime = False
Else
prefixX = prefixX & "," & xValue
xValue = ""
End If
Else

End If
Else
addedOnce = True
xValue = "Sheet1!$A$" & brCounter + 1 & ":$B$" & rowCounter
End If

Next i

Dim allRemoved As Boolean

allRemoved = False

While Not allRemoved
If InStr(1, prefixX, ",,") > 0 Then
prefixX = Replace(prefixX, ",,", ",")
Else
allRemoved = True
End If
Wend

prefixX = prefixX & "," & xValue
xValue = Replace(prefixX, ",,", ",")


If Right(xValue, 1) = "," Then
xValue = Mid(xValue, 1, Len(xValue) - 1)
End If

If Left(xValue, 1) = "," Then
xValue = Mid(xValue, 2, Len(xValue) - 1)
End If

chrt.SetSourceData xValue
chrt.ChartData.Workbook.Close
Err.Clear
End Sub


HTH.

Thanks,
Vikas

Tuesday, May 5, 2009

Auto Complete Textbox for Vb.Net Desktop Applications

Hi all,

Ever tried the google toolbar? Whenever you type something, the results are displayed related to the type text just below the textbox. Have you ever wondered if you can include the same thing in your project.


Edited on < 10 AM EST, 19th May 2009: >
Click here for the complete project


I tried to achieve the following :

If I enter a file name, then all the file names which has the text entered by me should appear in a pop up just below my textbox. If somebody cannot access the code at the codeplex, or if somebody cannot download, I have added the code right here :

I applied the following trick :

I loaded few paths to a collection. Created a textbox, and a combobox just behind the textbox so that it should not be visible, but its drop down should be. If I enter some name, and if the text is present in the combobbox items, then the combobox dropdown should display all the items which has that text. Ofcourse, the items should be grouped accordingly.

First step, add a class "AutoCompleteEntry". This will be the class which will be bound to the collection as Combobox Items.





Imports System.IO

Public Class AutoCompleteEntry
Public type As String

Public information As FileInfo

Public Sub New(ByVal type As String, ByVal fileInformation As FileInfo)
Me.type = type
information = fileInformation
End Sub

Public Property FileType() As String
Get
Return type
End Get
Set(ByVal value As String)
type = value
End Set
End Property

Public Property FileInformation() As FileInfo
Get
Return information
End Get
Set(ByVal value As FileInfo)
information = value
End Set
End Property

Public ReadOnly Property ParentFolder() As String
Get
Return information.Name
End Get
End Property

Public ReadOnly Property Name() As String
Get
Return information.Name
End Get
End Property

Public ReadOnly Property Size() As String
Get
Return information.Length & " bytes"
End Get
End Property

End Class



2nd Step, create a Xaml File with the Name of SearchControl.Xaml and add the following code there.



< UserControl x:Class="SearchControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
< UserControl.Resources>
< DataTemplate x:Key="cmbTemplate">
< StackPanel Orientation="Horizontal" Width="250">
< TextBlock Text="{Binding Path=Name}" Width="100" />
< TextBlock Text="{Binding Path=ParentFolder}" Width="70" HorizontalAlignment="Left" Margin="5,0,0,0"/>
< TextBlock Text="{Binding Path=Size}" Width="80" HorizontalAlignment="Left" Margin="5,0,0,0"/>
< /StackPanel>
< /DataTemplate>

< /UserControl.Resources>
< Grid>

< ComboBox Margin="2,28,0,0" Name="cmbAutoComplete"
ItemsSource="{Binding}" ItemTemplate="{StaticResource cmbTemplate}" MaxDropDownHeight="200" Height="24" VerticalAlignment="Top">
< ComboBox.GroupStyle>
< GroupStyle>
< GroupStyle.HeaderTemplate>
< DataTemplate>
< StackPanel>
< Border BorderThickness="1" BorderBrush="Black">
< TextBlock Text="{Binding Items[0].FileType}" Background="AliceBlue"/>
< /Border>
< /StackPanel>
< /DataTemplate>
< /GroupStyle.HeaderTemplate>

< /GroupStyle>
< /ComboBox.GroupStyle>
< /ComboBox>
< TextBox Margin="2,28,0,0" Name="TextBox1" TextChanged="TextBox1_TextChanged" Height="24" VerticalAlignment="Top" />
< Label Margin="22,2,0,0" Name="Label1" Height="23" VerticalAlignment="Top" FontWeight="Bold" Foreground="DarkBlue" HorizontalAlignment="Left" Width="119">Enter Text Criteria< /Label>
< /Grid>
< /UserControl>




3rd Step, copy the following code and paste in the SearchControl.Xaml file.


Imports System.Collections.ObjectModel
Imports System.ComponentModel

''' < summary >
''' This class takes the path of the file which user can search and sees how big file it is.
''' < /summary >
''' < remarks>< /remarks>

Partial Public Class SearchControl

Private _threshold As Integer = 2

Private path As String = "C:\Vikas-Data\" ' set the path here which you want to search

Private items As ObservableCollection(Of AutoCompleteEntry)
Private view As IcollectionView

Public Sub New()

' This call is required by the Windows Form Designer.
InitializeComponent()

' Add any initialization after the InitializeComponent() call.


items = New ObservableCollection(Of AutoCompleteEntry)

LoadPaths(New IO.DirectoryInfo(path))

view = CollectionViewSource.GetDefaultView(items)
view.GroupDescriptions.Add(New PropertyGroupDescription("FileType"))

cmbAutoComplete.DataContext = items

End Sub

Private Sub LoadPaths(ByVal dInfo As IO.DirectoryInfo)
Dim info As IO.DirectoryInfo

For Each info In dInfo.GetDirectories()
LoadPaths(info)
Next info


For Each fInfo As IO.FileInfo In dInfo.GetFiles()
items.Add(New AutoCompleteEntry(dInfo.FullName, fInfo))
Next fInfo

End Sub

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
Dim text As String


text = TextBox1.Text

If (text.Length < _threshold) Then

Else
view.Filter = New Predicate(Of Object)(AddressOf MyPredicate)

If (cmbAutoComplete.HasItems) Then
cmbAutoComplete.IsDropDownOpen = True
End If
End If
End Sub

Private Function MyPredicate(ByVal item As Object) As Boolean
Dim text As String
Dim itemEntry As AutoCompleteEntry

text = TextBox1.Text
itemEntry = TryCast(item, AutoCompleteEntry)

If (itemEntry.Name.IndexOf(text) > -1) Then
Return True
End If

Return False

End Function

End Class



The output is like following screenshot :



I entered "VB" and I had various file names in the collection which contain vb so it displayed file names grouped by the folder names.

Hope this article will help you!

Thanks,
Vikas

Friday, April 24, 2009

Use WPF Themes and styles


WPF, the future of Window Forms and Programming, has some fantastic flexibility to create excellent styles and apply with an immense ease. Here is an example, we can apply the themes to our WPF UIs, and the theme will take care of styles of the components used in the window. See the following link:

WPF Themes Home. Samantha is great :)

Hope this helps!

Thanks,
Vikas

Monday, April 6, 2009

Ghost Instance Problem in office application

Hi All,

A number of office programmers face the Ghost Instance issue while developing office applications. The ghost instance is an instance of office application which is not closed properly. In this scenario, you will be able to see the application entry in the Porcess list of task manager but it will not be visible for the user. I will explain the context by using an example of powerpoint Addin(Obviously in dot net).

Q. How does it occur?

Ans. I create a PowerPoint(aka, PP)Addin, and in that PP Addin I try to create an excel(aka, XL) Application object. Now if I do extensive programming using XL objects(like Range, Shapes, Worksheet etc), these InterOP variables stay in Memory and not handled by the CLR. You will need to explicitly release every COM Object by using System.Runtime.InteropServices.Marshal.ReleaseCOMObject(theObjectToBeReleased) method. But, even after releasing the objects few of the instances keep on running in memory. So if the variables are running in the memory, and I try to close the excel, the excel gets closed but its process keeps on running in the task Manager List. When we hit close button(the cross button in TopLeftHand corner) in Excel, the CLR first closes all the AddIns opened, and then closes the excel window. If there is any COM running in the memory the AddIns get removed but the CLR is unable to close the Excel properly. The result is Ghost Instance. In case of Ghost Instance running in the task manager, if we open any Excel File by double clicking the file, it will open the file but it will Not load any Addins. Reason is barely simple, the Addins were already closed by CLR but not the Excel Application Instance. So the file is actually opened in the previous Excel Ghost Instance.

Q. What is the solution?
Ans. One solution to the problem is: Go to task Manager, Process Tab, and kill the Excel.EXE instance.
The other solution is to include the following approach in AddInShutDown event of your code. This work around uses the Process Class.

1. Try to get the list of Processes by GetProcessByName method :
Process[] processes = Process.GetProcessesByName("EXCEL")
2. Run through Each Process in the processes Array and check if process.MainWindowHandle.ToInt64() is equal to 0. If this is 0 then you will need to kill the process right away.
3. The only thing you will need to take care is, to create a time Lag so that all the AddIns should shut down first then you will need to call the above steps.
4. Creating a Time lag means, you can use a separate EXE, which will run the above steps say 5 seconds after the Excel Closing event was fired.

Hope this helps :)

Thanks,
Vikas

Friday, April 3, 2009

Problem in using Information.TypeName Property

Hi All,

Whenever we debug the code in Dot Net while using InterOP, it is very frequent to notice a proxy object rather than the actual InterOP object. When you try to get the properties of an InterOP Variable, it shows you some proxy object, and not the actual InterOP object. For example, if I declare a variable like following :

Dim xlApp as XL.Application (The excel Application object)
set xlApp = ME.Globals.ThisAddin.Application

Now, in the debug mode, after executing the above line, if I want to see what values are stored in xlApp variable, the dot net editor will show the variable as a Runtime.Proxy object most of the times. The reason is, that normally, the InterOP layer creates a wrapper object to avoid any problems running in non EN-US locales.

Due to this behavior, I faced one problem. I was not able to obtain the Type Name of application' selection object because the selection object was coming as a proxy wrapper. I tried something like this :

Dim selectionType as string

selectionType = Information.TypeName(xlApp.Selection)

The above line was giving a System.Reflection.TargetInvocationException. I had to change my project's setting to ensure that the InterOp variables are not proxy objects. For that, I went to MyProject folder in my solution, opened the AssemblyInfo.vb file, change the attribute < Assembly: ExcelLocale1033(True) > set to < Assembly: ExcelLocale1033(False) > and saved the file. And see the difference, it didn't give me a proxy object :)

See the following thread For the example:
MSDN VSTO Thread Link.

Monday, March 30, 2009

Using WithEvents in Vb.Net

Hi,

Using withEvents in VB.net is very easy. I faced lot of problem while accessing the events. For example, activating a chart does not fire a selection change event. I had to do something like whenever I select my chart, my custom menu should appear. I couldn't find doing it in C#(please send a mail if you find it), but in VB.Net it is very easy.

So to take a small example, I have taken a scenario, if I select any of the chart in my workbook, it should display a message. So first of all I created a Class ProxyCharts. The purpose of the class is to serve a Wrapper for Charts Object. This is the class where we will bind our chart objects to WithEvent keyword. So as a wrapper, we will have as many Wrappers as the number of charts available in the workbook. The proxy chart is as follows:

Public Class ProxyCharts
Private WithEvents _Charts As Chart

Public WriteOnly Property _Chart() As Chart
Set(ByVal value As Chart)
_Charts = value
End Set
End Property

Private Sub _Charts_Activate() Handles _Charts.Activate
MsgBox(_Charts.Name, MsgBoxStyle.Exclamation, "ActivatedChart")
End Sub
End Class


Now we have to bind every chart in the workbook with the ProxyChart. So I added a WorkbookOpen method in my AddIn, which loops to all the charts in the opened workbook.

Private Sub _App_WorkbookOpen(ByVal Wb As Microsoft.Office.Interop.Excel.Workbook) Handles _App.WorkbookOpen

Dim chrtCol As Object
Dim chtCollection As Collection
Dim chrtObj As ChartObjects

For Each wkSht As Worksheet In Wb.Worksheets
chrtCol = wkSht.ChartObjects(Type.Missing)
chrtObj = TryCast(chrtCol, ChartObjects)

If Not chrtObj Is Nothing Then
For Each chrt As ChartObject In chrtObj
Dim chh As New ProxyCharts()
chh._Chart = chrt.Chart
Next chrt
End If
Next wkSht
End Sub



As soon as a workbook is opened, the WorkbookOpen method is called by default and binds all the charts in the opened workbook with ProxyChartType. After binding, the above code will display a message as soon as you select any of the pre existing charts in workbook.

Hope this helps.

Thanks,
Vikas

Thursday, March 26, 2009

Linq Example for Group Join

Hi All,

I have just started bringing LINQs to my work, and learning some new things. So I thought I will store it here before I forget it ;)

I had a simple problem, where in I had to loop through a list of files and to get out few Extensions. For example, If I have a list of around 500 files in the drive, I need to get the files with some valid extension, for eg, Images. So for that, I created a files list with the name of fileList and created an array with the valid extensions. I named that array by IMAGES.

Now to get the list of files with valid extensions I used the following code:


Dim result = From s In fileList Group Join p In IMAGES On s.Extension.ToUpper() Equals p.ToUpper() _ Into Group From p In Group Select s

WPF Fish Eye Effect

Hi,

I had a fantasy for Fish Eye effect, and I always have wondered how I will be able to do it one day. But guess what, it is barely simple. I didnt have to do anything much to do it. I am going to explain here in detail about the concept I followed:

Edited on : < May 20th 5.15 PM > Finally, I have got the way to store my projects with in my office. So please download it from
Here
First of all, in Xaml, I have a listview with the Following Code:



< ListView Name="lvwCharts" ItemsSource="{ Binding }" Margin="0,49,0,0">
< ListView.ItemTemplate>
< DataTemplate>
< Grid Width="250">
< StackPanel>
< Label Background="AliceBlue" HorizontalAlignment="Stretch" BorderBrush="Black" BorderThickness="1"
Content="{Binding Path = Name}" />

< Image Name="imgChart"
Height="{Binding Path = Height}"
Width="{Binding Path = Width}"
Source ="{Binding Path = Path, Converter={StaticResource converter}}"
MouseEnter="imgChart_MouseEnter"
MouseLeave="imgChart_MouseLeave"
MouseLeftButtonDown="imgChart_MouseLeftButtonDown"
HorizontalAlignment="Center"
VerticalAlignment="Center"
MouseWheel="imgChart_MouseWheel"
Margin="0"
/>
< /StackPanel>
< /Grid>
< /DataTemplate>
< /ListView.ItemTemplate>

< /ListView>


For Binding the object with the listview, create a class with the Chart Proxy


Public Class ChartsProxy
Private _name As String
Private _group As String
Private _height As Double = 100
Private _path As String
Private _width As Double = 100

Public Sub New(ByVal name As String, ByVal path As String, ByVal group As String, ByVal height As Double)
_name = name
_group = group
_path = path
End Sub

Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property

Public Property Group() As String
Get
Return _group
End Get
Set(ByVal value As String)
_group = value
End Set
End Property


Public Property Path() As String
Get
Return _path
End Get
Set(ByVal value As String)
_path = value
End Set
End Property

Public Property Height() As Double
Get
Return _height
End Get
Set(ByVal value As Double)
_height = value
End Set
End Property

Public Property Width() As Double
Get
Return _width
End Get
Set(ByVal value As Double)
_width = value
End Set
End Property

End Class


And in your Xaml.vb class add the following two Event handlers



Private Sub imgChart_MouseLeftButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
Dim img As Image
Dim proxy As ChartsProxy
Dim index As Integer = -1
img = TryCast(sender, Image)

If Not img Is Nothing Then
proxy = GetParent(img)

If Not proxy Is Nothing Then
index = lvwCharts.Items.IndexOf(proxy)
lvwCharts.SelectedIndex = index
End If

End If
lvwCharts.Focus()
lvwCharts.Items.Refresh()
End Sub

Private Sub imgChart_MouseLeave(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseEventArgs)
Dim img As Image
Dim proxy As ChartsProxy

img = TryCast(sender, Image)

If Not img Is Nothing Then
proxy = GetParent(img)

If Not proxy Is Nothing Then
Dim widthAnimation As DoubleAnimation = New DoubleAnimation()
widthAnimation.From = proxy.Width
widthAnimation.To = proxy.Width - 70
proxy.Width = proxy.Width - 70
widthAnimation.Duration = TimeSpan.FromSeconds(0.3)

Dim heightAnimation As DoubleAnimation = New DoubleAnimation()
heightAnimation.From = proxy.Height
heightAnimation.To = proxy.Height - 50
heightAnimation.Duration = TimeSpan.FromSeconds(0.3)
proxy.Height = proxy.Height - 50
img.BeginAnimation(Image.HeightProperty, heightAnimation)
img.BeginAnimation(Image.WidthProperty, widthAnimation)

End If

End If


'lvwCharts.Items.Refresh()

End Sub

Public Function GetParent(ByVal img As Image) As ChartsProxy
Dim proxy As ChartsProxy = Nothing
Dim prop As DependencyObject
Dim presenter As ContentPresenter
Dim bool As Boolean = True

prop = VisualTreeHelper.GetParent(img)

While bool
presenter = TryCast(prop, ContentPresenter)

If (Not presenter Is Nothing) Then

proxy = TryCast(presenter.Content, ChartsProxy)

If Not proxy Is Nothing Then
bool = False
Else
prop = VisualTreeHelper.GetParent(prop)
End If

Else
prop = VisualTreeHelper.GetParent(prop)
End If

End While

Return proxy
End Function


Edited on : < May 15th 2.13 PM > : As I have posted a very basic version here...if you want a complete code then send a mail at vikasbhandari2@gmail.com. I will send you a complete project.

Tuesday, March 24, 2009

Word 2003 Style Tracking Issue

In word 2003 or ealier versions, whenever we format a text on which a style is already applied, a new style is added in the Styles list and it keeps on increasing if we dont delete it. However, we can stop this automatic tracking and the automatic addition of styles will be disabled. For disabling the automatic addition of styles, go to Tools-->Options --> Edit tab and uncheck "Keep Track of Formatting" option. It is shown in the figure below




Thanks,
Vikas

Thursday, March 19, 2009

Filter using Predicate (WPF)

In WPF, XAML has changed the traditional way of creating and validation the form fields. For example, what if we want to display few of the items in a listview? And what if we want to give user an option to view the items with in the listview?

Without WPF, we will create the loop through all the items and will hide/show the items accordingly. But with WPF, we can do it very easily. I will explain in the following example.

Create a class SampleClass with Two Properties, Name(of string type) and Visible(of boolean type)

Create an ObservableCollection of type SampleClass in your Xaml.cs.

Code : ObservableCollection< SampleClass > collection = new ObservableCollection ()

Add few Items :

collection.Add(new SampleClass("Vikas", true));
collection.Add(new SampleClass("Sonia", true));
collection.Add(new SampleClass("Viman", False));
collection.Add(new SampleClass("Krishna", False));

Add the collection to our listview

myListView.DataContext = collection.

Now, for having a smooth access on filtering, sorting etc features, we will need to get the ICollectionView(Click to know more about ICollectionView) object out of out observable collection.

ICollectionView view = CollectionViewSource.GetDefaultView(collection);

now, to apply the filter we can use the following line anywhere in the code where in we want to put a filter on:

view.Filter = delegate(object item)
{
SampleClass sItem = item as SampleClass;
bool retValue = false;

if(sItem!=null)
{
retValue = sItem.Visible;
}

return retValue;
}

We can do the above step by using a new method with the predicate as well.

private bool GetVisibleState(object item)
{
SampleClass sItem = item as SampleClass;
bool retValue = false;

if(sItem!=null)
{
retValue = sItem.Visible;
}

return retValue;
}

And add the filter like following :

view.Filter = new Predicate< object >(GetVisibleState);

The above code will show the items in which the Visible property is set to true.

The code in VB.net is as follows :


Dim view As ICollectionView
Dim collection As ObservableCollection(Of SampleClass) = New ObservableCollection(Of SampleClass)

collection.Add(New SampleClass("Vikas", True))
collection.Add(New SampleClass("Sonia", True))
collection.Add(New SampleClass("Viman", False))
collection.Add(New SampleClass("Krishna", False))

myListView.DataContext = collection


view = CollectionViewSource.GetDefaultView(collection)
view.Filter = New Predicate(Of Object)(AddressOf FilterItems)



Private Function FilterItems(ByVal param As Object) As Boolean

Dim proxy As SampleClass
Dim Name As String
Dim retValue As Boolean

Name = combovalue ' (some arbit value, which you want to use as a filter. Example, the if you want to filter the value if the name is vikas, then say name = "Vikas")

proxy = TryCast(param, SampleClass)
retValue = proxy.Show

Return retValue

End Function


Public Class SampleClass
Private _name As String
Private _show As Boolean

Public Sub New(ByVal name As String, ByVal show As Boolean)
_name = name
_show = show
End Sub

Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property

Public Property Show() As Boolean
Get
Return _show
End Get
Set(ByVal value As Boolean)
_show = value
End Set
End Property
End Class

Wednesday, March 18, 2009

How to Use Linqs in VB.Net

With the new versions of Visual Studios, we have got the Power of LINQ(Language INtegrated Query). With the help of LINQ, we can make query on any collection like we do in SQL. What if we want to search if a string is present in an array or not. Let me explain this in an example :

I have a string Array :

Dim validXLExtns() As String = {"XLS", "XLSX", "XLA", "XLAM", "XLSM", "XLTX", "XLT", ""}


Now, I have to check programmatically if "XLS" exists in the array or not. Ideally, you will like to loop through the items in the array. But, now, with the help of LINQs you can do it with the following command :

Dim product = From s In validXLExtns _
Where s = "XLS"


And if product.count is greater than 0, the value actually exists in the array.


Some very good examples of LINQs:

Developer.com
MSDN LINQ Examples