//------------------------------------------------------------------------------
// <copyright file="CSSqlTrigger.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

using System.Text.RegularExpressions;

public partial class Triggers
{
    [Microsoft.SqlServer.Server.SqlTrigger(Name = "Trigger1", Target = "TriggerTest",
     Event = "FOR INSERT")]
    public static void Trigger1()
    {
        if (SqlContext.TriggerContext.TriggerAction == TriggerAction.Insert)
        {
            SqlConnection cn = new SqlConnection("context connection=true");

            cn.Open();

            SqlCommand cm = cn.CreateCommand();
            cm.CommandText = "select email from inserted";
            //SqlTransaction transaction = cn.BeginTransaction();

            SqlDataReader dr = cm.ExecuteReader();

            string email = string.Empty;
            while (dr.Read())
            {
                email = dr[0].ToString();
            }

            dr.Close();

            cm.CommandText = "rollback";

            if (ValidateEmail(email))
                return;
            else
                try
                {
                    //transaction.Rollback();
                    SqlContext.Pipe.ExecuteAndSend(cm);
                }
                catch
                {
                }

            cn.Close();

            SqlContext.Pipe.Send("Trigger FIRED");
        }
    }

    private static bool ValidateEmail(string email)
    {
        return Regex.IsMatch(email, @"^([\w-]+\.)*?[\w-]+@[\w-]+\.([\w-]+\.)*?[\w]+$");
    }
}