Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Visual Studio .NET » Automatic SQL Server Backup Utility using Sqlserver Agent

Automatic SQL Server Backup Utility using Sqlserver Agent

It is a sample C# (VS2005) application for Automatic Sql server Backup Utility using sqlserveragent. I have used SQL-DMO dll. This article will show you how to create a automatic backup in Sql server 2000.

Page Views : 38169
Downloads : 776
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
dbMaintain.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

It is a sample C# (VS2005) application for Automatic Sql server Backup Utility using sqlserveragent. I have used SQL-DMO dll. This article will show you how to create a automatic backup in Sql server 2000.

This code should work on any PC use VB.NET and installed SQL Server 2000 (any edition or Client Components for SQL Server 2000.

SQLDMO (Which installed always bt MS SQL Server 2000 or MS SQL Server Client Tools

To do:

  1. First enter your SQL Server username and password on corresponding Text Box.
  2. Set backup Start date & Backup Time
  3. After Finishing this then please check manually it will working or not
  4. Manual working procedure:
    1. Run Sql sever enterprise Manager
    2. Select management Option
    3. Open Sql server agent
    4. Open Jobs window
    5. Check whether job item exist or not
    6. Right click on newly created job item then, we will get one
    7. Popup menu, then select start job
    8. After finish the job then check folder "D:\backup" bkp file created or not

Add reference to SQL-DMO dll

You can do this by right clicking the project in Solution Explorer, then selecting 'Add Reference', COM components and the latest version of "Microsoft SQLDMO Object Library".

Available Server

public void dIsplayServerList(ComboBox cboListName)

{

    try

    {

        SQLDMO.Application oSQLServerDMOApp = new SQLDMO.Application();

        Info.informationLayer info = new Info.informationLayer();

                

        SQLDMO.NameList oNameList;

        oNameList = oSQLServerDMOApp.ListAvailableSQLServers();

        for (int intIndex = 0; intIndex <= oNameList.Count - 1; intIndex++)

        {

            if (oNameList.Item(intIndex as object) != null)

            {

                cboListName.Items.Add(oNameList.Item(intIndex).ToString());

            }

        }

        if (cboListName.Items.Count > 0) cboListName.SelectedIndex = 0;

        else cboListName.Text = "(Local)";

        }

    catch

    {

}

}

 

Available databases 

 

public void dIsplayDatabases(ComboBox cboDatabase,Info.informationLayer info)

{

    try

    {

        SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();

 

        cboDatabase.Items.Clear();

        SQLServer.Connect(info.strServerName,info.strLoginName,info.strPwd);

        foreach (SQLDMO.Database db in SQLServer.Databases)

        {

            if (db.Name != null)

                cboDatabase.Items.Add(db.Name);

        }

        cboDatabase.Sorted = true;

        if (cboDatabase.Items.Count == 0)cboDatabase.Text = "<No databases found>";

    }

    catch (Exception err)

    {

        info.ErrorMessageDataLayer = err.Message;

    }

}

 

Create Job on Server Agent: 

 

public void CreateJob_Sql(Info.informationLayer info)

{

    try

    {

        SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();

        SQLDMO.Job SQLJob = new SQLDMO.Job();

        SQLDMO.JobSchedule SQLSchedule = new SQLDMO.JobSchedule();

 

        SQLServer.Connect(info.strServerName, info.strLoginName, info.strPwd);

 

        switch (SQLServer.JobServer.Status)

        {

            case SQLDMO_SVCSTATUS_TYPE.SQLDMOSvc_Stopped:

            SQLServer.JobServer.Start();

            SQLServer.JobServer.AutoStart = true;

            break;

        }

 

        SQLJob.Name = info.strDatabaseName;

        SQLJob.Description = "Check and Backup" + info.strDatabaseName;

 

        SQLServer.JobServer.Jobs.Add(SQLJob);

        SQLJob.Category = "Database Maintenance";

 

        SQLDMO.JobStep aJobStep = new SQLDMO.JobStep();

 

        aJobStep.Name = "Step 2: Backup the Database";

        aJobStep.StepID = 1;

 

        aJobStep.DatabaseName = info.strDatabaseName;

 

        aJobStep.SubSystem = "TSQL";

        //------>>> If BackUp Folder is Not Found then create BackUp Folder.

                                   

        string   DirectoryName = "D:\\BackUp";

        if (Directory.Exists(DirectoryName)==false)

        {

            System.IO.Directory.CreateDirectory(DirectoryName);

        }

        //------>>>

        string sExt;

        sExt="EXEC master.dbo.xp_sqlmaint '-S " + info.strServerName + " -U " + info.strLoginName + " -P " + info.strPwd + "  -D " + info.strDatabaseName + " -CkDB -CkAl -CkCat -BkUpMedia DISK -BkUpDB D:\\Backup  -BkExt BAK -DelBkUps 2weeks -BkUpOnlyIfClean -Rpt D:\\Backup\\BackDB_Checks.txt'";

        aJobStep.Command = sExt;

        aJobStep.OnSuccessAction = SQLDMO_JOBSTEPACTION_TYPE.SQLDMOJobStepAction_QuitWithSuccess;

        aJobStep.OnFailAction = SQLDMO_JOBSTEPACTION_TYPE.SQLDMOJobStepAction_QuitWithFailure;

        SQLJob.JobSteps.Add(aJobStep);

        SQLJob.ApplyToTargetServer(info.strServerName);

        aJobStep.DoAlter();

        SQLJob.Refresh();

        aJobStep.Refresh();

 

    }

    catch (Exception Err)

    {

        info.ErrorMessageDataLayer = Err.Message;

    }

}

 

Create Job shedule on  server Agent: 

 

public void CreateShedule_Sql(Info.informationLayer info)

{

    try

    {

        //it will take bkp every week 2 day

        SQLDMO.Job SQLJob = new SQLDMO.Job();

 

        SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();

        SQLDMO.JobSchedule SQLSchedule = new SQLDMO.JobSchedule();

 

        SQLServer.Connect(info.strServerName, info.strLoginName, info.strPwd);

        SQLJob = SQLServer.JobServer.Jobs.Item(info.strDatabaseName);

 

        // create a new JobSchedule object

        SQLSchedule.Name = "Weekly Backup";

        SQLSchedule.Schedule.FrequencyType = SQLDMO.SQLDMO_FREQUENCY_TYPE.SQLDMOFreq_Weekly;

        SQLSchedule.Schedule.FrequencyInterval = 2;

        SQLSchedule.Schedule.FrequencyRecurrenceFactor = 2;

 

        // // start on Feb18, 2000 - at 12.55

        SQLSchedule.Schedule.ActiveStartDate = info.intStartDate;

        SQLSchedule.Schedule.ActiveStartTimeOfDay = info.intStartTime;

        ////  this schedule has no end time or end date

 

        SQLSchedule.Schedule.ActiveEndDate = 99991231;

        SQLSchedule.Schedule.ActiveEndTimeOfDay = 235959;

 

        ////  add the schedule to the Job

        SQLJob.BeginAlter();

        SQLJob.JobSchedules.Add(SQLSchedule);

        SQLJob.DoAlter();

        //SQLJob.JobSchedules.Refresh();

        info.ErrorMessageDataLayer = "New Sql Job [Databasename= " + info.strDatabaseName + " ]Sucessfully Created.  ";

    }

    catch (Exception err)

    {

        info.ErrorMessageDataLayer = err.Message;

    }

}

 

Syntax (SQL Server 2000)


xp_sqlmaint 'switch_string'
[
    [-S server_name[\instance_name]]
    [-U login_ID [-P password]]
    {
        [ -D database_name | -PlanName name | -PlanID guid ]
        [-Rpt text_file]
        [-To operator_name]
        [-HtmlRpt html_file [-DelHtmlRpt <time_period>] ]
        [-RmUnusedSpace threshold_percent free_percent]
        [-CkDB | -CkDBNoIdx]
        [-CkAl | -CkAlNoIdx]
        [-CkCat]
        [-UpdOptiStats sample_percent]
        [-RebldIdx free_space]
        [-WriteHistory]
        [
            {-BkUpDB [backup_path] | -BkUpLog [backup_path] }
            {-BkUpMedia
                {DISK [    [-DelBkUps <time_period>]
                            [-CrBkSubDir ] [ -UseDefDir ]
                         ]
                | TAPE
                }
            }
            [-BkUpOnlyIfClean]
            [-VrfyBackup]
        ]
    }
]
 
time_period
number[minutes | hours | days | weeks | months]
 
Syntax (SQL Server 7.0)


sqlmaint
[-?] |
[
    [-S server]
    [-U login_ID [-P password]]
    {
        [ -D database_name | -PlanName name | -PlanID guid ]
        [-Rpt text_file [-DelTxtRpt <time_period>] ]
        [-To operator_name]
        [-HtmlRpt html_file [-DelHtmlRpt <time_period>] ]
        [-RmUnusedSpace threshold_percent free_percent]
        [-CkDB | -CkDBNoIdx]
        [-CkAl | -CkAlNoIdx]
        [-CkTxtAl]
        [-CkCat]
        [-UpdSts]
        [-UpdOptiStats sample_percent]
        [-RebldIdx free_space]
        [-WriteHistory]
        [
            {-BkUpDB [backup_path] | -BkUpLog [backup_path] }
            {-BkUpMedia
                {DISK [    [-DelBkUps <time_period>]
                            [-CrBkSubDir ] [ -UseDefDir ]
                         ]
                | TAPE
                }
            }
            [-BkUpOnlyIfClean]
            [-VrfyBackup]
        ]
    }
]

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Joshy George
Joshy George , has over 5 years in Microsoft technologies. Certified Microsoft Professional with Master Degree in Computers. Working with Infogenie ITAS Pvt.Ltd,Infopark,Kochin,India, as a Sr.Software Engineer and have good experience in C#,ASP.net ,VB, ASP, SQL Server, smart card application,Tapii,Com ctrls.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Job Scheduler is not runnable by Deepak On September 16, 2009
Hi , 
Thank for this article. I did follow the same. Job is created everything is created successfully but when I see this job in Job Activity monitor it's next run date is coming null and Runnable option is coming No. If I create a job manully through wizard the next date is populating and runnable is yes. Can you please help me to figure out this as I waste complete one day for this.
Thanks in Advance
Reply | Email | Modify 
Job Scheduler is not runnable by Deepak On September 16, 2009
Hi , 
Thank for this article. I did follow the same. Job is created everything is created successfully but when I see this job in Job Activity monitor it's next run date is coming null and Runnable option is coming No. If I create a job manully through wizard the next date is populating and runnable is yes. Can you please help me to figure out this as I waste complete one day for this.
Thanks in Advance
Reply | Email | Modify 
Regret by amol On October 5, 2010
Thanks for Code Project...
Reply | Email | Modify 
HI by Nirav On December 13, 2010
I tried the code but I am getting error at "SQLServer.JobServer.Start();" , that the service is disabled...error 1058. PLease note that I need to take backup for SQLServer 2008 database. I tried to search and resolve this issue, but no luck so far. Every FOrum talks about some or the other registry file BUt I am not having those files in registry..can you please help. Thanks
Reply | Email | Modify 
Thanks. by Watcharakorn On May 22, 2011
Thanks, I will test it.
Reply | Email | Modify 
What is the point of doing a backup utility when SQL Agent is available. by Alex On July 21, 2011
If SQL Agent is available, why don't you just create a backup job and schedule it. Even in situations when there are no SQL Agent like MSDE or SQL Express editions, there many tools available to do that. By googling SQL Backup I find many of them like this http://sqlbackupandftp.com, it is very simple to use, you can backup several databases at a time, and has a scheduler automates backups for you.
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.