Web Code Blog

A web repository of coding tips and knowledge base articles

Obtaining XML Node Order when using SQL Server

Posted by Stefan Zvonar on January 11, 2012

Unfortunately, when reading / shredding XML document from SQL Server, there are no guarantees in the order in which SQL Server will read the XML nodes.  This can prove particularly troublesome if your code or import procedure relies on a specific order.  When you run your script, the order it retrieves the XML is random and can be the cause of some intermittent results – which can contribute to hair loss.

Your first thought, may be to try and use the “position()” function in your retrieval script, but alas, this will not work.

The below solution is a bit of a hack, but it seems to work regardless of how many times I run the script and I can guarantee the order in which the node information was presented in the XML.

First, let’s assume you have an XML parameter, or XML column in a table in your database.  Here, we are just going to create a dummy XML data type for demonstration purposes.

DECLARE @Xml XML

SET @Xml =

<Data>

    <Field>

        <Name>Person</Name>

        <Value>Joe Bloggs</Value>

    </Field>

    <Field>

        <Name>Telephone</Name>

        <Value>12345678</Value>

    </Field>

    <Field>

        <Name>Address</Name>

        <Value>1 Blah Street</Value>

    </Field>

</Data>

Now, we are going to create a temporary table which is simply full of sequential numbers which should cater for the number of nodes you are expecting. Note, in my case, I was reading XML describing the fields I was expecting, so 100 numbers here is more than enough. You may require more.

Here I create the table to consist of 100 numbers (as that is more than enough to cover the number of fields I am expecting).

DECLARE @Numbers TABLE(num int identity(1,1))

INSERT @Numbers DEFAULT VALUES;

WHILE SCOPE_IDENTITY() < 100

    INSERT @Numbers DEFAULT VALUES;

Then, we are going to perform the query on the XML, to retrieve the field information, combined with the order in which the node is stored in the XML.

SELECT *

INTO #Fields  

FROM 

(

    SELECT

        –Fields.Field.value(‘position()’, ‘int’) AS Order,  — Unfortunately, this will not work!

        n.num AS [Order],

        Fields.Field.value(‘./Name[1]‘, ‘varchar(50)’) AS FieldName,

        Fields.Field.value(‘./Value[1]‘, ‘varchar(50)’) AS FieldValue

    FROM @Numbers n

        CROSS APPLY @Xml.nodes(‘/Data/Field[sql:column("n.num")]‘) AS Fields(Field)

) AS f

 

SELECT * FROM #Fields

 

DROP TABLE #Fields

Below is an example of what is returned:

Ordered Node Values in Table

As you can see, it provides you now with a temporary table and column that defines the order in which the XML node was presented in the XML. You can then sort this table by the order column if you so wish, join by it, or whatever it is you need to do!

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in SQL Server, XML | Leave a Comment »

Executing xp_cmdshell with SQL Server 2008 R2

Posted by Stefan Zvonar on November 18, 2011

Sometimes there comes a time when you would like to have a user of your database be able to execute a program by making use of SQL Server’s xp_cmdshell procedure.  It can be a little tricky setting up the permissions to enable this call, so here are some steps you can take to make it possible.

Firstly, allow execution of xp_cmdshell:

USE [master]
GO
EXEC sp_configure 'xp_cmdshell', 1 RECONFIGURE 
GO

Secondly, create a SQL Login that can run xp_cmdshell.  Please create a more secure password than the example given:

USE [master] 
GO
CREATE LOGIN [CommandShellLogin] WITH PASSWORD ='abc123!@#' 
GO
CREATE USER [CommandShellLogin] FROM LOGIN [CommandShellLogin] 
GO
GRANT EXECUTEON xp_cmdshell TO [CommandShellLogin] 
GO

Thirdly, because you will be switching to this command shell login temporarily, grant impersonation rights to the user’s group. Note: Am assuming that the user group is mapped to a login in SQL Server:

USE [master] 
GO
GRANT IMPERSONATE ON LOGIN::CommandShellLogin TO [DOMAIN\USER GROUP] 
GO

Now, you could make [CommandShellLogin] a member of sysadmin to make this work, but that would be providing too much priviledges. Instead, you can set up a proxy account that xp_cmdshell uses whenever it is called. This will be an actual windows account that the command will execute as, so make sure that the windows account has the permissions to perform whatever it is you are intending it to execute:

EXEC sp_xp_cmdshell_proxy_account 'DOMAIN\User', 'UserPassword' 
GO

Now in your procedure, trigger, script or whereever you plan on running xp_cmdshell, switch the context to the CommandShellLogin user temporarily to execute your desired command. Here we are just running DIR as an example:

EXECUTE AS LOGIN = 'CommandShellLogin' 
EXEC xp_cmdshell 'DIR' 
REVERT

Note: Setting up the proxy account above results in any xp_cmdshell to run as the user specified. If you no longer want subsequent calls to xp_cmdshell to run as that windows account, then ensure that you empty the proxy account so that it does not run anymore as that account:

EXEC sp_xp_cmdshell_proxy_account NULL 

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in SQL Server | Leave a Comment »

Quickly check if network file or path exists in VB.NET

Posted by Stefan Zvonar on May 31, 2011

This little article explains a way to check if a file or path exists in code, without having to wait a long time for the result if the network is down or the path does not exist.

For example, in my particular case, I wanted a way to check for connectivity to the network before accessing the server file system. Scaling the internet I found some good C# examples (like this one: http://stackoverflow.com/questions/1232953/speed-up-file-exists-for-non-existing-network-shares)

However, the application I was working on was developed in VB.Net and the threading code is quite different between the languages.

The first problem I encountered was trying to pass a variable to the threading function. After some playing around, I was able to produce the following in VB.Net (based on the example in the link above) and using Visual Studio 2008.

   Public Function PathExists(ByVal path As String, ByVal timeout As Integer) As Boolean
        Dim exists As Boolean = True
        Dim t As New Thread(DirectCast(Function() CheckPathFunction(path), ThreadStart))
        t.Start()
        Dim completed As Boolean = t.Join(timeout)
        If Not completed Then
            exists = False
            t.Abort()
        End If
        Return exists
    End Function

    Public Function CheckPathFunction(ByVal path As String) As Boolean
        Return System.IO.File.Exists(path)
    End Function 

Note: To use this method, you would call the function like done below, passing in an integer representing milliseconds before it stops trying to reach the path – in this case I have set it to 3 seconds.

If PathExists("\\BLAH\PATH\", 3000) Then 
...
End If

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in .NET | 2 Comments »

ASP.NET website not working with DNS Alias

Posted by Stefan Zvonar on April 5, 2011

This is a curious bit of information I have stumbled upon.

An ASP.NET Web Site will not persist session variables between requests when the host name has an underscore (“_”) in it. This is only apparent when using Internet Explorer.

Turns out that underscores are against the standard of naming servers. The particular server I was using decided they wanted to use a DNS Alias for all requests (in case of server name changes in the future). However, the alias itself had an underscore in it, which stopped page requests from working properly in the ASP.NET web site.

Here is a little summary from Microsoft:

SYMPTOMS

After you install security patch MS01-055 for Microsoft Internet Explorer 5.5 or 6.0, you may encounter the following problems:

* Session variables are lost.
* Session state is not maintained between requests.
* Cookies are not set on the client system.

Note These problems can also occur after you install a more recent patch that includes the fix that is provided in security patch MS01-055.

CAUSE
Security patch MS01-055 prevents servers with improper name syntax from setting…
Security patch MS01-055 prevents servers with improper name syntax from setting cookies names. Domains that use cookies must use only alphanumeric characters (“-” or “.”) in the domain name and the server name. Internet Explorer blocks cookies from a server if the server name contains other characters, such as an underscore character (“_”).

Because ASP session state and session variables rely on cookies to function, ASP cannot maintain session state between requests if cookies cannot be set on the client.

This issue can also be caused by an incorrect name syntax in a host header.

RESOLUTION
To work around this problem, use one of the following methods: Rename the domai…
To work around this problem, use one of the following methods:

* Rename the domain name and the server name, and use only alphanumeric characters.
* Browse to the server by using the Internet Protocol (IP) address rather than the domain/server name.

Note You may need to change the Microsoft Internet Information Server (IIS) configuration after you rename a server.

Click here to read the full Microsoft Support Article.

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in .NET, ASP.NET, IIS | Leave a Comment »

Find out what service pack and edition your SQL Server installation is

Posted by Stefan Zvonar on April 4, 2011

Here is a quick little T-SQL script to run to find out some basic version, service pack and edition your SQL Server Instance is running:

SELECT SERVERPROPERTY('productversion') AS [Version], SERVERPROPERTY ('productlevel') AS [Service Pack], SERVERPROPERTY ('edition') AS [Edition]

The complete knowledge base article can be found here.

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in SQL Server | Leave a Comment »

Using KDiff for your TFS comparison and merging tool

Posted by Stefan Zvonar on January 4, 2011

TFS is a great source control solution, however it can be a pain when trying to merge or even compare code when merging branches together (especially when you cut and paste code into a new IF statement – the code comparison gets shuffled down considerably, making comparing the two changesets very difficult).

Thankfully, KDiff is a free tool which performs much better than the default tools (in my opinion).

You can download and install KDiff from here:

http://kdiff3.sourceforge.net/

Once you have installed Kdiff, it is now time to configure TFS.

Go to Tools -> Options:

Options

Go to Source Control -> Visual Studio Team Foundation Server -> Configure User Tools:

Configure User Tools

You will now want to add two new operations for comparing and merging.

Note, in the following picture examples, replace ‘C:\Program Files\KDiff3’ with the path where you have installed KDiff.


Compare operations

Compare Operator

Note, the arguments are:

%1 –fname %6 %2 –fname %7

Merge operations

Merge Operator

Note, the arguments are:

%3 –fname %8 %2 –fname %7 %1 –fname %6 -o %4

That should be it.  This will now ensure that TFS will use the KDiff tool when comparing any type of file.  Note, you can change these operations to be specific to certain code files (instead of an ‘.*’ extension, you could use ‘.vb’,  for example)

If you would like more information on the arguments used or use a different comparison tool, please read the following informative post:

http://blogs.msdn.com/b/jmanning/archive/2006/02/20/diff-merge-configuration-in-team-foundation-common-command-and-argument-values.aspx

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in Team Foundation Server, Visual Studio | 2 Comments »

Click Once Application Error – The signer’s certificate is not valid for signing

Posted by Stefan Zvonar on November 17, 2010

Problem:

When trying to publish a Click Once application, you recieve the following error:
“The signer’s certificate is not valid for signing.”
Reason:
This is most likely due to the fact that the certificate used to publish the application originally has expired.  Most certificates have a lifespan of about a year, so it needs updating now and then, especially when publishing new versions of the application.

Solution:
To get around this problem, you need to create a new certificate.
Open your project in Visual Studio and go to the Project menu -> Project Properties.  Click on the Signing tab and click on the “Create Test Certificate” button (as shown in the image below).

Create Test Certificate

Create Test Certificate

I left the password blank, but if you do use a password, be sure to remember it a year later, or whenever you need to regenerate another certificate :)
This will place a ????.pfx file in your project.  This file contains the private and public key informaiton.  I simply removed the old file (backed it up first) and renamed my new generated file to the old file name.
You should now be able to publish your Click Once application.

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in .NET, Visual Studio | Leave a Comment »

Replacing all instances of a piece of text inside a SQL Server Database

Posted by Stefan Zvonar on November 12, 2010

So, have you ever had to replace a piece of text wherever it occured inside a SQL Server Database (without knowing where to even look)?  This can be a time consuming task, especially if you have a database with hundreds of tables and columns.

I had to perform this recently when a server moved to a new domain (changing all usernames etc).

Here is how you can make a quick start.  What this article will explain is how to generate the script which you can then use to perform the alteration (although of course you will need to review the resultant script, change it, test it and run at your own risk!)

First, open SQL Server Management Studio and connect to your database, creating a blank query window.  You will need to also click on the “Results to Text” button, like shown below.

Results to text

Results to text

Now copy and paste the below script into your new query window.  This script will perform the script generation, replacing all instances of ‘ABC’ with ‘XYZ’.  Here is where you change what string you are wanting to replace with its new value.

    SET NOCOUNT ON
    DECLARE @SearchStr varchar(100)
    DECLARE @ReplaceStr varchar(100)
    SET @SearchStr = 'ABC'
    SET @ReplaceStr = 'XYZ'

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @Counter int, @Exists int

    SET @TableName = ''
    SET @Counter = 0

    CREATE TABLE #StringFound
    (
     occurances varchar(1000),
     tableName varchar(1000),
     columnName varchar(1000)
    )

    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL
            BEGIN

                INSERT INTO #StringFound EXEC ('SELECT COUNT(*), ''' + @TableName + ''', ''' + @ColumnName + '''  FROM ' + @TableName + ' WHERE ' + @ColumnName + ' LIKE ''%' + @SearchStr + '%'' HAVING COUNT(*) > 0')
                SET @Counter = @Counter + @@ROWCOUNT

            END
        END
    END

    SELECT 'EXEC sp_MSforeachtable ''ALTER TABLE ? DISABLE TRIGGER ALL'''

    SELECT 'UPDATE [' + DB_NAME() + '].' + tableName + CHAR(13) + CHAR(10) +
           'SET ' + columnName + ' = REPLACE(' + columnName + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''')' + CHAR(13) + CHAR(10) +
           'GO' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
    FROM #StringFound
    ORDER BY tableName, columnName

    SELECT 'EXEC sp_MSforeachtable ''ALTER TABLE ? ENABLE TRIGGER ALL'''

    DROP TABLE #StringFound

    --PRINT CAST(@Counter AS varchar) + ' occurence(s)'

    SET NOCOUNT OFF

Simply execute the query and view the results.  Here is an example of the output script:

----------------------------------------------------------
EXEC sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL'

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UPDATE [TEMP_DATABASE].[dbo].[SIMPLE_NAME]
SET [FIRST_NAME] = REPLACE([FIRST_NAME], 'ABC', 'XYZ')
GO

UPDATE [TEMP_DATABASE].[dbo].[SIMPLE_NAME]
SET [LAST_NAME] = REPLACE([LAST_NAME], 'ABC', 'XYZ')
GO

UPDATE [TEMP_DATABASE].[dbo].[SIMPLE_NAME]
SET [USERNAME] = REPLACE([USERNAME], 'ABC', 'XYZ')
GO

---------------------------------------------------------
EXEC sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL'

As stated previously, never run this straight onto your database without testing and verifying the results.  You will also probably want to fine tune the script so that its updates are more precise (adding in WHERE clauses to keep the changes more precise).  However, this should give you a good place to start and see what tables and columns you need to look for!

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in SQL Server | Leave a Comment »

Disable all triggers for a database

Posted by Stefan Zvonar on October 4, 2010

Here is a nice little bit of T-SQL that will help with your scripting woes.

Ever wanted to disable all triggers in a database so you can merrily import or merge data and other such tasks?

Well here is what you can do, it simply disables all triggers for all tables in your active database and then enables them again at the end of your changes.


----------------------------------------------------------
EXEC sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL'
----------------------------------------------------------

-- Write some SQL Modifications here

---------------------------------------------------------
EXEC sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL'
---------------------------------------------------------

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in SQL Server | Leave a Comment »

Save and retrieve images / documents into SQL Server using ASP.NET

Posted by Stefan Zvonar on August 22, 2010

In this article I will explain how to save and retrieve VARBINARY(MAX) data into SQL Server using ASP.NET.  You may opt to do this to store images or documents into the database.

So, let us start at the database level.  Below is a simplistic table definition for storing our files into a table:

CREATE TABLE [dbo].[tb_File](
    [FileID] [int] IDENTITY(1,1) NOT NULL,
    [FileName] [varchar](255) NOT NULL,
    [FileData] [varbinary](max) NOT NULL,
    [FileContentType] [varchar](255) NOT NULL,
 CONSTRAINT [PK_TB_FILE] PRIMARY KEY CLUSTERED
(
    [FileID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

And here are two simple stored procedures to save and retrieve the file data:

CREATE PROCEDURE dbo.usp_File_Get
(
     @FileID int
)

AS

BEGIN

    SET NOCOUNT ON

    SELECT FileID
      ,[FileName]
      ,FileData
      ,FileContentType
    FROM tb_File
    WHERE FileID = @FileID
   SET NOCOUNT OFF

END
GO

And

CREATE PROCEDURE dbo.usp_File_Insert
( 
     @FileName varchar(255),
     @FileData varbinary(max),
     @FileContentType varchar(255)
)

AS

BEGIN

    SET NOCOUNT ON
  
    INSERT INTO tb_File ([FileName], FileData, FileContentType)
    VALUES (@FileName, @FileData, @FileContentType) 
    SET NOCOUNT OFF

END
GO

Now that we have the database objects in place, lets create a basic maintenance web page to be able to upload a file and save it to the database:

Markup:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Upload file to database</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                File Name:
            </div>
            <div>
                <asp:TextBox runat="server" ID="txtFileName"></asp:TextBox>
            </div>
            <br />
            <div>
                File:
            </div>
            <div>
                <asp:fileupload runat="server" id="uplFile" />
            </div>
            <br />
            <div>
                <asp:button ID="btnSave" runat="server" text="Save" OnClick="btnSave_Click" />
            </div>
        </form>
    </body>
</html>

Code-Behind:

 Partial Class _Default
    Inherits System.Web.UI.Page

    Private m_strFileName, m_strFileContentType As String
    Private m_intFileLen As Integer
    Private m_byteFileData As Byte()

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)

        GetFileData()
        SaveData()

    End Sub

    Private Sub GetFileData()

        Dim myFile As HttpPostedFile = uplFile.PostedFile
        m_strFileName = System.IO.Path.GetFileName(uplFile.FileName)
        m_strFileContentType = myFile.ContentType
        m_intFileLen = myFile.ContentLength
        m_byteFileData = Nothing

        ' make sure the size of the file is > 0
        If m_intFileLen > 0 Then
            ' Allocate a buffer for reading of the file
            m_byteFileData = New Byte(m_intFileLen - 1) {}

            ' Read uploaded file from the Stream
            myFile.InputStream.Read(m_byteFileData, 0, m_intFileLen)

        End If

    End Sub

    Private Sub SaveData()

        Dim conSQL = New SqlClient.SqlConnection
        conSQL.ConnectionString = "Your database connection string"
        conSQL.Open()

        Dim comSQL As New SqlClient.SqlCommand()

        With comSQL

            .CommandText = "dbo.usp_File_Insert"
            .Connection = conSQL
            .CommandType = CommandType.StoredProcedure
            .Parameters.AddWithValue("@FileName", m_strFileName)

            .Parameters.Add("@DocData", SqlDbType.VarBinary, -1)   ' Need to set size to -1 since it is varbinary(max)
            If m_byteFileData Is Nothing Then
                .Parameters("@DocData").Value = System.DBNull.Value
            Else
                .Parameters("@DocData").Value = m_byteFileData
            End If

            .Parameters.AddWithValue("@DocContentType", m_strFileContentType)
            .ExecuteNonQuery()
        End With

        conSQL.Close()
        conSQL.Dispose()

    End Sub

End Class

Now lets look at how we can view the stored binary data through ASP.NET. Below we have a simple handler that is passed a File ID as a Querystring. It will look up the ID in the database and then write the object out as a byte stream.

<%@ WebHandler Language="VB" Class="FileHandler" %>
Imports System
Imports System.Web
Imports System.Web.Services

Public Class FileHandler
    Implements System.Web.IHttpHandler

    Private m_strFileContentType As String = String.Empty
    Private m_objFileData As Object
    Private m_intFileID As Integer

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property


    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        GetData(context)
        ShowFile(context)

    End Sub

    Private Sub GetData(ByVal context As HttpContext)

        If context.Request.QueryString("ID") IsNot Nothing AndAlso context.Request.QueryString("ID").Trim() <> String.Empty AndAlso IsNumeric(context.Request.QueryString("ID").Trim()) Then
            m_intFileID = CInt(context.Request.QueryString("ID").Trim())

            Dim conSQL = New SqlClient.SqlConnection
            conSQL.ConnectionString = "Your database connection string"
            conSQL.Open()

            Dim comSQL As New SqlCommand("dbo.usp_File_Get")
            comSQL.Connection = conSQL
            comSQL.Parameters.AddWithValue("@FileID", m_intFileID)
            comSQL.CommandType = CommandType.StoredProcedure

            'read record from database
            Dim drdDrillInstructions As SqlDataReader
            drdDrillInstructions = comSQL.ExecuteReader()
            Try
                If (drdDrillInstructions.HasRows) Then
                    While drdDrillInstructions.Read()
                        m_strFileContentType = drdDrillInstructions.Item("FileContentType").ToString()
                        m_objFileData = drdDrillInstructions.Item("FileData")
                    End While
                End If
            Catch ex As Exception
                ' Publish error here
            Finally
                If Not drdDrillInstructions.IsClosed Then
                    drdDrillInstructions.Close()
                End If
                conSQL.Close()
                conSQL.Dispose()
            End Try
        End If

    End Sub

    Private Sub ShowFile(ByVal context As HttpContext)

        ' Clear out the existing HTTP header information
        context.Response.Expires = 0
        context.Response.Buffer = True
        context.Response.Clear()

        If m_objFileData IsNot Nothing AndAlso (Not DBNull.Value.Equals(m_objFileData)) Then
            context.Response.ContentType = m_strFileContentType
            context.Response.BinaryWrite(DirectCast(m_objFileData, Byte()))
        Else
            context.Response.Write("<html><body bgcolor='#D6EBFF'><p align='center'><br /><br /><br /><br /><br />")
            context.Response.Write("<font class='text'>(No file available)</font>")
            context.Response.Write("</p></body></html>")
        End If

    End Sub

End Class

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in .NET, ASP.NET, SQL Server | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.