Wednesday, December 9, 2009

WPF application template doesn't show up on my

I decided to start playing around with WPF, but I couldn't see the template when I went to New Project from Visual Studio 2008.  It turns out I need to do the following:
1.  In the command prompt - Go to the location where I've installed Visual Studio - c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE
2.  Make sure to close all open Visual Studio applications.
3.  Type in the following "devenv /installvstemplates"

I found the information here:
http://msdn.microsoft.com/en-us/library/ms247116.aspx


Wednesday, November 25, 2009

Dealing with the "Cannot open include file: 'windows.h': No such file or directory" error and the "A problem has been encountered while loading the setup components. Canceling setup." error

I got the error - "Cannot open include file: 'windows.h': No such file or directory" after I had installed Visual Studio 2008 Team Suite and I tried to compile something that compiles on another persons computer. 
When I looked at "C:\Program Files\Microsoft SDKs\Windows" there was a directory v5.0.  I thought maybe that is because I have VS 2005 and not VS 2008.  So I googled the error and I read that someone named Chris Hubbard from Microsoft suggested maybe I should run Setup again.  I read this here http://channel9.msdn.com/forums/Coffeehouse/415758-Visual-Studio-2008-Professional-no-windowsh-/ .  So I put in the install cd in again and tried the setup.exe at which point I got the following error:"A problem has been encountered while loading the setup components.  Canceling setup."  I then restarted the computer and got the same error again. 

Below is the data from the log file
===========
In the file dd_install_Vs_vstscore_90.txt in my Documents and Settings\Usernme\Local Settings\Temp directory

[11/25/09,11:22:04] Setup.exe: MoveLoadProgress()
[11/25/09,11:22:04] Setup.exe: MoveLoadProgress()
[11/25/09,11:22:04] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:22:04] setup.exe: ***ERRORLOG EVENT*** : ISetupModule::SetManager() failed in ISetupManager::LoadSetupObjectGuid() : vs_setup.dll
[11/25/09,11:22:05] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:22:05] setup.exe: ***ERRORLOG EVENT*** : CSetupManager::LoadSetupObjectname() - Failed in call to LoadSetupObjectGuid() for strName:  in file: vs_setup.dll
[11/25/09,11:22:05] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:22:05] setup.exe: ***ERRORLOG EVENT*** : LoadComponent(), LoadSetupObjectName failure: vs_setup.dll
[11/25/09,11:22:05] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:22:05] setup.exe: ***ERRORLOG EVENT*** : LoadComponent failed in ISetupManager::LoadComponentsFromDBObject(): vs_setup.dll
[11/25/09,11:22:05] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:22:05] setup.exe: ***ERRORLOG EVENT*** : CSetupManager::LoadDatabaseValues() - Failed in call to LoadComponentsFroMDBObjects()
[11/25/09,11:22:05] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:22:05] setup.exe: ***ERRORLOG EVENT*** : CSetupManager::RunIntro() - Failed to Load Database Values
[11/25/09,11:22:05] vs70uimgr: Entering DisplayMessage() method.
[11/25/09,11:22:05] vs70uimgr: DisplayMessage_START:A problem has been encountered while loading the setup components. Canceling setup.
[11/25/09,11:22:05] Setup.exe: CCoreEngine-Proc() - Finished Main Message Loop
[11/25/09,11:26:45] vs70uimgr: DisplayMessage_END:A problem has been encountered while loading the setup components. Canceling setup.
[11/25/09,11:26:45] Setup.exe: AddGlobalCustomProperty
[11/25/09,11:26:45] setup.exe: ***ERRORLOG EVENT*** : CSetupManager::RunLoadSetup() - Failed to Run the Intro
[11/25/09,11:26:45] Setup.exe: UnloadSuiteComponents()
[11/25/09,11:26:45] UTILS::RunNGENAction: Started
[11/25/09,11:26:45] UTILS::RunNGENAction: starting "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ngen.exe queue continue"
[11/25/09,11:26:45] UTILS::RunNGENAction: ngen.exe returned 0
[11/25/09,11:26:45] Setup.exe: GetGlobalCustomProperty - Property: {383F0141-C682-4665-A69B-756E719C968D} - PropertyName: Process Return Code - Value:
[11/25/09,11:26:45] Setup.exe: SETUP EXIT CODE - 0
==============

I then found this link, which says to repair from Add/Remove programs and not from the disk
http://blogs.msdn.com/heaths/archive/2008/08/20/do-not-repair-vs-2008-sp1-from-installation-media.aspx

I then went to add/remove programs and tried to run Change/Remove on my "Microsoft Visual Studioe Team System 2008 Team Suite - ENU"  but this resulted in the same error.  So at this point I was stuck.  So  I went back to google and found this link - http://stackoverflow.com/questions/114332/visual-studio-setup-problem-a-problem-has-been-encountered-while-loading-the-s (yes the link ends with an 's').  The user had the same problem and was just trying to uninstall the program.  He found a neat tool to completely remove the application, which I didn't need to use but I might need down the road.  I didn't want to completely remove the application I just wanted to "add the sdk's to the application."  Further down the page, people suggest the problem is with some of the Hotfixes that came with VS 2008.

- Removed Hotfix, but had the same error (however this time it did go further in the install process)
- Removed Update for Microsoft Visual Studio Team system 2008 Team Suite - ENU (KB972221)
    - This time I ran Change/Remove from Add/Remove programs and "it worked" in that it went to the Update page. When I had originally installed the software I had selected everything, so there was nothing new to select.  So the "Update" button was grayed out.  What I did was to uncheck something (anything) and then check it back on. 
    - If you read Chris Hubbard's notes (from the above link), it says that "Normal repair" will only repair the installed components.  So technically I did not run Setup again, I just did the "Normal Repair". 
- After setup ran for a while when it tried to install "Microsoft SQL publishing wizard", I got the following error - "Microsoft Visual Studio Team System 2008 Team Suite - ENU has encountered a problem during setup.  Setup did not complete correctly."
It appears that a number of components did install.  I clicked "Finish"
This is what was in my setup log file:

***EndOfSession***[11/25/09,10:48:18] setup.exe: [2] ISetupModule::SetManager() failed in ISetupManager::LoadSetupObjectGuid() : vs_setup.dll
[11/25/09,10:48:18] setup.exe: [2] CSetupManager::LoadSetupObjectname() - Failed in call to LoadSetupObjectGuid() for strName:  in file: vs_setup.dll
[11/25/09,10:48:18] setup.exe: [0] LoadComponent(), LoadSetupObjectName failure: vs_setup.dll
[11/25/09,10:48:18] setup.exe: [0] LoadComponent failed in ISetupManager::LoadComponentsFromDBObject(): vs_setup.dll
[11/25/09,10:48:18] setup.exe: [2] CSetupManager::LoadDatabaseValues() - Failed in call to LoadComponentsFroMDBObjects()
[11/25/09,10:48:18] setup.exe: [2] CSetupManager::RunIntro() - Failed to Load Database Values
[11/25/09,10:49:41] setup.exe: [2] CSetupManager::RunLoadSetup() - Failed to Run the Intro
[11/25/09,10:51:08] setup.exe: [2] ISetupModule::SetManager() failed in ISetupManager::LoadSetupObjectGuid() : vs_setup.dll
[11/25/09,10:51:08] setup.exe: [2] CSetupManager::LoadSetupObjectname() - Failed in call to LoadSetupObjectGuid() for strName:  in file: vs_setup.dll
[11/25/09,10:51:08] setup.exe: [0] LoadComponent(), LoadSetupObjectName failure: vs_setup.dll
[11/25/09,10:51:09] setup.exe: [0] LoadComponent failed in ISetupManager::LoadComponentsFromDBObject(): vs_setup.dll
[11/25/09,10:51:09] setup.exe: [2] CSetupManager::LoadDatabaseValues() - Failed in call to LoadComponentsFroMDBObjects()
[11/25/09,10:51:09] setup.exe: [2] CSetupManager::RunIntro() - Failed to Load Database Values
[11/25/09,10:51:18] setup.exe: [2] CSetupManager::RunLoadSetup() - Failed to Run the Intro
[11/25/09,11:06:15] setup.exe: [2] ISetupModule::SetManager() failed in ISetupManager::LoadSetupObjectGuid() : vs_setup.dll
[11/25/09,11:06:15] setup.exe: [2] CSetupManager::LoadSetupObjectname() - Failed in call to LoadSetupObjectGuid() for strName:  in file: vs_setup.dll
[11/25/09,11:06:15] setup.exe: [0] LoadComponent(), LoadSetupObjectName failure: vs_setup.dll
[11/25/09,11:06:15] setup.exe: [0] LoadComponent failed in ISetupManager::LoadComponentsFromDBObject(): vs_setup.dll
[11/25/09,11:06:15] setup.exe: [2] CSetupManager::LoadDatabaseValues() - Failed in call to LoadComponentsFroMDBObjects()
[11/25/09,11:06:15] setup.exe: [2] CSetupManager::RunIntro() - Failed to Load Database Values
[11/25/09,11:07:13] setup.exe: [2] CSetupManager::RunLoadSetup() - Failed to Run the Intro
[11/25/09,11:22:04] setup.exe: [2] ISetupModule::SetManager() failed in ISetupManager::LoadSetupObjectGuid() : vs_setup.dll
[11/25/09,11:22:05] setup.exe: [2] CSetupManager::LoadSetupObjectname() - Failed in call to LoadSetupObjectGuid() for strName:  in file: vs_setup.dll
[11/25/09,11:22:05] setup.exe: [0] LoadComponent(), LoadSetupObjectName failure: vs_setup.dll
[11/25/09,11:22:05] setup.exe: [0] LoadComponent failed in ISetupManager::LoadComponentsFromDBObject(): vs_setup.dll
[11/25/09,11:22:05] setup.exe: [2] CSetupManager::LoadDatabaseValues() - Failed in call to LoadComponentsFroMDBObjects()
[11/25/09,11:22:05] setup.exe: [2] CSetupManager::RunIntro() - Failed to Load Database Values
[11/25/09,11:26:45] setup.exe: [2] CSetupManager::RunLoadSetup() - Failed to Run the Intro
[11/25/09,11:37:49] setup.exe: [2] ISetupModule::SetManager() failed in ISetupManager::LoadSetupObjectGuid() : vs_setup.dll
[11/25/09,11:37:49] setup.exe: [2] CSetupManager::LoadSetupObjectname() - Failed in call to LoadSetupObjectGuid() for strName:  in file: vs_setup.dll
[11/25/09,11:37:49] setup.exe: [0] LoadComponent(), LoadSetupObjectName failure: vs_setup.dll
[11/25/09,11:37:49] setup.exe: [0] LoadComponent failed in ISetupManager::LoadComponentsFromDBObject(): vs_setup.dll
[11/25/09,11:37:49] setup.exe: [2] CSetupManager::LoadDatabaseValues() - Failed in call to LoadComponentsFroMDBObjects()
[11/25/09,11:37:49] setup.exe: [2] CSetupManager::RunIntro() - Failed to Load Database Values
[11/25/09,11:37:53] setup.exe: [2] CSetupManager::RunLoadSetup() - Failed to Run the Intro
[11/25/09,11:53:22] Microsoft SQL Publishing Wizard: [2] Error: Installation failed for component Microsoft SQL Publishing Wizard. MSI returned error code 1603
***EndOfSession***

- The interesting is that after this setup when I got to "C:\Program Files\Microsoft SDKs\Windows" there is now a directory called "v6.0a".  So something did happen, and I am now able to compile that project.  There are a couple of oustanding items that I need to now deal with:
1.  Add the hotfixes back in
2.  What about that item that didn't properly install?


Friday, November 13, 2009

Locate items in the SolutionExplorer

This blog and comments pretty much cover all the bases here.
http://dvanderboom.wordpress.com/2008/03/21/visual-studio-macro-track-item-in-solution-explorer-on-demand/

1.  You could just turn it on or off by going to Tools—>Options, expand Projects and Solutions, select General, and then uncheck the box next to Track Active Item in Solution Explorer.
2.  You could create a Macro and turn it on or off when you want it.  The site has the code for doing the macro
3.  You could add the option to the view menu you going to Tools->Customize, View, Track Activity in Solution Explorer, and then moving that to the View Menu
4.  The approach I selected.  You could bind the action to a keyboard shortcut by going to Tools->Options, Environment, Keyboard, finding View.TrackActivityInSolutionExplorer and clicking in the "Press shortcut Keys" box and then entering your shortcut.  I used Alt-T.  This way when you want it you can click Alt-T and then you can use Alt-T to turn it off.  What this method also does is pretty mimic the activity in step 1.




Thursday, November 12, 2009

How to get the AssemblyTitle


http://www.vb-helper.com/howto_net_get_program_version.html
Code in the above page works, except that if you have the code in a dll and you want to get the calling applications assemblytitle, you won't get it.  You'll get the assemblytitle of the dll.

I do know that if you use the System.Windows.Forms.Application.ProductName you will get the AssemblyProduct from the calling application.  But how do you get the AssemblyTitle from the calling application?


Tuesday, November 3, 2009

How to stop SMC service

 
http://www.symantec.com/connect/forums/smcexe-takes-99-cpu
 

upgrade to MP5 it will work

upgrade to MP5 it will work

Please see note below on how stop SMC service on a desktop if its going through the roof

• Open regedit
• HKEY_LOCAL_MACHINE\SOFTWARE\Symantec\SYMANTEC ENDPOINT PROTECTION\SMC\smc_exit_test 1 to 0

Then from the Symantec installed DIR etc c:\program files\symantec\symantec endpoint protection\

Then run.

• SMC –STOP

Then run an upgrade.

Then run.

• SMC –START

Then all done !!!

Enjoy.

Wednesday, September 2, 2009

Plus and Minus sign

I keep forgetting this but if you need to ever print out the +/- sign but have them on top of each other in VB.NET you would use Chr(177)


Thursday, August 27, 2009

AnkhSVN with a blue plus sign in Visual Studio even when you are connected to SVN

Recently, I opened my Visual Studio project that had AnkhSVN and all the files had a blue plus sign next to it.  I went to the Options menu and made sure that I had AnkhSVN as my Source Control Provider but for some reason it thought everything was new files.
 
The problem appears to be that I upgraded my TurtoiseSVN and didn't also upgrade my AnkhSVN. When I upgraded AnkhSVN, everything seemed to be fixed.
 
- Ted

Monday, August 10, 2009

Check if a String is a number

You could try:

double
Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum) Then
...

Or you could try the IsNumeric function from Microsoft.VisualBasic.FileIO




Monday, August 3, 2009

Start Windows Explorer on a specific directory in VB.NET


System.Diagnostics.Process.Start("Explorer.exe", "c:\dev\")

Default Values to Properties

Got this from:
http://www.vb-helper.com/howto_net_default_value.html


The DefaultValue attribute gives a property's default value. If you right-click on the property in the Properties window and select Reset, the property is reset to this value.

Usually the DefaultValue is the same as the property's initial value. This example uses the same constant for the FirstName property's initial and default values.

 
Private Const m_DefaultFirstName As String = "<unknown " & _
"first name>"
Private m_FirstName As String = m_DefaultFirstName

<DefaultValue(m_DefaultFirstName)> _
Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(ByVal Value As String)
m_FirstName = Value
End Set
End Property

Friday, July 31, 2009

VB.net to open a web page on a button click

System.Diagnostics.Process.Start("http://www.website.com")

You can actually use this to open a text page, word document.  IT will open the document with the application associated with that type of file.

Thursday, July 23, 2009

Check if the program is the first instance

I read this on codeproject and wanted to save it incase I need it down the road
 
To check that the program is the first instance, try this code :-

'Check to see if already running
Dim currentProcess As Process = Process.GetCurrentProcess()
Dim allProcesses() As Process = Process.GetProcessesByName(currentProcess.ProcessName)

If allProcesses.Length > 1 Then
'already running
Else
'not already running
End If


You could also pass the necessary parameter via a file. For instance write an file somewhere, containing the necessary parameters and use a FileSystemWatcher to monitor the file for changes.

Depands how slick you want it, but the simplest options are usually the best.

Monday, June 22, 2009

Padding out a cell with leading zeros in Excel

http://www.mrexcel.com/archive/General/14898.html

=REPT(0,8-LEN(A1))&A1

Or you can use the Format->Custom and enter 0000

Excel Formula to extract the Path from a filename

If you have C:\Temp\Files\1.txt
this wil lreturn C:\Temp\Files\

=MID(F1,FIND("*",SUBSTITUTE(F1,"\","*",LEN(F1)-LEN(SUBSTITUTE(F1,"\",""))))+1,LEN(F1))

Changing the Icon for an Application

For some reason I forgot about this. But when you launch an application, I know about having an icon for the form, but I forgot about having an icon for the application so that when it runs it has your icon on the task bar.

To do this its real simple. Just go to the Project Properties. Click on the Application Tab (it is probably the default selection). Then select "Icon:" and browse to in icon that you would lile. That's it.

Friday, June 19, 2009

How to return a dialog box result

I keep forgetting this but when you show a form via Showdialog you can check to see how that form was closed via  something like this:

If Form1.ShowDialog() = Windows.Forms.DialogResult.OK Then
   ....
End if

However when you do this in your Form1 you will need to specify the Dialog Result with something like this:

  Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
    Me.Close()
    Me.DialogResult = Windows.Forms.DialogResult.OK
  End Sub

  Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
    Me.Close()
    Me.DialogResult = Windows.Forms.DialogResult.Cancel
  End Sub

More info (barely) can be found here : http://msdn.microsoft.com/en-us/library/ms745820.aspx


Wednesday, June 17, 2009

Read in a tab delimited file in vb.net

If its a comma delimited file you can change ControlChars.Tab to ","
        Dim fields As String()
        Dim delimiter As String = ControlChars.Tab
        Using parser As New TextFieldParser(MultipleInputFile)
          parser.SetDelimiters(delimiter)
          While Not parser.EndOfData
            ' Read in the fields for the current line
            fields = parser.ReadFields()
            ' Add code here to use data in fields variable.
          End While
        End Using

How to determine if the Mouse is over a Control that is within another Control

You could so something in the MouseMove, MouseEnter, MouseLeave events, but I like this solution below. It uses a Timer and the on the Timer Click events it can determine if a control has Focus. In the situation below, I have two controls that are within a splitcontainer. when I mouse over the control, I want that control to have focus. For some reason it wasn't happening, and this code below takes care of that situation. I also had to use the PointToScreen call because the Controls are within the splitContainer and I wasn't getting the proper position otherwise.

Private WithEvents mTimer As Timer
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
mTimer = New Timer()
mTimer.Interval = 200
mTimer.Enabled = True
End Sub

Private Sub mTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles mTimer.Tick
Dim CursorPosition As Point = PointToScreen(Cursor.Position)
Dim Control1Bounds As New Rectangle(ImageContainer1.PointToScreen(Control1.Location), Control1.Size)
Dim Control2Bounds As New Rectangle(ImageContainer2.PointToScreen(Control2.Location), Control1.Size)

If Control1Bounds.Contains(CursorPosition) Then
Control1.Focus()
ElseIf Control2Bounds.Contains(CursorPosition) Then
Control1.Focus()
End If
End Sub

Detect Active Control on a Form

You can use the Me.ActiveControl property, additionally if a control is withing another control you can call this property from the control.  For Example if you have a SplitContainer which has another control in it you can do the following:

If Me.ActiveContainer Is SplitContainer1 Then
   If SplitContainer1.ActiveControl Is MyControl1 Then
        Do Something


Detect the Ctrl Key plus another key

Make sure the KeyPreview property is set to true
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.Modifiers = Keys.Control Then
            If e.KeyCode = Whatever key ou want
            End If
        End If
End Sub

Wednesday, June 3, 2009

itunes was unable to load provider data from sync services

I got this message when plugging in my ipod to my computer.

The solution seems to be this (at least it worked for me):
1.  I clicked ok, then waited for the sync to complete.  It appears that despite the message it still syncs but slowly and sometimes not all the files are synced with this error.  I then unplugged my ipod and closed itunes.
2.  Go to Control Panel > Administrative Tools > Services. Select 'Apple Mobile Device' and on the left side click 'Stop the service'. After it has stopped then select 'Start the service'. Then try opening iTunes again (I just plugged in my ipod back in and that launched itunes)

Solution was found towards the bottom of this page.  The message board has a lot of different solutions that seem to work for some but not for others
http://discussions.apple.com/thread.jspa?threadID=1595916&tstart=0

Tuesday, May 19, 2009

Using the Visual Studio Editor Regular Expression Search/Replace

I always forget this so I'm saving it here

If you want to save a string and then use it in the replace box put a {} around it.  Then you can refer to it using \1 or \2 (depending on how many curly brackets you put.

Ok, if you want more info you can check out the three part tutorial.

http://blogs.msdn.com/vseditor/archive/2004/06/16/157276.aspx
http://blogs.msdn.com/vseditor/archive/2004/06/18/159515.aspx
http://blogs.msdn.com/vseditor/archive/2004/06/18/159515.aspx

Or this site which compares it to regular regex.
http://www.codinghorror.com/blog/archives/000633.html

How do I configure the Visual Studio debugger to break when an exception is thrown?

http://windowsclient.net/blogs/faqs/archive/2006/05/26/how-do-i-configure-the-visual-studio-debugger-to-break-when-an-exception-is-thrown.aspx

In Visual Studio go to the Debug | Exceptions | Common Language Runtime Exceptions | System and select System.NullReferenceException.

In the When the exception is thrown group box, select Break into the debugger.

Run your scenario. When the exception is thrown, the debugger will stop and notify you with a dialog that says something like:

An exception of type "System.NullReferenceException" has been thrown.

[Break] [Continue]

Select [Break]. This will put you on the line of code that's causing the exception.



vb6.GetPath replacements

System.Windows.Forms.Application.ExecutablePath

System.Windows.Forms.Application.StartupPath

System.AppDomain.CurrentDomain.BaseDirectory()

System.GetEntryAssembly().Location

Vb6.FixedLengthString(2048) to Space(2048)

When we converted code from VB6 to .NET the following call was specified for a string that was a specific length

Dim astr as New VB6.FixedLengthString(2048)

In .NEt the replacement is
Dim aStr as String = New SpacE(2048)

This works just like the VB6. function call.

VB6.Format(tempstr, "mmm dd, yyyy") to CType(tempstr, Date).ToString("MMM dd, yyyy") in VB.NET 2005

VB6.Format(tempstr, "mmm dd,yyyy")
to
CType(tempstr, Date).ToString("MMM dd,yyyy")

The MMM gives you Jan as opposed to 01
For more information and all the formats go to :
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx


Replace Format(Now, "yyyymmdd") with Date.Now.ToString("yyyymmdd") in VB.NET 2005

Previously in VB6 we were doing
Format(Now, "yyyymmdd")
in .NET do the following Date.Now.ToString("yyyymmdd")

Monday, May 18, 2009

Replacement for VB6.Format(Number, "00") in VB 2005

When I converted the project from VB6 to VB.NET, either the Converter or someone on our team used the Microsoft.VisualBasic.Compatability library for the following code:
 VB6.Format(anumber, "00")
the replacement in .NET 2005 is:
CStr(anumber).PadLeft(2, "0")




Thursday, April 23, 2009

Recursively Iterate through a folder without using FileSystemObject in VB.NET

    Dim files As ReadOnlyCollection(Of String)
    files = My.Computer.FileSystem.GetFiles("c:\modifiedfiles\", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
    For index As Integer = 0 To files.Count - 1
       MsgBox files(index)
    Next

Tuesday, April 21, 2009

Increase the brightness on my Laptop

For some reason the brightness on my laptop screen is dark.  To increase/decrease the brightness use the Fn key and the Up/Down arrow.
 

Wednesday, April 15, 2009

Have a CheckedListBox only allow one selection at a time

At first I thought the SelectionMode.One property might be what I want but that doesn't seem to do it.  The block of code below seems to do it.

In the Handles clause add the CheckedListBox(s) that you want to only allow one selection for.

  Private Sub myList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged, CheckedListBox2.SelectedIndexChanged
    For index As Integer = 0 To sender.Items.Count - 1
      If index <> sender.SelectedIndex Then
        sender.setitemcheckstate(index, CheckState.Unchecked)
      End If
    Next
  End Sub


Wednesday, April 1, 2009

Change the cursor of the mouse to that of a circle

I needed a tool similar to one in a paint program where you can change the mouse cursor to that of a circle.  Initially my solution was to draw a circle around the mouse and to adjust this circle on mousemove.  Therefore you had a circle that followed the mouse around the screen.  However that was not a good solution as there were latent circles all over the image (it actually works if you don't have a background image).  I then tried using the OvalShape tool that came with the PowerPack3 but again that wasn't good with a background image.  Below is a solution that works.


Public Class Form1 
    Private radius As Integer = 20
    Private startAngle As Integer = 0
    Private sweepAngle As Integer = 360
    Private currentColor As Color = Color.Red
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        CreateCursor()
    End Sub
 
    Private Sub CreateCursor()
        Dim bmp As New Bitmap(radius * 2, radius * 2)
        Dim g As Graphics = Graphics.FromImage(bmp)
        Dim myPen As New Pen(currentColor, 1)
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias
        g.DrawArc(myPen, 0, 0, bmp.Width - 1, bmp.Height - 1, startAngle, sweepAngle)
        g.Dispose()
        myPen.Dispose()
 
        Dim C As New Cursor(bmp.GetHicon)
        Me.Cursor = C
    End Sub

End Class


fill the area outside of a polygon with a color

The graphics object has a fillpolygon function.  I wanted a solution to the problem of receiving an image and a polygon points and the need to fill the area outside of that polygon with a color.  The solution below solves that problem.

Imports System.Drawing.Drawing2D
Public Class Form1

  Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
    Dim polypoints() As Point

    ' Draw a polygon.
    polypoints = New Point() { _
        New Point(25, 100), _
        New Point(275, 350), _
        New Point(275, 100), _
        New Point(25, 350) _
    }

    Using gp As New GraphicsPath
      gp.AddPolygon(polypoints)
      Using rgn As New Region(gp)
        e.Graphics.ExcludeClip(rgn)
        e.Graphics.FillRectangle(Brushes.Red, Me.ClientRectangle)
      End Using
    End Using

  End Sub

End Class


Thursday, March 26, 2009

Save a byte array to a file

I've done this before and always seem to forget about it..  Found this here http://www.example-code.com/vbdotnet/save-byte-array.asp

How to save a byte array to a file in Visual Basic .NET
        Dim byteData() As Byte


' Create a file and write the byte data to a file.
Dim oFileStream As System.IO.FileStream
oFileStream = New System.IO.FileStream("bytes.dat", System.IO.FileMode.Create)
oFileStream.Write(byteData, 0, byteData.Length)
oFileStream.Close()



Friday, March 13, 2009

how to close a form when it loses focus vb.net

Put the the Me.Close call in the _Deactivate event.

The scenario is such:
- You have two forms, Form1 and Form2.  In Form1 you have a button and on the button_click event it just calls Form2.Show.  However when you click back on form1 you want Form2 to close.  You don't want it to go to the background, you want it out of there.  The solution is to close it in the DeActivate event

  Private Sub Form2_Deactivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Deactivate
    Me.Close()
  End Sub

Thursday, March 12, 2009

Read a comma delimited file in VB.NET

the snippets is
filParseText

The code is below:
Dim filename As String = FILE_NAME
Dim fields As String()
Dim delimiter As String = ","
Using parser As New TextFieldParser(filename)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
' Read in the fields for the current line
fields = parser.ReadFields()
' Add code here to use data in fields variable.
End While
End Using

Recursively Iterate through a folder

Set fs = WScript.CreateObject ("Scripting.FileSystemObject")

Sub ShowSubFolders(Folder)
For Each Subfolder In Folder.SubFolders
Set files = SubFolder.Files
For Each file In files
WScript.Echo file.Name, file.Size
Next
ShowSubFolders Subfolder
Next
End Sub

ShowSubFolders fs.GetFolder("C:\your\path\here")

Check for a text in a string

Dim find As String = "Ted"
Dim strg As String = "My name is Ted Unnikumaran"
If InStr(obj, find) = 1 Then
MsgBox("found it")
Else
MsgBox("not found")
End If

Monday, March 9, 2009

Visual Basic 2005: A Developer's Notebook/Windows Applications

A great  number of tips and tricks that are in visual basic 2005.


The one that I didn't know about that I used immediately was that now DoubleBuffered is a property that you can set for a UserControl.  PReviously, I would set it in the Sub New.

http://commons.oreilly.com/wiki/index.php/Visual_Basic_2005:_A_Developer%27s_Notebook/Windows_Applications



DoEvents vs Sleep

Sometimes when you want to delay things you might call a DoEvents.  However I've ocassionally come across situations where this can really slow down an application.  Sleep is actually called by DoEvents, so it might be better to call Sleep instead.  Call DoEvents if you have a long running routine or loop and you don't want to tie up the operating system.  Thats my take on it. 

This forum has more on the topic.
http://www.vbforums.com/showthread.php?t=344709

And it has an interesting API call where you check the status to see if there are items waiting in the Queue

  1. Option Explicit
  2.  
  3. Private Const QS_HOTKEY = &H80
  4. Private Const QS_KEY = &H1
  5. Private Const QS_MOUSEBUTTON = &H4
  6. Private Const QS_MOUSEMOVE = &H2
  7. Private Const QS_PAINT = &H20
  8. Private Const QS_POSTMESSAGE = &H8
  9. Private Const QS_SENDMESSAGE = &H40
  10. Private Const QS_TIMER = &H10
  11. Private Const QS_ALLINPUT = (QS_SENDMESSAGE Or QS_PAINT Or QS_TIMER Or QS_POSTMESSAGE Or QS_MOUSEBUTTON Or QS_MOUSEMOVE Or QS_HOTKEY Or QS_KEY)
  12.  
  13. Private Declare Function GetQueueStatus Lib "user32" (ByVal fuFlags As Long) As Long
  14.  
  15. Private Sub Form_Click()
  16.     Dim lngDoEventCnt As Long
  17.     Dim lngLoopCount As Long
  18.    
  19.     Do
  20.         If GetQueueStatus(QS_ALLINPUT) <> 0 Then
  21.             lngDoEventCnt = lngDoEventCnt + 1
  22.             DoEvents
  23.         End If
  24.        
  25.         lngLoopCount = lngLoopCount + 1
  26.     Loop Until lngLoopCount = 2000000
  27.    
  28.     Debug.Print lngDoEventCnt
  29. End Sub


Another post from the forum is below:

HOWTO: Determine the Differences Between DoEvents and Sleep
Q158175


SUMMARY
This article explains the differences between the Visual Basic DoEvents function and
the Sleep() Windows API function.

MORE INFORMATION
DoEvents is a Visual Basic function that yields execution so the operating system can
process other events. This function cleans out the message loop and executes any other
pending business in the Visual Basic runtime. Upon completing the pending business
execution, the function calls the Sleep function with zero (0) as the argument so that
the remaining time slice can be used to check the queue.

The Sleep 32-bit API function is a subset of the DoEvents function. The Visual Basic
program calling the function and the Visual Basic runtime executable and interactions
with Windows are immediately put to sleep by this function. The programs remain inactive
for the time in milliseconds specified in the Sleep argument.

The Sleep function allows you to specify the amount of time your applications are
inactive. The DoEvents function returns control to the Visual Basic program after
the operating system has finished processing the events in its queue and all keys in
the SendKeys queue have been sent.

The information in this article applies to:
Microsoft Visual Basic Learning Edition for Windows 5.0
Microsoft Visual Basic Learning Edition for Windows 6.0
Microsoft Visual Basic Professional Edition for Windows 5.0
Microsoft Visual Basic Professional Edition for Windows 6.0
Microsoft Visual Basic Enterprise Edition for Windows 5.0
Microsoft Visual Basic Enterprise Edition for Windows 6.0
Microsoft Visual Basic Standard Edition, 32-bit, for Windows 4.0
Microsoft Visual Basic Professional Edition, 32-bit, for Windows 4.0
Microsoft Visual Basic Enterprise Edition, 32-bit, for Windows 4.0
Last Reviewed: 5/13/2003 (3.0)
Keywords: kbhowto KB158175


Monday, February 23, 2009

Adjust the dropdownheight of a ComboBox automatically in VB.NET

I would like to adjust the size of a combobox to fit all of the items in it automatically.  One thing I noticed when testing it was if I set the dropdownheight to some large number, it automatically adjusted it to the size at runtime.  For example, if you combobox when fully filled out would need to be sized at say 200 pixels, but when you Designer you set the dropdownheight to 1000 when you run the program the combobox will only be sized at 200 pixels.  It won't create an enormously large combobox at 1000 pixels.

However the above solution just didn't seem right and I would like to have something where I wasn't hardcoding a number.  I came across this blog post below:
http://rajeshkm.blogspot.com/2006/11/adjust-combobox-drop-down-list-width-c.html

Basically he does what I want, but does it for the width of a combobox.  I converted the code to VB.NET and created a function that sets the Height as well.  The converted code and the modified function to adjust the height is below:

To call it just pass the name of the combobox to the routines

  Public Shared Sub SetComboScrollWidth(ByVal sender As Object)
    Try
      Dim senderComboBox As ComboBox = DirectCast(sender, ComboBox)
      Dim width As Integer = senderComboBox.Width
      Dim g As Graphics = senderComboBox.CreateGraphics()
      Dim font As Font = senderComboBox.Font

      'checks if a scrollbar will be displayed.
      'If yes, then get its width to adjust the size of the drop down list.
      Dim vertScrollBarWidth As Integer = IIf((senderComboBox.Items.Count > senderComboBox.MaxDropDownItems), SystemInformation.VerticalScrollBarWidth, 0)

      'Loop through list items and check size of each items.
      'set the width of the drop down list to the width of the largest item.

      Dim newWidth As Integer
      For Each s As String In DirectCast(sender, ComboBox).Items
        If s IsNot Nothing Then
          newWidth = CInt(g.MeasureString(s.Trim(), font).Width) + vertScrollBarWidth
          If width < newWidth Then
            width = newWidth
          End If
        End If
      Next
      senderComboBox.DropDownWidth = width
    Catch objException As Exception
      'Catch objException
    End Try
  End Sub

  Public Shared Sub SetComboScrollHeight(ByVal sender As Object)
    Try
      Dim senderComboBox As ComboBox = DirectCast(sender, ComboBox)
      Dim cboheight As Integer = senderComboBox.Height
      Dim g As Graphics = senderComboBox.CreateGraphics()
      Dim font As Font = senderComboBox.Font

      'Loop through list items and check size of each items.
      'increment the newheight to be the size of the items
      Dim newHeight As Integer = cboheight
      For Each s As String In DirectCast(sender, ComboBox).Items
        If s IsNot Nothing Then
          newHeight += CInt(g.MeasureString(s.Trim(), font).Height) '+ vertScrollBarWidth
        End If
      Next
      senderComboBox.DropDownHeight = newHeight
    Catch objException As Exception
      'Catch objException
    End Try
  End Sub

Wednesday, February 18, 2009

Select Block Text in Visual Studio

To select block, hold down the ALT key while dragging the cursor in the code window.  This way you can select a block of text rather than line by line.


Power Packs

I'm a little slow and had no idea that microsoft had released these power packs.  One great tool in there is the line and rectangle controls.  In my old vb code we had these line controls and I now draw them by hand.  I wish I had these power packs when I was doing the conversion.  Also the printing is made easier as I had to redo our entire printing when doing the conversion.

http://msdn.microsoft.com/en-us/vbasic/ms789080.aspx


Great explanation of Refresh vs Invalidate vs Update or using all three

http://www.vbforums.com/showthread.php?t=426684

Friday, February 13, 2009

Get the height and width of a polygon or a list of points in array in vb.net

When drawing a polygon, I place the points in an array and then draw it out.  However what if you want to know the height and width of your polygon.  One solution is to create a new GraphicsPath object from your array and then use the GetBounds.Width and GetBounds.Height call to get it.

           Dim apolygon As New GraphicsPath
           apolygon.AddPolygon(m_Points)
           If (apolygon.GetBounds.Width >= 10 AndAlso apolygon.GetBounds.Height >= 10) Then
                             do something
m_Points is an array of points

Thursday, February 5, 2009

Cannot have an enum of strings

When you try to do the following

Public Enum Enum_Type as String
  VALUE1 = "Value1"
  VALUE2 = "Value2"
End Enum

I get some error that the enum must be of integral type.

My work around was to do the following (nothing elaborate here):
Public CONST VALUE1 = "Value1"
Public CONST VALUE2 = "Value2"

And then I just accessed the values the same way I would have from the enum

-- Ted

Wednesday, February 4, 2009

Things you can do with the find box - mini buffer

http://blogs.msdn.com/saraford/archive/2007/11/26/did-you-know-how-to-have-fun-with-the-find-combo-box.aspx

  • Goto a line – type the line number and press Ctrl+G (i like showing this off as how you can do a "go to line" without popping up the go to dialog box) 
  • Goto a file – type the name of the file (either in your project or on the INCLUDE path)and press Ctrl+Shift+G
  • Set a breakpoint on a function – type the name of the function and press F9
  • Get help – type the keyword and press F1


Did you know... How to dock the Find and Replace window? - #076

http://blogs.msdn.com/saraford/archive/2007/11/05/did-you-know-how-to-dock-the-find-and-replace-window.aspx

Monday, February 2, 2009

a problem has occurred in retrieving the digital rights management machine identification

I got a new machine and when I tried to download a audiobook from Overdrive I got an error similar to the one mentioned above.  I ended up doing a number of things which may or may not have worked.  Below is that I did:

I followed the directions found here - http://www.microsoft.com/windows/windowsmedia/player/webhelp/default.aspx?&mpver=11.0.5721.5230&id=C00D11E2&contextid=71&originalid=C00D2781
Basically they ask you to reinstall Windows Media Player.  But when uninstalling it you need to remove about 3 other programs, and restart the computer.  Then you need to delete whatever is in your drm folder and then again restart the computer.  However that didn't work and I still got the error.

What I then did was in Overdrive, I went to Tools->Windows Media Player Security Update.  But I got an error when trying to do this.  So what I ended up doing was renamed the folder "C:\Documents and Settings\All Users\DRM" to "C:\Documents and Settings\All Users\DRM.old" then I tried the Tools->Windows Media Player Security Update again, and it worked.  One thing with the renaming of the folder is that you need to "Show all files" which is an options in Windows Explorer.

I think the second step is really what I needed to do and reinstalling Windows Media Player was just a waste of time.

-- Ted

Firefox tweak for Sharepoint

Whenever I have to go to the know or to a teamsite our our sharepoint server, I get this dialog box which prompts me to enter a username and password in firefox.  I don't get this in IE.   The fix in firefox is this:

1. Open Firefox

2. Navigate to the url about:config

3. Locate the following preference names and put as the value the comma separated values of the address roots.

network.automatic-ntlm-auth.trusted-uris

network.negotiate-auth.delegation-uris

network.negotiate-auth.trusted-uris

Your value should look something like this: localhost,noblis.org

-- Ted

Sorting Algorithms

This one will take only a minute, but it's a great way to graphically see the differences between sorting algorithms.

 

http://www.cs.rit.edu/~atk/Java/Sorting/sorting.html

 

Friday, January 23, 2009

How to include the DotNetFx folder and the WindowsInstaller3_1 into my application

Another way to ask this question is - "How to get the setup application to build the dotnetfx folder and the WindowsINstaller3_1". 

So that when you run the build of the setup application it creates a folder called dotnetfx and another folder called WindowsInstaller3_1

Well to do this, right click on your Setup project (from within the IDE), and then select Properties.  Then click on the "Prerequisites" button.  In the window that pops up make sure "Create setup program to install...." is checked.  In the next area, select ".NET Framework 2.0" and "Windows Installer 3.1" and in the radio buttons towards the bottom, select "Download prerequisites from the same location as my application"  Then click 'OK'.

Now when you build your application it will create thos folders for you.


Friday, January 16, 2009

Image.Save produces Bitmap with an incorrect header












The above two images will be referred to as good (left) and bad (right). They both look alike, but their headers contain a small difference. Most applications do not seem to mind this but some will give an invalid bitmap error when you use the bitmap saved from Visual Studio 2005. To recreate the bug:
Just create a VB.Net program and do the following:
Dim img1 As Bitmap = New Bitmap("c:\good.bmp")
img1.Save("c:\bad.bmp", Imaging.ImageFormat.Bmp)

Not sure if when you download the above two images if you'll get what I was working with, but just use any bitmap images. These are color, I've been able to recreate this issue using grayscale 8bit images at 500 ppi. If you were to open both bitmaps in a binary viewer you will see that that the header of bad.bmp is different. The good has the field "size of the image data" (offset 34) as F4080900, while the bad has the size of the image data as 00000000. I've also seen situations where the good has the field (offset 47) "number of colors in image" as 00 while the bad has it as 01. I am using Visual Studio 2005 SP1 and working with Visual Basic.

My solution was to create a function in C and to call that from the VB program instead of using the native Image.Save. I can't show that solution right now.

Additionally, the following incident seems to allude to a similar problem with the header but their problem looks to be different than ours.
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=214834

The field header locations and values were found on this website:
http://www.fastgraph.com/help/bmp_header_format.html

Thursday, January 15, 2009

Great page on the TabControl.

http://dotnetrix.co.uk/tabcontrol.htm

Topics include

Change the colours of a Tabcontrols Header Item.
A Completely OwnerDraw TabControl.
Associate a ContextMenu with the TabItem headers of a Tabcontrol.
Hide and Show Tabpages in a Tabcontrol.
An alternative approach to Tabpage Navigation.
Tabpage order has changed.
Reposition TabItems at runtime.
Add Mnemonic support to Tabpages.
Tabcontrol using custom Tabpages.
Mirrored Tabcontrol.
Prevent users navigating TabControl via Ctrl+Tab and Ctrl+Shift+Tab.
Add a SelectedIndexChanging Event.
Add a HideTabs property to turn on/off the Tabitems.
Add a custom Scroller to Tabcontrol.


Tuesday, January 6, 2009

How to create a Left-Click Context Menu that looks like its a drop-down list on a button

Copy and paste the code from the post just below this.  The key part is the function below.  When you click on the button, you want the ContextMenu to show up below the button making it appear that it is drop-down list.

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.ContextMenuStrip1.Show(Button1, New Point(0, Button1.Height))
  End Sub

How to dynamically create MenuStripItems and ContextMenuStripItems

To get this code working, drop a MenuStrip, ContextMenuStrip and a Button on the form, and then past the following code:


Public Class Form1
  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    SetMenus()
  End Sub
  Private Sub SetMenus()
    Dim mnuMenuItem1 As ToolStripMenuItem, mnuMenuItem3 As ToolStripMenuItem

    mnuMenuItem1 = New ToolStripMenuItem("Item 1", Nothing, New EventHandler(AddressOf mnuMenuItem1_Click))
    MenuStrip1.Items.Add(mnuMenuItem1)

    mnuMenuItem3 = New ToolStripMenuItem("Item 3", Nothing, New EventHandler(AddressOf mnuMenuItem3_Click))
    MenuStrip1.Items.Add(mnuMenuItem3)

    Dim mnuContext1 As ToolStripMenuItem
    Dim mnuContext2 As ToolStripMenuItem
    mnuContext1 = New ToolStripMenuItem("ToolStripMenuItem1", Nothing, New EventHandler(AddressOf mnuContext1_Click))
    mnuContext2 = New ToolStripMenuItem("ToolStripMenuItem2", Nothing, New EventHandler(AddressOf mnuContext2_Click))
    ContextMenuStrip1.Items.Add(mnuContext1)
    ContextMenuStrip1.Items.Add(mnuContext2)

  End Sub


  Private Sub mnuMenuItem1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    MessageBox.Show("Menu Item 1 Clicked")
  End Sub


  Private Sub mnuMenuItem3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    MessageBox.Show("Menu Item 3 Clicked")
  End Sub

  Private Sub mnuContext1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    MessageBox.Show("mnuContext1 Clicked")
  End Sub

  Private Sub mnuContext2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    MessageBox.Show("mnuContext2 Clicked")
  End Sub
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.ContextMenuStrip1.Show(Button1, New Point(0, Button1.Height))
  End Sub
End Class