Thursday, May 14, 2009

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