asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

ASP AND SQL-DMO - Part 2
By S.S. Ahmed
Rating: 3.5 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    Please refer to the Part 1 of this article published on www.15seconds.com. The URL is http://www.15seconds.com/Issue/001030.htm.

    I suggest reading the first edition of this article before going through this one. The major details of the SQL-DMO are discussed in the Part 1.

  • Download supporting code

    The SQL Distributed Management Objects (SQL-DMOs) are OLE automation-compatible COM objects. These objects and a set of properties and methods are used to write programs to administer multiple SQL Servers distributed across a network. Also, SQL-DMO is the foundation of SQL Enterprise Manager. In fact, SQL-DMO is a very powerful object model of SQL Server management. The obvious advantage of using a component encompassing SQL-DMO functionality is that you can manage your SQL Server from anywhere in the world.

    In this article, we have now upgraded the component to be used with SQL Server 7.0. The code in the previous article worked only with version 6.5 of the SQL Server. More enhancements are made in the new component. This new component is capable of deleting the task automatically once the task has been accomplished. In the previous version, the task once created has to be removed manually by executing a method called RemoveTask, but there is no need for such a method in the new component because it will delete the task upon successful completion. Furthermore, the task initially was executed each time a specific date was reached, but now the task will execute only once at a specific date the user will supply to the component. Also, we have demonstrated how to add two steps in the same job. In the previous article, the job consisted of only one step, but the new tasks created with the new component shall consist of more than one job step. The user can accomplish more than one job within the same task.

    The Code

    Let's review the code step by step:

    
    Private Sub Class_Initialize()
        
        On Error Resume Next
        
        NL = Chr$(13) & Chr$(10)
            
        Set oSQLServer = New SQLDMO.SQLServer
        
        oSQLServer.LoginTimeout = 10
        
    End Sub
    
    
    The main object is created when the class is initialized. Similarly this object shall be deleted from memory when the class is terminated.

    Our main method is known as AddTask. This method will add a new task to the task scheduler. Note we have not passed the parameters directly to function, instead we have used the properties to get the input from the user.

    
    Public Function AddTask()
    
    
        On Error GoTo errhandler
            
        oSQLServer.DisConnect
    
    Disconnect the server if it's already connected. 
            
        If Server = "" Then
            ErrDesc = "You must enter server name."
            Exit Function
        ElseIf UserID = "" Then
            ErrDesc = "You must enter a valid User ID"
            Exit Function
        ElseIf Password = "" Then
            Password = ""
        End If
    
    
    Get the values of important parameters from the user. These values are needed to connect to the SQL Server.
    
        'Connect to the server!
        oSQLServer.Connect CStr(Server), CStr(UserID), CStr(Password)
        
        Dim oJob As New SQLDMO.Job
        Dim idStep As Integer
    
    
    IdStep will be used to define the total number of steps to be included in the task.
    
        'Set the schedule name
        oJob.Name = JobID
    
    
    Assign a name to the job.
    
        'objSQLServer.Executive.Tasks.Add oJob
        oSQLServer.JobServer.Jobs.Add oJob
    
    
    Add the newly created job to the job server. The jobserver object exposes attributes associated with the SQL Server agent. The SQL Server agent is responsible for executing the scheduled jobs and notifying operators of SQL Server error conditions or other SQL Server execution or job states.
    
        'Use the code below to change the task!!!
        oJob.BeginAlter
        
        'idStep = 0
    
    
    Initially we have assigned a zero value to the step id. Because we intend to add two steps to our task, we run the following loop.
    
        For idStep = 0 To 2
            
            Dim oJobStep As SQLDMO.JobStep
            Set oJobStep = New SQLDMO.JobStep
    
    
    We have created a new job step object in the statements above. The JobStep object exposes the attributes of a single SQL Server agent executable job step. SQL Server Agent jobs contain one or more execution units called "steps." Each job step contains a textual command, a type of execution that specifies command interpretation, and logic that determines the behavior of the job if the step succeeds or fails.
            
            idStep = idStep + 1
            
            oJobStep.Name = JobID & idStep
            oJobStep.StepID = idStep
            
            'Set the job step executable subsystem.
            oJobStep.SubSystem = "TSQL"
    
    
    The SubSystem property specifies the SQL Server Agent execution subsystem used to interpret job step task-defining text.
               
            If DatabaseName <> "" Then
               oJobStep.DatabaseName = DatabaseName
            Else
                oJobStep.DatabaseName = "yourdatabase"
            End If
    
    
    If the user fails to pass the database name from the front end, then the component will pick up the hard-coded database name provided that you have hard-coded the database name in your code.
           
            If idStep = "1" Then
                If CommandText <> "" Then
                    oJobStep.Command = CommandText
                Else
                    oJobStep.Command = "select * from table1"
                    oJobStep.OnSuccessAction = SQLDMOJobStepAction_GotoNextStep
                End If
            Else
            
                oJobStep.StepID = 2
                If Commandtext2 <> "" Then
                    oJobStep.Command = Commandtext2
                Else
                    oJobStep.Command = "delete from table2"
                    oJobStep.OnSuccessAction = SQLDMOJobStepAction_QuitWithSuccess
                End If
           End If
     
    
    We have added two commands to the jobs, one will return all the records from the table and the second will delete all the records from the particular table. This has been done just to give you an example. You can do whatever you want with your database tables by passing the command text either from the front end or by hard-coding the command text in the code as seen above.
    
            oJob.JobSteps.Add oJobStep
        Next
    
    
    Add the individual job step to the JobSteps collection.
    
        'Set the Target Server
        oJob.ApplyToTargetServer (CStr(Server))
    
    
    The ApplyToTargetServer method adds an execution target to the list of targets maintained for the referenced SQL Server Agent job.

    Now, here comes the important part, the scheduling of the job. The job has been created, but now we have to schedule the job so that it runs at a specific date and time. The JobSchedule object exposes the attributes of a single SQL Server Agent executable job schedule.

    
        Dim oJobSchedule As SQLDMO.JobSchedule
        
        Set oJobSchedule = New SQLDMO.JobSchedule
        
        'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        'Schedule the task!
        'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
    
    You can calculate any time and date for your task to start executing. It solely depends on your choice or requirement. We have calculated the year, month, and day separately.
    
        Dim startyear, startmonth, startday
        
        'Indicate execution scheduled for every day by using
        'the FrequencyType and FrequencyInterval properties.
        oJobSchedule.Name = JobID
        oJobSchedule.Schedule.FrequencyType = SQLDMOFreq_OneTime
    
    
    We want to execute the task only once so we have set the frequency type to one time.
        
        'Set the ActiveStartDate to indicating the date on
        'which the schedule becomes active. Start date is
        'today's date
        
        Dim mydate
        mydate = DateAdd("h", CInt(Num_Of_Hours), Now())
            
        Dim hr, min, sec
        hr = Hour(mydate)
        min = Minute(mydate)
        sec = Second(mydate)
        
        Dim mytime
        mytime = hr & min & sec
        
        startyear = DatePart("yyyy", mydate)
        startmonth = DatePart("m", mydate)
        startday = DatePart("d", mydate)
        
        If Len(startmonth) < 2 Then startmonth = "0" & startmonth
        If Len(startday) < 2 Then startday = "0" & startday
        
        oJobSchedule.Schedule.ActiveStartDate = startyear & startmonth & startday
    
    
    The ActiveStartDate property indicates the first effective date for a schedule.
    
        'Set the ActiveStartTimeOfDay property to indicate the
        'scheduled execution time on each day
        
        oJobSchedule.Schedule.ActiveStartTimeOfDay = mytime
    
    
    The ActiveStartTimeOfDay property indicates the start time for a certain day's schedule.
        
        'Indicate that the schedule never expires
        oJobSchedule.Schedule.ActiveEndDate = SQLDMO_NOENDDATE
        oJobSchedule.Schedule.ActiveEndTimeOfDay = SQLDMO_NOENDTIME
    
    
    Similarly, we have to provide the ActiveEndDate and time for the job. We have set these properties to "SQLDMO_NOENDDATE" and "SQLDMO_NOENDTIME" which means that the job will never expire until is executed.
       
        'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        'Add task to scheduler
        'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        
        oJob.JobSchedules.Add oJobSchedule
    
    
    Now here is the clever part -- how to remove the task from the scheduler automatically. There is a property named as DeleteLevel that controls post-execution processing for SQL Server Agent jobs.
    
        'Automatically delete job after successful completion
        oJob.DeleteLevel = SQLDMOComp_Success
     
    
    If the job is successful, then we delete the job from the scheduler.
    
        oJobStep.OnFailAction = SQLDMOJobStepAction_QuitWithFailure
        
        If SQLDMOJobStepAction_QuitWithFailure = True Then
            ErrDesc = "Failure"
        Else
            ErrDesc = "Success"
        End If
        
        oJob.StartStepID = 1
        
        'Alter the job
        oJob.DoAlter
        
        'Clear references to the created objects
        Set oJob = Nothing
        Set oJobStep = Nothing
        Set oJobSchedule = Nothing
        
        Exit Function
        
    errhandler:
        
        'Clear references to the created objects
        Set oJob = Nothing
        Set oJobStep = Nothing
        Set oJobSchedule = Nothing
        
        ErrDesc = "Failure: " & "'" & Err.Source & "'" & " " & Err.Number & " " & Err.Description
        
    End Function
    
    
    The rest of the code is similar to the code used in Part 1 of this article. It explains how to destroy the object when the class terminates. Compile the DLL and access the component either in your Visual Basic (VB) project or ASP code. It works fine and efficiently. You can customize the component to add more features or to change the functionality according to your own needs.

    Summary

    There is a difference between SQL OLE and SQL-DMO. The SQLOLE.DLL library comes with SQL Server 6.5, while the SQLDMO.DLL library comes with SQL Server 7.0. You will have to include the correct reference to the library. For this article, add the reference to the SQLDMO.DLL from the project menu.

    About the Author

    S.S. Ahmed is a senior software engineer in a software development company that specializes in Web application development. To contact Ahmed with questions or comments, e-mail him at ss_ahmed1@hotmail.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES