.Net with SMO, Triggers, Tables and the Modified (Last Updated Date)

clock October 4, 2008 04:12 by author csmith12

Have you ever had a lot of tables in a database that needed to have the timestamp of the record updated on insert or update? I know I have. I wish I could find a really good tool for automating some of the database development tasks that I perform. Until then, I end up writing my own scripts or code.

This code utilizes the .Net SMO object model to automatically create triggers for tables that have an Modified datetime column.

Below you will see my code for adding triggers to a MS SQL server database. These triggers will update the "Modified" column in the table when a record is inserted or updated. Feel free to modify the code to fit your specific needs as it is common for the "Modified" column to be named differently per database/project.

Limits:

1. Table can only have one primary key column

Enjoy!

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace Pixelect.MsSql
{
    public class ModifiedDateTriggerGenerator
    {
        public void Process(string database)
        {
            // get connection string
            string conString = ConfigurationManager.ConnectionStrings["SqlServerConnectionString"].ConnectionString;

            // create sql connection
            SqlConnection sqlConnection = new SqlConnection(conString);

            // create server connection
            ServerConnection serverConnection = new ServerConnection(sqlConnection);

            // create server
            Server server = new Server(serverConnection);    

            // 
            if (server.Databases.Contains(database))
                AddModifiedTriggerToTables(server.Databases[database]);
            else
                throw new Exception("Database not found.");
        }

        private static void AddModifiedTriggerToTables(Database database)
        {
            foreach (Table table in database.Tables)
            {
                if(table.Columns.Contains("ModifiedDate"))
                {
                    // check if table already had trigger, drop it
                    if (table.Triggers.Contains(string.Format("trg{0}SetModifiedDate", table.Name)))
                        table.Triggers[string.Format("trg{0}SetModifiedDate", table.Name)].Drop();
                    
                    // set up trigger
                    Trigger trigger = new Trigger(table, string.Format("trg{0}SetModifiedDate", table.Name));
                    trigger.TextMode = false;
                    trigger.Insert = true;
                    trigger.Update = true;

                    // get trigger resource
                    string textBody = TriggerTemplate.ResourceManager.GetString("ModifiedDateTrigger");

                    // get template
                    if(string.IsNullOrEmpty(textBody))
                        throw new Exception("Unable to get Modified trigger template from resource.");

                    // swap values
                    textBody = textBody.Replace("[table]", string.Format("[{0}]", table.Name));
                    textBody = textBody.Replace("[schema]", string.Format("[{0}]", table.Schema));

                    // get primary key of table
                    List<Column> keys = GetPrimaryKeys(table);

                    // i.[primaryKey] = [schema].[table].[primaryKey]
                    string keyChain = string.Empty;
                    foreach (Column col in keys)
                        keyChain += string.Format("i.{0} = [{1}].[{2}].[{3}] AND ", col.Name, table.Schema, table.Name, col.Name);
                    
                    // replace body
                    keyChain = keyChain.Substring(0, keyChain.Length - 5);
                    textBody = textBody.Replace("[keys]", keyChain);
                    
                    // update body
                    trigger.TextBody = textBody;

                    // create trigger
                    trigger.Create();
                }
            }
        }

        private static List<Column> GetPrimaryKeys(Table table)
        {
            List<Column> keys = new List<Column>();

            foreach (Column c in table.Columns)
                if (c.InPrimaryKey) keys.Add(c);

            return keys;
        }
    }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Fun with JetBrains TeamCity

clock March 9, 2008 16:34 by author csmith12

A friend and I have been working with TeamCity from JetBrains for the past week. I must say that I am impressed with the application so far. I do have a couple of issues I am still working out, but all and all, its a killer continuous integration server for free. Here are just a few of the questions that I have not been able to figure out from reading the documentation so far;

  1. How do I get the build agents to build applications that contain 3rd party project references without installing them on the build server or where the build agent is installed? Am I missing something that is taken for granted here?
  2. Is there any plug-ins/add-on's that will deploy the compiled output (artifacts) to a staging server automatically?

If any experienced TeamCity users read this, please point me in the right direction.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Explorer Addin for Visual Studio

clock February 8, 2008 13:14 by author csmith12

Just wanted to post a link to a nice addin for visual studio 2005. This little addin will give you some easy browser and explorer tools right from the solution explorer. Check out the tool for yourself (http://www.codeproject.com/KB/cs/Explorer.aspx).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


My Development Environment

clock January 28, 2008 14:41 by author csmith12

I posted this on my old blog, but it somehow didn't get migrated to this new one. So I am posting again for those who asked.

Machine:
Dell Precision M70
CPU: P4
Mem: 2GB
HD: 100GB (10k RPM)
Dual 21'' LCDs running max resolution (1920x1200)

Software:
Visual Studio 2005
Visual Studio 2008
Jet Brains Reshareper (can't live without)
Reflector
NUnit (download the free jet brains unit test runner)
Explorer In windows Visual Studio Addin

 

I will add more to this list as well as links but, I am out of time.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


One step closer to SharePoint Development without SharePoint Designer

clock January 23, 2008 20:50 by author csmith12

I was browsing today and ran across this little nugget http://www.codeplex.com/spdevexplorer. I am still testing and have found it cannot edit all SharePoint types, but hey...

screen2.png

This allows for editing of SharePoint content and structure from within visual studio. Although SharePoint designer is not 100% bad, it leaves a lot to be desired.


Check it out for yourself.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Alt-Tab Replacement for Windows XP

clock January 15, 2008 14:34 by author csmith12

A friend of mine was sitting at my desk while I was working and seen me alt-tab. I have an alt-tab replacement installed from http://www.ntwind.com/taskswitchxp/.

TaskSwitchXP Start Panel style

This is pretty cool for Windows XP. So I thought I would share with everyone else.

 

Enjoy

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


TreeSize - Disk Usage Tool (Free)

clock January 13, 2008 18:16 by author csmith12

A couple of friends of mine have been downloading like mad. And not all of them are very technical pc users, but are downloading some very large files. So in order to help them out, I am linking a great tool to view the disk usage of your hard drive. http://www.jam-software.com/freeware/index.shtml 

TreeSize is an excellent tool for visualizing the usage your hard drive on a directory basis. The provides invaluable to non technical users who don't have all their downloads organized very well.

Special thanks to the guys/gals at Jam Software for making this tool free.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


News Reader

clock January 5, 2008 14:50 by author csmith12

I just thought I would share a free tool that I find enjoyable to use for downloading from news servers. Grabit from http://www.shemes.com/ is a very nice new reader and downloader that makes usage of news servers a breeze. And best of all, its free. The one thing it is missing a bandwidth throttle feature.

But I thought I would share for the few friends I have.

Enjoy and happy downloading,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


SVN Server Made Easy For Free

clock November 29, 2007 17:22 by author csmith12

I would like to take the time to thank the guys/gals over at VisualSVN for making a couple of really nice products. The one that hits today is SVN repo hosting. Some users use file:/// some use svn:/// others use apache or some form of http:/// to access the repos. But a lot of us just don't have the time to set up a secure, cert based https:/// access point to SVN repos. This is where http://www.visualsvn.com/server/ comes in.

  1. Simply download and install VisualSVN Server and configure the repo root folder.
  2. Right click and create a new repo
  3. Create a user and give that new user access to the repo (make sure to turn everybody else to no access)
  4. To check your new secure set up. Open a browser and enter something like this in the URL box https://<servername>:8443/svn/<reponame>/

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


QOTD

Have you ever needed a Captain Crunch Decoder Keyring to figure out code before? I have.....

- Reactor

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Sign in