Thursday, February 25, 2010

Display Logical drives information of Machine VB.NET

The following code snippets explains how to retrieve the logical drives in the system, information about the logical drives (Drive Name, Drive Type, Available Free Size, Volume Label etc.,)  present in the system.

All we have to do is to reference the namespace System.IO

The System.IODirectory.GetLogicalDrives method is used to get an array of the drive names.  I have displayed them in a ListBox.




' List the drives.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal _


e As System.EventArgs) Handles MyBase.Load


For Each drive As String In Directory.GetLogicalDrives()


    lstDrives.Items.Add(drive)


Next drive

End Sub


This code snippet how to retrieve information about each logical drive. The important thing to be noted here that, we have to check whether the device is ready before accessing it's properties, otherwise it will throw the exception "Device is not ready"
'List the Drives Information for each drive

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click



Dim strInfo As String = ""



For Each drive_info As DriveInfo In DriveInfo.GetDrives()


If drive_info.IsReady() Then


' Display information about the selected drive.


strInfo = strInfo & " Device is ready" & vbCrLf


strInfo = strInfo & "Drive Name: " & drive_info.Name.ToString & Environment.NewLine


strInfo = strInfo & "Drive Type: " & drive_info.DriveType.ToString & Environment.NewLine


strInfo = strInfo & "Drive Format: " & drive_info.DriveFormat.ToString & Environment.NewLine


strInfo = strInfo & "Available Free Space: " & drive_info.AvailableFreeSpace().ToString & Environment.NewLine


strInfo = strInfo & "Total Free Space: " & drive_info.TotalFreeSpace.ToString & Environment.NewLine


strInfo = strInfo & "Total Size: " & drive_info.TotalSize.ToString & Environment.NewLine


strInfo = strInfo & "Volume Label: " & drive_info.VolumeLabel.ToString & Environment.NewLine


strInfo = strInfo & "Root Directory: " & drive_info.RootDirectory.ToString & Environment.NewLine



Else


' Display information about the selected drive.


strInfo = strInfo & " Device not ready" & vbCrLf


strInfo = strInfo & "Drive Name: " & drive_info.Name.ToString & Environment.NewLine


strInfo = strInfo & "Drive Type: " & drive_info.DriveType.ToString & Environment.NewLine


'strInfo = strInfo & "Drive Format: " & drive_info.DriveFormat.ToString & Environment.NewLine


'strInfo = strInfo & "Available Free Space: " & drive_info.AvailableFreeSpace().ToString & Environment.NewLine


'strInfo = strInfo & "Total Free Space: " & drive_info.TotalFreeSpace.ToString & Environment.NewLine


'strInfo = strInfo & "Total Size: " & drive_info.TotalSize.ToString & Environment.NewLine


'strInfo = strInfo & "Volume Label: " & drive_info.VolumeLabel.ToString & Environment.NewLine


strInfo = strInfo & "Root Directory: " & drive_info.RootDirectory.ToString & Environment.NewLine


End If


Next drive_info



lblDriveInfo.Text = strInfo 'Displaying the information in the label


End Sub


Finally display the information in the label.

Wednesday, February 24, 2010

Hosting MS Office Inside .NET Windows Forms Applications

The purpose of this article is to discuss how to build Office solutions in Visual Studio .NET.




WebBrowser Control – (available from the Visual Studio .NET WinForms designer toolbox) which allows simply to navigate to a file-URL pointing to an office document.



The problem is, WebBrowser is nothing else than the well known Internet Explorer webbrowser control, so its behavior depends on the client's internet settings.

E.g. when "Confirm open after download" has been set, a file download dialog will appear when programmatically opening an Office document (even in case of a local file), and after confirming the document shows up in a new top-level Word or Excel window, not inside the webbrowser control's host (= your application).



That's why I switched from WebBrowser to the DSOFramer ActiveX control provided by Microsoft, which doesn't have these restrictions.

DSOFramer Control

The DsoFramer control is an ActiveX control provided by Microsoft that allows you to host instances of Office applications (Excel, Word , Visio, Power Point etc) inside our ActiveX-capable application, including Windows Forms. The DSO Framer control is compatible with Office 2007, so we can embed all office 2007 applications.



DSOFramer Control in Windows Forms



Steps to use DSOFramer Control in Windows Forms application



1. Download the DSOFramer Control from Microsoft Website and install it in your machine.





2. Open a new Visual Studio Project





3. Add New Form





4. Right Click on Tool Box -> Click Choose Items …




5. Select Com Components Tab





6. Select DSO Framer Control Object





7. Click On Ok.










8. Drag and Drop the Control DSO Framer onto the Form




9. Name the control as AxFramerControl1

The following VB.NET Code examples explains how to create a new office document(Excel, Word etc), open existing office document (Excel, Word etc).


Opening Office Documents


Opening an Excel File

Dim FileViewer As AxDSOFramer.AxFramerControl = Nothing


Dim _FileName As String = ""


_FileName = "C:\Test.xls"


FileViewer = Me.AxFramerControl1


FileViewer.Open(_FileName, True, Type.Missing, Type.Missing, Type.Missing)




' To open file from Web site With UserId and password


FileViewer. Open ("https://Myserver/test/mytest.asp?id=XFile", True, " Excel.Sheet ", "MyUserAccount", "MyPassword")



The File Extensions supported are .xls, .xlsx, .doc, .docx, .ppt and .pptx .



To Open word document,

_FileName = "C:\Test.doc"


_FileName = "C:\Test.docx" ' Office 2007






To Open Power Point,


_FileName = "C:\Test.ppt"


_FileName = "C:\Test.pptx" ' Office 2007




Create a New instance of Office application


To create an instance of an office application, the ProgId needs to be passed to the CreateNew function. Some of the examples are given below:



1. Excel Sheet Creation

FileViewer.CreateNew("Excel.Sheet")

2. PowerPoint Show Creation

FileViewer.CreateNew("PowerPoint.Show")

3. Word File Creation

FileViewer.CreateNew("Word.Document")

4. Excel Chart Creation

FileViewer.CreateNew("Excel.Chart")





Saving Files


We can save the application by passing the FileName. For Example,

FileViewer.Save "C:\aa.doc" , will save the file with the name aa.doc.


Customization of DSOFramer


The DSOFramer can be customized to hide/show the toolbar, menu bar and disable/enable the menu options.



AxFramerControl1.Toolbars = False 'Hide Tool Bar




AxFramerControl1.Menubar = False 'Hide Menu Bar


AxFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileNew, False) 'Disable the File New Option


AxFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileOpen, False) 'Disable the File Open Option


AxFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileClose, False) 'Disable the File Close Option


AxFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileSave, False) 'Disable the File Save Option


AxFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFileProperties, False) 'Disable the File Properties Option


AxFramerControl1.set_EnableFileCommand(DSOFramer.dsoFileCommandType.dsoFilePrintPreview, False) 'Disable the File Print Preview Option



Destroying the instance

Whenever we create an instance of an office application, we must destroy it explicitly as it will not get destroyed automatically.



If we don’t destroy the instance, for example after opening the file ‘c:\aa.doc’ in the DSOFramer , close the form and tries to open the file again it will throw the error “Cannot access the file”



The following Code snippet explains how to destroy the instance and do explicit garbage collection.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing


Try






If Not xlsViewer Is Nothing Then


xlsViewer.Dispose()


xlsViewer = Nothing


End If

GC.Collect()


GC.WaitForPendingFinalizers()

Catch ex As Exception


MsgBox(ex.Message)


End Try


End Sub

DBNull is a type and cannot be used as an expression

This is a compile time error which occurs when checking whether the value is System.DBNULL with the following statement..



If result Is System.DBNULL Then


End If



The correct statement should be



If result Is System.DBNULL.Value Then


End If

Concatenation of NULL strings in SQL Server

Concatenation of String with a null value always yields a NULL result. When we concatenate two field values using ‘+’ operator in SQL Server, it yields a NULL result when either one of the value is NULL.

For example , SELECT FirstName + LastName AS Name yields NULL value where FirstName is ‘XX’ and LastName is Null.



But the actual requirement should be ‘XX’ instead of NULL.



This can be achieved in two ways:



1. Using SET CONCAT_NULL_YIELDS_NULL option

If The SET CONCAT_NULL_YIELDS_NULL option is OFF, concatenating a null value with a string yields the string itself , as the NULL value will be treated as an empty string



Example:

SET CONCAT_NULL_YIELDS_NULL OFF


GO


SELECT FirstName + LastName AS Name


GO


SET CONCAT_NULL_YIELDS_NULL ON


GO


SELECT FirstName + LastName AS Name


GO

Result:

XX


NULL



By default, CONCAT_NULL_YIELDS_NULL option is ON.

2) Using ISNULL Keyword



The ISNULL option replaces the NULL value with specified value. In this example if the Last Name is NULL value, then it will be replaced by empty string.

SELECT FirstName + ISNULL( LastName,’ ‘) AS Name

Result:

XX

Thursday, February 18, 2010

How to Integrate Windows Forms in WPF Applications

This article explains how to integrate Windows Forms in WPF Application.



The first thing we need to do (after creating a new WPF project) is add few references.


1. Add reference to System.Windows.Forms and WindowsFormsIntegration.











Once these two references are added, we have access to all windows forms controls and access to the components that will allow us to embed them in WPF.

2. In the WPF Tool Box, we can see WindowsFormsHost control






This object is glue layer between WPF and Windows Forms. The WindowsFormsHost is a Framework element, so it can be added to anything in WPF that can take an element. But it has a property Child which takes in a System.Windows.Forms.Control - and this is the control that will be embedded.


Drag and Drop the WindowsFormsHost Control in WPF Window.

Our XAML is going to be extremely simple:

<Window x:Class = "Window1" >

xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="278" Width="587"
<Grid>
<WindowsFormsHost Name="WindowsFormsHost1" >

</Grid>
</Window>








3. Add New Windows Forms to the WPF application



Add DataGridView and add few columns and the windows form would look like as follows:





Set EnableVisualStyles()of Windows Forms in the New Method.



Public Class Form1


Public Sub New()




' This call is required by the Windows Form Designer.


InitializeComponent()





' Add any initialization after the InitializeComponent() call.


Forms.Application.EnableVisualStyles()


End Sub


End Class




4. After the Form is ready, all we need is adding the form as the child for the WindowsFormsHost control.



In the WPF Window Load event add the following:



Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded


Dim Frm As New Form1


Frm.TopLevel = False 'Very important ..



WindowsFormsHost1.Child = Frm



Frm = Nothing



End Sub

5. See the result




That’s All!!!!!!


And that is about it for Hosting Windows Forms or Windows Forms Controls inside of WPF Window.

Wednesday, February 17, 2010

Gradient Background on .NET Windows Forms or Controls

The following few lines of code adds cool gradient background to the .NET windows forms or controls.

1. Imports System.Drawing.Drawing2D
2. Add the following in New() function

Public Sub New()

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

' Add any initialization after the InitializeComponent() call.


Me.SetStyle(System.Windows.Forms.ControlStyles.DoubleBuffer, True)
Me.SetStyle(System.Windows.Forms.ControlStyles.AllPaintingInWmPaint, True)
Me.SetStyle(System.Windows.Forms.ControlStyles.ResizeRedraw, True)
Me.SetStyle(System.Windows.Forms.ControlStyles.UserPaint, True)

End Sub
3. Add the following in Paint() function of Form

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
'Fill Panel with gradient colors Red and Blue
Dim rect As New System.Drawing.Rectangle(0, 0, e.ClipRectangle.Width, e.ClipRectangle.Height)

Dim g As Graphics = e.Graphics

Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), System.Drawing.Color.Red, Color.Blue)
g.FillRectangle(gradientBrush, rect)

End Sub


1. We can do the same thing for all Form Controls by adding the above three lines in the Paint Event of the controls (E.x Panel )

The following Code snippet explains how to paint the panel with gradient background.
Private Sub Panel1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
'Fill Panel with gradient colors white and green
Dim rect As New System.Drawing.Rectangle(0, 0, e.ClipRectangle.Width, e.ClipRectangle.Height)

Dim g As Graphics = e.Graphics

Dim gradientBrush As New LinearGradientBrush(New Point(0, 0), New Point(Width, 0), System.Drawing.Color.White, Color.Green)
g.FillRectangle(gradientBrush, rect)

End Sub

.NET Error: Class not registered Exception from HRESULT: 0×80040154

This error might occur when an ActiveX control is not registered in the machine. For example, the DSO Framer control (an ActiveX control to host office file) works fine in the local machine. After deployment in another machine, it might throw the error: “Class not registered

Reason:
An AciveX control needs to be registered before it can be used

How to register the active-x control?

1) Using regsvr32.exe (Manual registration)


The active-x control needs to be manually registred in that machine by using regsvr32.exe.
Go the the DOS prompt and type in "regsvr32.exe c:\DSOFramer.ocx".


2) During Deployment: (Best option)


1. Add the dsoframer.ocx in your Setup project
2. Set the Register property of this file to vsdrfCOM.
3. Build the Setup project and run the resulting MSI package to install your application as well as the DSOFramer ActiveX control on the target machine.