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.

    Tuesday, December 1, 2009

    Active Directory Using VB.NET

    This article discusses working within the Active Directory (AD) using VB.NET, how to query the AD, How to authenticate the user, how to retrieve the user details using Domain User ID, how to retrieve the user details using domain e-mail id etc

    The Active Directory is the Windows directory service that provides a unified view of the entire network. Working with the Active Directory is a lot like working with a database, you write queries based on the information you want to retrieve.

    Recently, at work, I was tasked with creating a single signon for the application I am currently programming to allow the user to use the application without entering the userid and password details; Also I had to ensure that in the event the application was ever taken off-site, that it couldn't run; This would prevent an individual from taking the application off-site and attempting to use it.

    Then I thought of using the Active Directory of the company network to achieve the Single Signon as well as Security.

    Active directory seemed to be the most secure way as only a select group of people actually have the permissions to alter the Active Directory in any way.

    I built the logic using the System.DirectoryServices namespace.

    System.DirectoryServices: The System.DirectoryServices namespace built into the .NET Framework is designed to provide programming access to LDAP directories (Active Directory).

    To start querying Active Directory from your VB.NET code, you simply add a reference to the System.DirectoryServices.dll in your project and the following Imports statement to your code:


    Imports
    System.DirectoryServices

    When the application is launched, it will check the name the user was logged in as:

    Environment.UserName.ToString. It will return the user name in the format: DOMAIN\USERNAME

    After getting the user name the application will query the Active Directory to ensure this is a valid network account and they have permissions to be using this application.

    The first thing to do when working with the Active Directory is to create a connection to the Active Directory:

    dirEntry = New System.DirectoryServices.DirectoryEntry("LDAP://" & DOMAIN_NAME)

    You can replace the path with the one specific to your network.

    The next thing to search for the provided user to ensure that the login provided is a valid one.

    dirSearcher = New

    System.DirectoryServices.DirectorySearcher(dirEntry)

    dirSearcher.Filter = "(samAccountName=" & m_LoginName & ")"

    Dim sr As SearchResult = dirSearcher.FindOne()

    If sr Is Nothing Then 'return false if user isn't found
    lblStatus.Text = "User authentication failed"
    Return False
    End If

    The condition used here to Search for an entry for the logged in user. The "samAccountName" is the name of the field used to store Domain User ID.

    If the user does not exist in the Active Directory, the result will be nothing.

    The .FindOne() method will be used to stop searching as soon as the match is found.

     

    Sample Code 1:

    The IsLogonValid is used to validate the logged in user. It will search for the provided user in the Active Directory. The function will return true or false depending if the login provided is a valid one. With this function, if the selected user is found, and then True is returned, else False is returned, letting the programmer know that this isn't a valid user in the Active Directory.

    Private m_ServerName As String
    Private m_LoginName As String

    Private m_Authenicate As String

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

    ' Add any initialization after the InitializeComponent() call.
    m_ServerName = DOMAIN_NAME ' Your Domain Name
    m_LoginName = Environment.UserName.ToString
    m_Authenicate = My.User.Name 
    End Sub 
     

    Public Function IsLogonValid() As Boolean

    Dim m_LoginName As String
    Dim dirEntry As System.DirectoryServices.DirectoryEntry

    Dim dirSearcher As System.DirectoryServices.DirectorySearcher

    lblStatus.Text = "Validating User Account" 

    Try 
    m_LoginName = Environment.UserName.ToString 'The logged in user ID
    dirEntry = New System.DirectoryServices.DirectoryEntry("LDAP://" & DOMAIN_NAME) 
    dirSearcher = New System.DirectoryServices.DirectorySearcher(dirEntry) 
    dirSearcher.Filter = "(samAccountName=" & m_LoginName & ")"

           'Use the .FindOne() Method to stop as soon as a match is found

    Dim sr As SearchResult = dirSearcher.FindOne() 

    If sr Is Nothing Then 'return false if user isn't found
    lblStatus.Text = "User authentication failed"
    Return False
    End If

    Dim de As System.DirectoryServices.DirectoryEntry = sr.GetDirectoryEntry()

    sUserName = de.Properties("GivenName").Value.ToString()
     

    lblStatus.Text = "User authentication success"


    Return True  'Valid user


    Catch ex As Exception ' return false if exception occurs

    lblStatus.Text = "User authentication failed"


    Return False


    End Try


    End Function


     

    Sample Code 2:

    The DisplayActiveDirUserDetails function is used to retrieve the FirstName, Last Name and e-mail adddress of the logged in user.

    The PropertiesToLoad property of the DirectorySearcher object is a collection containing attribute names of AD objects that we want the query to return. By analogy with SQL query, the Filter property serves as the WHERE clause and the PropertiesToLoad property works as a list of column names that the query will return.

    To retrieve specific properties, we need add them to the Collection before we begin the search. For example, searcher.ProperiesToLoad("GivenName") will add the GivenName property to the list of properties to retrieve in the search.

    Some of the directory entry properties are

    • SAMAccountName – Users Login Name
    • Mail –E-Mail
    • Sn – SurName or Last Name
    • GivenName – First Name
    • Title – User Title
    • Phone – User telephone number
    • Department – User's Department etc.
    • Mobile – Mobile Phone number
    • City – User's City


     

    In this example I have retrieved only FirstName, LastName and e-mail address.


     

    Basically, this is a good practice to limit the amount of returning properties as much as you can. It can reduce execution time of the query significantly.


     

    Private Function DisplayActiveDirUserDetails(ByVal USERID As
    String) As Boolean


    Dim dirEntry As System.DirectoryServices.DirectoryEntry


    Dim dirSearcher As System.DirectoryServices.DirectorySearcher

    lblStatus.Text = "Validating User Account"

    Try dirEntry = New System.DirectoryServices.DirectoryEntry("LDAP://" & DOMAIN_NAME)

    dirSearcher = New System.DirectoryServices.DirectorySearcher(dirEntry) 

     dirSearcher.Filter = "(samAccountName=" & USERID & ")"

            'The PropertiesToLoad.Add method will be useful when retrieving only the selected properties.

    'In this example I have retrieved only GivenName, Mail and sn

    'There are many other properties are available


    dirSearcher.PropertiesToLoad.Add("GivenName")
    'Users First Name
    dirSearcher.PropertiesToLoad.Add("Mail")
    'Users e-mail address
    dirSearcher.PropertiesToLoad.Add("sn")
    'Users last name

    Dim sr As SearchResult = dirSearcher.FindOne()

    If sr Is Nothing Then 'return false if user isn't found
    lblStatus.Text = "Invalid UserID"
    Return False
    End If

    'Retrieve the user's First Name, e-mail and Last Name and assigns them to text boxes

    Dim de As System.DirectoryServices.DirectoryEntry = sr.GetDirectoryEntry() 

    If Not de.Properties("GivenName").Value Is Nothing Then
    txtUserName.Text = de.Properties("GivenName").Value.ToString()
    End If 

    If Not de.Properties("Mail").Value Is Nothing Then
    txtEmail.Text = de.Properties("Mail").Value.ToString()
    End If

    If Not de.Properties("LastName").Value Is Nothing Then
    txtLastName.Text = de.Properties("LastName").Value.ToString()
    End If

    Return True
    'Valid user

    Catch e As Exception ' return false if exception occurs

    MsgBox("User Authetication Exception: " & e.Message)

    Return False

    End Try

    End Function 
     

    Sample Code 3:

    The GetUserPropsUsingEmail function is used to retrieve the domain user Id using domain e-mail address.

    The userPrincipalName property of Active directory determines the Domain e-mail address of the User.
     

    Public Function GetUserPropsUsingEmail() As String


    Dim strFullName As String = ""

    Dim sPath As String = ""

    Dim objDirEnt As New DirectoryEntry("LDAP://" & DOMAIN_NAME)

    Dim objSearcher As New DirectorySearcher(objDirEnt)
    Dim objSearchRes As SearchResult

    ' Filter by Lotus Notes internet name

    objSearcher.Filter = "(userPrincipalName=" & txtInternetName.Text & ")"


    Try
    ' count should be 1

    If objSearcher.FindAll.Count > 0 Then

    For Each objSearchRes In objSearcher.FindAll
    sPath = objSearchRes.GetDirectoryEntry.Path

    Next
    objDirEnt.Close()

    objDirEnt.Path = sPath


    'get domain short name

    strFullName = objDirEnt.Invoke("GET", "samAccountName")


    End If


    Catch ' return nothing if user isn't found

    strFullName = ""


    End Try


    Return strFullName


    End Function


     

    SQL Query: Removing leading zeroes from SQL Server field

    The SQL Query for Removing leading zeroes from SQL Server field

    The following SQL Query removes the leading zeroes from "Field" field

    Select replace(ltrim(replace(Field1, '0', ' ')) , ' ', '0') FROM TestTable


     

    ERROR [HY000] [IBM][iSeries Access ODBC Driver][DB2 UDB]SQL0666 - Estimated query processing time xxx exceeds limit yyy

    ERROR [HY000] [IBM][iSeries Access ODBC Driver][DB2 UDB]SQL0666 - Estimated query processing time xxx exceeds limit yyy.


     Where xxx and yyy represent the estimated amount of time it will take to process the query and the OS/400 query time limit, respectively.

    The error occurs when the estimated SQL Query run time exceeds the system's query processing limit.

    Solution:

    You can turn off the query timeout limit in the iSeries Access ODBC Driver.

     

    IBM now provides you with a mechanism for turning off query timeout value support for applications that use a particular ODBC Data Source Name (DSN).

     

    You can turn off query timeout limit processing in a DSN by performing the following steps:

    • Open the ODBC Data Source Administrator on the client machine that is experiencing the SQL0666 error
    • In the Administrator window, highlight the DSN that you want to change and click on the Configure button
    • Click on the Performance tab in the Windows Setup dialogue
    • Click on the Advanced button under the Performance options. This will bring up the Advanced performance options window
    • Turn off the checkmark in the Allow Query Timeout checkbox. Click on OK to exit this screen
    • In the Windows Setup screen, click on the Apply button followed by the OK button. This allows you to exit the screen and save your changes


      image 

    • image 
       

    Once this option is turned off, applications using this particular ODBC DSN will automatically disable support for query timeout value checking.

    Note:

    But remember that while this option is handy for allowing longer running queries to automatically finish, it also removes a safeguard against run-away queries that will throttle PC and AS/400 performance. So use it only when it's needed and leave it on the rest of the time.

    Another Tip:

    The ODBC Progress database can store binary or array of data into "CHAR" field type.

    The SQLBulkCopy error "The byte array of data cannot be converted to nvarchar/varchar" might throw while migrating the data into SQL Server table's nvarchar/varchar (equivalent SQL data types)field.

    Reason: While retrieving the data will be reaching into the destination table as an array of bytes which is supposed to be a text or string of characters.

    IBM provides a mechanism to convert the binary data into text. This is achieved by performing the following steps:
     

    • Open the ODBC Data Source Administrator on the client machine that is experiencing this error
    • In the Administrator window, highlight the DSN that you want to change and click on the Configure button
    • Click on the Translation tab in the Windows Setup dialogue that appears
    • Turn on the checkmark in the Convert binary data (CCSID 65535) to text checkbox.
    • Click on the Apply button. This allows you to exit the screen and save your changes


       image

    How to display a PDF document in browser using ASP.NET and VB.NET?

    The below example would explain on how to Display a PDF document in browser using ASP.NET/VB.NET

    Dim Fs As FileStream
    Dim FileSize As Long
    Dim filePath As String = "C:\Test.Pdf"

    'Open the file.


    Fs = New FileStream(filePath, FileMode.Open)
    FileSize = Fs.Length

    'Convert the file into array of bytes.
    Dim Buffer(CInt(FileSize)) As Byte
    Fs.Read(Buffer, 0, CInt(FileSize))
    Fs.Close()

    'Write the binary content directly to the HTTP Output Stream.

    Response.ContentType = "application/pdf"
    Response.OutputStream.Write(Buffer, 0, FileSize)
    Response.Flush()
    Response.Close()

    Thursday, November 19, 2009

    XML Error- A semi colon character was expected. Error processing resource –

    1) XML Error: A semi colon character was expected. Error processing resource –

    Error Description:

    While  viewing  the xml file in a web browser, sometimes an error "A semi colon character was expected." Occurs.

    Example of a  XML snippet  that throws this error:

    <NODES>

    <NODE Caption="Ext Link" Link Name="http://google.com/ccc?key=0AEeVE& hl=en" />

    </NODES>

    Reason:

    This occurs when using external links on the XSLT sheet which contains the character “&”.

    Solution:

    The work around is to simply replace every instance of & in the link with &amp;

    <NODES>

    <NODE Caption="Ext Link" Link Name="http://google.com/ccc?key=0AEeVE&amp;hl=en" />

    </NODES>

    .NET Error: Operator '<operatorname>' is not defined for types '<typename1>' and '<typename2>'

    Error Description:

    The error "Operator '<operatorname>' is not defined for types '<typename1>' and '<typename2>'" occurs When an attempt was made to use an operator in a way that is inappropriate for the specified types.

    Reason:

    This error can be caused by using the "=" operator instead of using the Is operator to compare two objects.


     

    Example:


     

    Private Sub toolBar_ButtonClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs)


    If e.Button = toolBarButtonNew
    Then ' => Error Operator '=' is not defined for types 'System.Windows.Forms.ToolBarButton' and 'System.Windows.Forms.ToolBarButton'

          menuItemNew_Click(Nothing, Nothing)

    End If

     

    If e.Button <> toolBarButtonSave
    Then ' => Error Operator '<>' is not defined for types 'System.Windows.Forms.ToolBarButton' and 'System.Windows.Forms.ToolBarButton'

    menuItemNew_Click(Nothing, Nothing)

    End
    If

     

    End Sub

     

    Solutions:

    1. Use Is operator to compare two reference types.
    2. Use the Not operator in conjunction with the Is operator to denote inequality. 

    Replace


    1. "If e.Button = toolBarButtonNew
      Then"
      with "If e.Button Is toolBarButtonNew
      Then"

    2. "If e.Button <> toolBarButtonSave
      Then"
      with "If Not e.Button Is toolBarButtonSave
      Then"