Thursday, January 28, 2021

SQL Compare SDK - schema snapshots with 2 lines of code

Using xSQL Software's SQL Compare SDK you can take snapshots of your database schema with just 2 lines of code - well, as you will see below, technically, there are a few extra lines of code needed to set things up, but you are only calling 2 methods, ReadSchema() and SaveToSnapshot():

using xSQL.Schema.Core;
using xSQL.Schema.SqlServer;
using xSQL.SchemaCompare.SqlServer;

namespace xSQL.Sdk.SchemaCompare.Examples
{
    class DatabaseSnapshot
    {
        /// <summary>
        /// Creates a snapshot for the AdventureWorks database
        /// </summary>
        public static void CreateSnapshot()
        {
            SqlServer server;
            SqlDatabase database;
            try
            {
                //--create the SQL Server object, connect using Windows authentication
                server = new SqlServer(@"(local)");

                //--create the database object
                database = server.GetDatabase("AdventureWorks");

                //--attach an event handler to SchemaOperation event in order to get progress information during the schema read
                database.SchemaOperation += new EventHandler<SchemaOperationEventArgs>(database_SchemaOperation);

                //--attach an handler to SnapshotOperation event to get snapshot feedback
                database.SnapshotOperation += new EventHandler<SnapshotOperationEventArgs>(database_SnapshotOperation);

                //--read the database schema
                database.ReadSchema();

                //--create the snapshot
                database.SaveToSnapshot(Path.Combine(@"C:\", database.GetDefaultSnapshotFilename()));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private static void database_SchemaOperation(object sender, SchemaOperationEventArgs e)
        {
            //--exclude verbose messages
            if (e.Message.MessageType != OperationMessageTypeEnum.Verbose)
                Console.WriteLine(e.Message.Text);
        }

        private static void database_SnapshotOperation(object sender, SnapshotOperationEventArgs e)
        {
            //--exclude verbose messages
            if (e.Message.MessageType != OperationMessageTypeEnum.Verbose)
                Console.WriteLine(e.Message.Text);
        }
    }
}

Download the SQL Compare SDK now and try for yourself. 

0 comments:

Post a Comment