THE SQL Server Blog Spot on the Web

Welcome to SQLblog.com - The SQL Server blog spot on the web Sign in | |
in Search

Andy Leonard

Andy Leonard is CSO of Linchpin People and SQLPeople, an SSIS Trainer, Consultant, and developer; SQL Server database and data warehouse developer, community mentor, engineer, and farmer. He is a co-author of SQL Server 2012 Integration Services Design Patterns. His background includes web application architecture and development, VB, and ASP. Andy loves the SQL Server Community!

  • Creating a Custom SSIS 2012 Task Series

  • Using Enterprise Data Integration Dashboards Recording Available

    The recording of the presentation Using Enterprise Data Integration Dashboards is now available!

    Enjoy!

    :{>

  • New Article: Stairway to SSIS 11!

  • New Article: Stairway to SSIS 10!

  • Free Webinar - Using Enterprise Data Integration Dashboards

    Join Kent Bradshaw and I as we present Using Enterprise Data Integration Dashboards Tuesday 11 Dec 2012 at 10:00 AM ET!

    If data is the life of the modern organization, data integration is the heart of an enterprise. Data circulation is vital. Data integration dashboards provide enterprise ETL (Extract, Transform, and Load) teams near-real-time status supported with historical performance analysis. Join Linchpins Kent Bradshaw and Andy Leonard as they demonstrate and discuss the benefits of data integration dashboards.

    Space is limited, so register today!

    :{>

     

    About Kent Bradshaw:Kent-Bradshaw
    Kent Bradshaw is a SQL Server database/ETL developer and database architect. His background is in Medicaid claims, public school, government, retail and insurance systems.  He was born in Richmond, Virginia and has remained in the area throughout his life.  He attended the University of Richmond where he received a Bachelor degree in Information Systems as well as an Associate degree in Public Administration.  In 2011, he founded Tudor Data Solutions LLC to pursue new development opportunities as well as join the family at Linchpin People.  Outside of work, Kent enjoys spending time with his family, road trips with his wife, playing golf and laughing at the non-stop antics of his dog (and office assistant), Llian the Goldendoodle.

     

    Andy-Leonard

    About Andy Leonard:
    Andy Leonard is CSO of Linchpin People, an SSIS Trainer and Consultant, SQL Server database and Integration Services developer, SQL Server data warehouse developer, community mentor, blogger, and engineer. He is a co-author of SSIS Design Patterns. His background includes Visual Basic and web application architecture and development and SQL Server 2000-2012.

    Changing the world, one career at a time.

    About Linchpin People:
    Linchpin People LLC exists to create generations of technology entrepreneurs who are true servant leaders. We desire to serve our customers with integrity and skill. We are here to help and we strive to infuse the Golden Rule and love of God into every aspect of our business. Call us crazy but our goal is to change the world, one career, and one person at time.

  • Presenting Loading Data Warehouse Partitions with SSIS 2012 at SQL Saturday DC!

    Join Darryll Petrancuri and I as we present Loading Data Warehouse Partitions with SSIS 2012 Saturday 8 Dec 2012 at SQL Saturday 173 in DC!

    SQL Server 2012 table partitions offer powerful Big Data solutions to the Data Warehouse ETL Developer. In this presentation, Darryll Petrancuri and Andy Leonard demonstrate one approach to loading partitioned tables and managing the partitions using SSIS 2012, and reporting partition metrics using SSRS 2012. Objectives

    • A practical solution for loading Big Data Fact tables (1B+ rows).
    • Learn more about SQL Server 2012 table partitioning.
    • Learn more about using SSIS Expression Language to generate dynamic SQL in SSIS 2012.

    I hope to see you there!

    :{>

     

    About Darryll Petrancuri:

    Darryll Petrancuri is a Data & Business Intelligence Architect for SPS Commerce. He has been in software development for over 30 years, working across a wide variety of industries and domains serving as a consultant, developer, architect, thought leader, visionary, mentor and instructor. His background in the Microsoft technology stack includes VB (from Classic 1.0 Beta & .Net), C#, SQL Server 6.5 - 2012 (Core, Reporting Services, Integration Services, Notification Services, Analysis Services), component, application, database, data warehouse and business intelligence architecture and development. He currently specializes in innovative data warehouse solutions architecture and development, leveraging custom metadata repositories and automation.

     

    About Andy Leonard:

    Andy Leonard is CSO of Linchpin People, an SSIS Trainer and Consultant, SQL Server database and Integration Services developer, SQL Server data warehouse developer, community mentor, blogger, and engineer. He is a co-author of SSIS Design Patterns. His background includes Visual Basic and web application architecture and development and SQL Server 2000-2012.

  • Presenting at the University of Virginia Tomorrow!

    I am honored to present SQL Server 2012 Design Patterns at the University of Virginia’s Local Support Partners Fall Conference 2012 tomorrow!

    :{>

  • A PASS Summit Blogger No More?

    … unless there is a public apology.

    The day began with disappointment as PASS bloggers were warned to remain silent or “there won’t be a bloggers table next year.” This was in response to last year’s tweets and posts from the bloggers table that PASS and their sponsors found disagreeable.

    I disagreed with some of the opinions of my fellow bloggers last year and their communication style differs from mine. But I respect their right to express their opinions in their communication style. PASS seems fine with bloggers expressing their opinions so long as neither the opinions and/or mode of expression are unacceptable to PASS and its sponsors. PASS wants the influence of bloggers, so long as it’s positive influence.

    Transparent? Not at all. Attempted censorship? A sophomoric attempt, but yes.

    I refuse to participate in blogging about the PASS Summit until PASS apologizes for this offensive behavior: namely, threatening – regardless of how weak the threat – members of the blogosphere. My limited influence is a package deal. PASS and its sponsors receive my praise when they do things I think are cool, and I reserve the right to point out deficiencies when and where I see them. My readers (both of them – Hi Mom!) expect honest opinions. And they will continue to get them. My fellow bloggers will continue to express their views in their style to their readership. I may disagree with them, but I will stand for their right to express themselves.

    PASS is dead wrong here, and they owe the SQL Server Community an apology for attempting to control the media.

    Andy
    7 Nov 2012
    Seattle

  • [Updated Again!] RedGate SQL Source Control and Team Foundation Service

    31 Oct 2012 Update 2: Microsoft made Team Foundation Service (formerly TFSPreview) public today!  – Andy

    31 Oct 2012 Update 1: SQL Source Control 3.1 is available! - Andy

    12 Oct 2012 Update: The SQL Source Control 3.1 update is currently unavailable. I will provide additional updates when this version is re-released. - Andy

    I am excited that RedGate’s SQL Source Control now supports connectivity to TFSPreview Team Foundation ServiceMicrosoft’s cloud-based Application Life Cycle Management portal. Buck Woody (Blog | @buckwoody) and I have written about TFSPreview (the test version of Team Foundation Service) at SQLBlog already:

    Microsoft’s commitment to cloudtech is strong and producing very cool features, in my humble opinion. It’s neat to see third-party vendors like RedGate providing connectivity to these features.

    Prerequisites

    SQL Source Control’s support for Team Foundation Service is new and there are software prerequisites at the time of this writing (Oct 2012):

    You must have these tools installed to use SQL Source Control 3.1 with Team Foundation Service.

    Setup Your Free Trial

    Navigate to the SQL Source Control download page:

    SNAG-0000
    Figure 1

    Download and install SQL Source Control 3.0.

    Once SQL Source Control 3.0 is installed, open SSMS 2012. Your environment should display the SQL Source Control page shown in Figure 2:

     SNAG-0001
    Figure 2

    Click the Help dropdown and click “Check for Updates…”:

    CheckForUpdates
    Figure 3

    At the time of this writing, you will find an available update from SQL Source Control 3.0 to version 3.1 as shown in Figure 4:

    SNAG-0003
    Figure 4

    Download the new version. You will need to shut down SSMS to install the update as shown in Figure 5:

    SNAG-0008
    Figure 5

    Once the update is installed, re-open SSMS 2012. Connect to an instance and select a database:

    SNAG-0012
    Figure 6

    Click the link labeled “Link database to source control”. When the Link to Source Control window displays, select the Team Foundation Server (TFS) Source Control System option. If you do not have the Team Explorer for Visual Studio 2012 client installed, you will receive the error displayed in Figure 7:

    SNAG-0013
    Figure 7

    If the Team Explorer for Visual Studio 2012 client is installed you will be presented with a screen similar to that shown in Figure 8:

     TFSFigure8
    Figure 8

    But you cannot yet use SQL Source Control with Team Foundation Service. First, click the link beneath the Server URL textbox that states “To link to TFS2012 or tfs.visualstudio.com, you must edit a config file. Learn more

     ConfigurationLink
    Figure 9

    Follow the link to the support page and then follow the instructions on the page. Open the RedGate_SQLSourceControl_Engine_EngineOptions.xml file as shown in Figure 10:

    SNAG-0021
    Figure 10

    Edit the file according to the instructions on the support page:


    ConfgifFileEdit
    Figure 11

    When complete (at the time of this writing), the file will appear similar to that shown in Figure 12:

    SNAG-0023
    Figure 12

    I set up SQL Source Control on a new Windows Server 2012 virtual machine, so there were a lot of default permissions in place. When attempting to connect with Team Foundation Service, I had to add several (~8) URLs to Trusted Sites. Even after that, I saw the Windows Live login screen appear briefly before being replaced by the message window in Figure 13:

    SNAG-0026
    Figure 13

    I closed this window and attempted to connect to Team Foundation Service once more and was successful, reaching the screen shown in Figure 14:

    SNAG-0029
    Figure 14

    After reaching my Team Foundation Service site, I clicked the Browse button to select a database folder as shown in Figure 15:

     TFSFigure15
    Figure 15

    I selected a Team Project (Demos) from my default collection of TFS Team Projects and created a folder named CloudDemo:

     TFSFigure16
    Figure 16

    Once the folder was created I could select it as shown in Figure 17:

     TFSFigure17
    Figure 17

    Returning to the Link to Source Control window, I see my selected Database folder:

     TFSFigure18
    Figure 18

    Click the Link button to start the Source Control Link process. A message balloon informs me the link is complete, as shown in Figure 19:

    image
    Figure 19

    The First Commit

    I see a visual indication the database is under SQL Source Control in the SSMS 2012 Object Explorer:

    image
    Figure 20

    Objects added to the database – like the RainDrops table shown in Figure 21 – are marked visually for Commit:

    image
    Figure 21

    The Commit Changes tab of the SQL Source Control window provides a space to enter version comments before performing the Commit operation as shown in Figure 22:

    image
    Figure 22

    When the Commit operation completes, SQL Source Control provides excellent feedback:

    SNAG-0048
    Figure 23

    Awesome!

    Conclusion

    Source-controlling code of any kind is important. Having the ability to store source code remotely is handy for many Application Life Cycle Management scenarios. tfs.visualstudio.com is constantly adding features to support developers practicing continuous (or continual) integration methodologies.

    I like the manner in which SQL Source Control approaches database source control. I especially like that when I log into the Source page of my project at Team Foundation Service, I see something that looks similar to Object Explorer:

     TFSFigure24
    Figure 24

    I admire the thought RedGate put into the design of SQL Source Control and believe the product is well-positioned to support database development now and – with the addition of tfs.visualstudio.com support – for the foreseeable future.

    :{>

  • Installing SQL Server 2012 on Windows 2012 Server

    In Want to Learn SQL Server 2012? I wrote about obtaining a fully-featured version of SQL Server 2012 (Developer Edition).

    This post represents one way to install SQL Server 2012 Developer Edition on a Hyper-V virtual machine running the Windows 2012 Server Standard Edition operating system. This is by no means exhaustive. My goal in writing this is to help you get a default instance of SQL Server 2012 up and running. I do not cover setting up the Hyper-V virtual machine. I begin after loading the SQL Server 2012 Developer Edition ISO file into the VM’s CD/DVD drive.

    Navigate to the installation drive folder. Right-click setup.exe and click “Run as administrator” as shown in Figure 1:

    Figure1
    Figure 1

    This starts the SQL Server Installation Center. Click the Installation page from the list on the left side, and then click the top link (“New SQL Server stand-alone installation or add features to an existing installation”):

    Figure2
    Figure 2

    Setup conducts eight checks for things that could interfere with a successful installation of SQL Server:

    Figure3
    Figure 3

    Next, enter the product key. If you are installing SQL Server 2012 Developer Edition, the value appears for you on the screen shown in Figure 4:

    Figure4
    Figure 4

    The next screen prompts you to accept the license terms. You can also opt to send anonymous feature usage data to Microsoft. I do this and recommend you do too. Why? Microsoft actually uses this data to qualify and prioritize future development efforts.

    Figure5
    Figure 5

    Setup checks for conditions that may interfere with the installation of setup support files:

    Figure6
    Figure 6

    You next select the setup role in the installation process. I like the option “All Features With Defaults,” as shown in Figure 7:

    Figure7
    Figure 7

    When you select the “All Features With Defaults” option, the next screen – Feature Selection – is prepopulated, as shown in Figure 8:

    Figure8
    Figure 8

    Setup next checks installation rules:

    Figure9
    Figure 9

    Figure 10 shows the next step in the process, SQL Server instance configuration:

    Figure10
    Figure 10

    Disk space calculations are next…

    Figure11
    Figure 11

    … followed by service account configuration:

    Figure12
    Figure 12

    Database engine configuration includes Authentication Mode and SQL Server Administrators. You can accept the defaults if you want. I use Mixed Mode Authentication (combined with very strong passwords) for my installations. Clicking the Add Current User button adds me to the SQL Server administrators, as shown in Figure 13:

    Figure13
    Figure 13

    Analysis Services setup is next. Although Figure 14 does not show it, I mostly work with Tabular Model these days. As before, I click the Add Current User button to add this account to the Administrators:

    Figure14
    Figure 14

    Accept the defaults for Reporting Services configuration as shown in Figure 15:

    Figure15
    Figure 15

    I haven’t used the Distributed Replay Client (DRC) yet, but it is on my list of SQL Server 2012 stuff to learn. I click the Add Current User button:

    Figure16
    Figure 16

    Give the DRC a name similar to the server name, as shown in Figure 17:

    Figure17
    Figure 17

    Select Error Reporting options as shown in Figure 18:

    Figure18
    Figure 18

    Installation configuration rules are checked for consistency and readiness, shown in Figure 19:

    Figure19
    Figure 19

    Figure 20 confirms the installation is ready to begin:

    Figure20
    Figure 20

    When the installation is complete, the Complete window displays as shown in Figure 21:

    Figure21
    Figure 21

    A bunch of new cool tiles appear on your Windows 2012 Server start page, as shown in Figure 22:

    Figure22
    Figure 22

    And you are done! Installation is complete and you are ready to begin exploring SQL Server 2012!

    :{>

  • Less Useful Soft Skills

    Introduction

    This post is the fifty-sixth part of a ramble-rant about the software business. The current posts in this series can be found on the series landing page.

    Over a career that spans decades, one encounters useful and “less useful” soft skills in the modern enterprise. I thought I would share a few of the less useful variety:

    Free Advice

    If someone asks another for advice, that’s a cool compliment. The person asking has seen something that compels them to seek information about how-another-does-or-sees-things. That’s different from someone offering unsolicited advice. Way different. In the first case, the individual asking is open to receive advice. This is often not the case with unsolicited advice.

    Anti-anti-pattern: Offer advice when asked.

    Retentiveness

    Best practices, formatting, case and capitalization are all excellent tools for assisting a developer to represent, support, and facilitate their thoughts and thought processes… until the attempted transfer to another developer. I hope you are seated before you read this next line: Not everyone thinks like you. (I know!) Moreover, not everyone wants to think like you. </shocker>. Others think in ways that facilitate their code development style. Their documentation – or lack thereof – is there (or not) because of their coding style. Some wait until the end of a development to begin code optimization (this is a recommended best practice, by the way) instead of optimizing each code fragment.

    Everyone – and I mean everyone – has a preferred method for representing code. I hear you thinking, “But their way doesn’t work for me.” It's. not. supposed. to. work. for. you. It’s supposed to work for them. Different != wrong.

    Anti-anti-pattern: Allow others to code in their style. If they observe your coding style and want your advice… see the section on free advice.

    Destructive Competition

    Wanting to be a better developer is a good thing. Wanting to be better than the developer in the next cubicle is not a good thing. The collective IQ of a team is greater than the collected IQs of the team members. Why? Synergy is the great entropy-buster, spawning positive cycles as team members interact – sans retentiveness. Synergy works best with a dash of humility, and humility facilitates an environment where team members freely seek the advice of each other. Communicating you are the smartest person on the team accomplishes the opposite: striking lines of communication, binding synergy, and destroying the cooperation that would induce a positive cycle. (This is why Performance-Based Management Stinks.)

    Anti-anti-pattern: Before acting or speaking ask yourself, “Will this help?” If the answer is not, “Yes, this will help,” don’t act or speak.

    :{>

  • Want to Learn SQL Server 2012?

    Or SSIS 2012? SSRS 2012? SSAS 2012? There’s no substitute for getting your hands on the product, in my opinion.

    I can hear you thinking, “But Andy, I can’t afford to purchase a copy of SQL Server 2012.” Are you sure? What if I told you that you can get a full-feature version of SQL Server 2012 Enterprise Edition for $50? Well, you cannot… it’s actually less than $50! SQL Server 2012 Developer Edition is available at Amazon on the day of this writing for $41.24USD. That’s about the price of eight cups of fancy coffee.

    SQL Server releases follow a cycle. SQL Server 2005 was a major release with big changes from SQL Server 2000. SQL Server 2008 and SQL Server 2008 R2 were not drastic departures from SQL Server 2005. Take it from me: SQL Server 2012 is a major release.

    Is taking your career to the next level worth the price of eight cups of coffee?

    :{>

  • Updates to Stairway to Integration Services

    The Stairway to integration Services has been updated! I added content to Step 1 to provide more detail about creating a first SSIS project and corrected a typo in Step 2 that referred to an older name for the Step 1 article. I also made the corrected Step 1 article name a link to help.

    Thanks to Steve Jones (blog | @way0utwest) for all his hard work editing and corralling trifling authors.

    :{>

  • SSIS Design Pattern: Producing a Footer Row

    imageThe following is an excerpt from SSIS Design Patterns (now available in the UK!) Chapter 7, Flat File Source Patterns. The only planned appearance of all five authors presenting on SSIS Design Patterns is the SSIS Design Patterns day-long pre-conference session at the PASS Summit 2012. Register today.

    Let’s look at producing a footer row and adding it to the data file. For this pattern, we will leverage project and package parameters. We will also leverage the Parent-Child pattern, which will be discussed in detail in another chapter. We are not going to build the package that creates a flat file containing data. We will start with the assumptions that an extract file exists and we know the number of rows and the extract date. We will use parameters to transmit metadata from the parent package to the child package. Let’s get started!

    Create a new SSIS package and name it WriteFileFooter.dtsx. Click on the Parameters tab and add the following parameters:

    Name

    Data Type

    Value

    Required

    AmountSum

    Decimal

    0

    FALSE

    DateFormat

    String

     

    TRUE

    Debug

    Boolean

    TRUE

    FALSE

    Delimiter

    String

    ,

    TRUE

    ExtractFilePath

    String

     

    TRUE

    LastUpdateDateTime

    DateTime

    1/1/1900

    TRUE

    RecordCount

    Int32

    0

    TRUE

    The parameters, when entered, appear as shown in Figure 7-20:

    image
    Figure 7-20. Parameters for the WriteFileFooter.dtsx Package

    The Sensitive property for each parameter is set to False. The Description is optional and available in the image.
    We’re going to do the heavy lifting in a Script Task. Return to the Control Flow and drag a Script Task onto the canvas. Change the name to “scr Append File Footer” and open the editor. On the Script page, click the ellipsis in the ReadOnlyVariables property’s value textbox. When the Select Variables window displays, select the following variables:
    •    System::PackageName
    •    System::TaskName
    •    $Package::AmountSum
    •    $Package::DateFormat
    •    $Package::Debug
    •    $Package::Delimiter
    •    $Package::ExtractFilePath
    •    $Package::LastUpdateDateTime
    •    $Package::RecordCount

    The Select Variables window will not appear exactly as shown in Figure 7-21, but these are the variables you need to select for use inside the “scr Append File Footer” Script Task:

    image
    Figure 7-21.Selecing Variables for the Footer File

    Click the OK button to close the Select Variables window. Set the ScriptLanguage property to Microsoft Visual Basic 2010. Click the Edit Script button to open the VstaProjects window. At the top of the ScriptMain.vb code window, you will find an “Import” region. Add the following lines to that region:

    Imports System.IO
    Imports System.Text

    Just after the Partial Class declaration, add the variable declaration for the bDebug variable (the Dim statement below):

    Partial Public Class ScriptMain
        Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase

    Dim bDebug As Boolean

    Replace the code in Public Sub Main with the following:

        Public Sub Main()

            ' 1: detect Debug setting...
            bDebug = Convert.ToBoolean(Dts.Variables("Debug").Value)

            ' 2: declare and initialize variables...
            ' 2a: generic variables...
            Dim sPackageName As String = Dts.Variables("PackageName").Value.ToString
            Dim sTaskName As String = Dts.Variables("TaskName").Value.ToString
            Dim sSubComponent As String = sPackageName & "." & sTaskName
            Dim sMsg As String
            ' 2b: task-specific variables...
            Dim sExtractFilePath As String = Dts.Variables("ExtractFilePath").Value.ToString
            Dim iRecordCount As Integer = Convert.ToInt32(Dts.Variables("RecordCount").Value)
            Dim sAmountSum As String = Dts.Variables("AmountSum").Value.ToString
            Dim sDateFormat As String = Dts.Variables("DateFormat").Value.ToString
            Dim sDelimiter As String = Dts.Variables("Delimiter").Value.ToString
            Dim sLastUpdateDateTime As String= _
    Strings.Format(Dts.Variables("LastUpdateDateTime").Value, sDateFormat) _
    '"yyyy/MM/dd hh:mm:ss.fff")
            Dim sFooterRow As String
            Dim s As Integer = 0

            ' 3: log values...
            sMsg = "Package Name.Task Name: " & sSubComponent & ControlChars.CrLf & _
    ControlChars.CrLf & _
                "Extract File Path: " & sExtractFilePath & ControlChars.CrLf & _
    ControlChars.CrLf & _
                "Record Count: " & iRecordCount.ToString & ControlChars.CrLf & _
    ControlChars.CrLf & _
                   "Amount Sum: " & sAmountSum & ControlChars.CrLf & ControlChars.CrLf & _
                   "Date Format: " & sDateFormat & ControlChars.CrLf & ControlChars.CrLf & _
                   "Delimiter: " & sDelimiter & ControlChars.CrLf & ControlChars.CrLf & _
                "LastUpdateDateTime: " & sLastUpdateDateTime & ControlChars.CrLf & _
    ControlChars.CrLf & _
                   "Debug: " & bDebug.ToString
            Dts.Events.FireInformation(0, sSubComponent, sMsg, "", 0, True)
            If bDebug Then MsgBox(sMsg)

            ' 4: create footer row...
            sFooterRow = iRecordCount.ToString & sDelimiter & sAmountSum & sDelimiter & _
    sLastUpdateDateTime
            ' 5: log...
            sMsg = "Footer Row: " & sFooterRow
            Dts.Events.FireInformation(0, sSubComponent, sMsg, "", 0, True)
            If bDebug Then MsgBox(sMsg)

            ' 6: check if the file is in use...
            While FileInUse(sExtractFilePath)
                ' 6a: if file is in use, sleep for a second...
                System.Threading.Thread.Sleep(1000)
                ' 6b: incrementor...
                s += 1
                ' 6c: if incrementor reaches 10 (10 seconds),
                If s > 10 Then
                    ' exit the loop...
                    Exit While
                End If 's > 10
            End While 'FileInUse(sExtractFilePath)
            ' 7: log...
            If s = 1 Then
                sMsg = "File was in use " & s.ToString & " time."
            Else ' s = 1
                sMsg = "File was in use " & s.ToString & " times."
            End If ' s = 1
            Dts.Events.FireInformation(0, sSubComponent, sMsg, "", 0, True)
            If bDebug Then MsgBox(sMsg)

            ' 8: if the file exists...
            If File.Exists(sExtractFilePath) Then
                Try
                    ' 8a: open it for append, encoded as built, using a streamwriter...
                    Dim writer As StreamWriter = New StreamWriter(sExtractFilePath, True, _
    Encoding.Default)
                    ' 8b: add the footer row...
                    writer.WriteLine(sFooterRow)
                    ' 8c: clean up...
                    writer.Flush()
                    ' 8d: get out...
                    writer.Close()
                    ' 8e: log...
                    sMsg = "File " & sExtractFilePath & " exists and the footer row has " & _
    "been appended."
                    Dts.Events.FireInformation(0, sSubComponent, sMsg, "", 0, True)
                    If bDebug Then MsgBox(sMsg)
                Catch ex As Exception
                    ' 8f: log...
                    sMsg = "Issue with appending footer row to " & sExtractFilePath & _
    " file: " & ControlChars.CrLf & ex.Message
                    Dts.Events.FireInformation(0, sSubComponent, sMsg, "", 0, True)
                    If bDebug Then MsgBox(sMsg)
                End Try
            Else
                ' 8g: log...
                sMsg = "Cannot find file: " & sExtractFilePath
                Dts.Events.FireInformation(0, sSubComponent, sMsg, "", 0, True)
                If bDebug Then MsgBox(sMsg)
            End If ' File.Exists(sExtractFilePath)

            '  9: return success...
            Dts.TaskResult = ScriptResults.Success

        End Sub

    Add the following function after Public Sub Main():

        Function FileInUse(ByVal sFile As String) As Boolean

            If File.Exists(sFile) Then
                Try
                    Dim f As Integer = FreeFile()
                    FileOpen(f, sFile, OpenMode.Binary, OpenAccess.ReadWrite, _
    OpenShare.LockReadWrite)
                    FileClose(f)
                Catch ex As Exception
                    Return True
                End Try
            End If
        End Function

    This script builds the footer row and appends it to the Extract file. The first thing we do – at the comment labeled 1 – is assign a value to the Debug variable. I use the Debug variable to control message boxes displaying variable values and other pertinent information. I describe why in the chapter on Execution Patterns.

    At comment 2, we declare and initialize variables. I break variables into two categories: generic and task-specific variables. At comment 3, we build a message in the variable sMsg. This message contains the values of each variable used in the Script thus far. If we are running in Debug mode (if bDebug is True), the code displays a message box (via the MsgBox function) containing the contents of sMsg. Whether we’re running in Debug Mode or not, I use the Dts.Events.FireInformation method to raise an OnInformation event, passing it the contents of sMsg. This means the information is always logged and is optionally displayed by a message box. I like options (a lot).

    Comment 4 has us constructing the actual footer row and placing its text in the String variable sFooterRow. Note the delimiter is also dynamic. The String variable sDelimiter contains the value passed to the WriteFileFooter into the Package Parameter named $Package::Delimiter. At comment 5, we log the contents of the footer row.

    At comment 6, we initiate a check to make sure the Extract File is not marked as “in use” by the operating system. There are many ways to detect the state of the file in the file system, so I created a Boolean function named FileInUse to encapsulate this test. If the function I created doesn’t work for you, you can construct your own. If the file is in use, the code initiates a While loop that sleeps the thread for one second. Each iteration through the loop causes the variable s (the incrementor in this example) to increment at comment 6b. If s exceeds ten, the loop exits. We will only wait 10 seconds for the file to be usable. Note that if the file remains in use at this juncture, we still move on. We'll deal with the file in use matter later, but we will not hang ourselves in a potentially endless loop waiting for the file’s availability. We will instead fail. Whether the file is in use or not in use, the script logs its state at comment 7.

    At comment 8, we check for the existence of the file and begin a Try-Catch. If the file doesn’t exist, I opt to log a status message (via Dts.Events.FireInformation) and continue (see comment 8g). The Try-Catch enforces the final test of the file’s usability. If the file remains in use here, the Catch fires and logs the status message at comment 8f. At 8f and / or 8g, you may very well decide to raise an error using the Dts.Events.FireError method. Raising an error causes the Script Task to fail, and you may want this to happen. At comments 8a through 8d, we open the file, append the footer row, close the file, and clean up. At comment 8e, the code logs a status message. If anything fails when executing 8a through 8e, code execution jumps to the Catch block.

    If all goes well, the code returns Success to the SSIS Control Flow via the Dts.TaskResult function (comment 9).
    The Script Task does all the work in this pattern.

    I created a test package called TestParent.dtsx to test this package. The package has variables that align with the parameters of the WriteFileFooter.dtsx package, as shown in Figure 7-22:

    image
    Figure 7-22. Variables in the TestParent.dtsx Package

    If you’re playing along at home, you should adjust the path of the ExtractFooterFilePath variable.
    I added a Sequence Container named “seq Test WriteFileFooter” and included an Execute Package Task named “ept Execute WriteFileFooter Package.” On the Package page of the Execute Package Task Editor, set the ReferenceType property to “Project Reference” and select WriteFileFooter.dtsx from the PackageNameFromProjectReference property dropdown. Map the TestParent package variables to the WriteFileFooter package parameters as shown in Figure 7-23:

    image
    Figure 7-23. Mapping Package Parameters

    Execute TestParent.dtsx to test the functionality. The package executes successfully and the footer row is appended to the file as shown in Figure 7-24:

    image
    Figure 7-24. Mission Accomplished


    Interesting stuff? I think so but I’m biased; I wrote it! You can get more in the SSIS Design Patterns book and by attending the SSIS Design Patterns day-long pre-conference session at the PASS Summit 2012.

    :{>

  • Step 9 of the Stairway to Integration Services is Live!

This Blog

Syndication

My Company


Other Blog

Check out my personal blog...
http://andyleonard.me

Contact Me

Twitter: @AndyLeonard
Email: andy.leonard@gmail.com

Powered by Community Server (Commercial Edition), by Telligent Systems
  Privacy Statement