Search This Blog

2009-04-29

todo: upgrage eeepc with

SOURCES:
XUbuntu

An example Console Application in C# ready for debugging and testing of a simple class or library



//this is the xml added replace here your log4net and Nunit paths
//<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
        //  <SpecificVersion>False</SpecificVersion>
        //  <HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
        //</Reference>
        //<Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;

namespace ExampleConsoleApplication
{
    [TestFixture]
    class TestClass
    {

        private static readonly ILog logger =
                 LogManager.GetLogger ( typeof ( TestClass ) );


        static void Main ( string[] args )
        {
            Console.WriteLine ( " START " );
            #region LoggerUsage
            DOMConfigurator.Configure (); //tis configures the logger 
            logger.Debug ( "Here is a debug log." );
            logger.Info ( "... and an Info log." );
            logger.Warn ( "... and a warning." );
            logger.Error ( "... and an error." );
            logger.Fatal ( "... and a fatal error." );
            #endregion LoggerUsage
            TestClass objTestClass = new TestClass();
            objTestClass.TestMethodNameOK ();
            objTestClass.TestMethodNameNOK ();

            Console.WriteLine ( " END HIT A KEY TO EXIT " );
            Console.ReadLine ();
            } //eof method 

        [SetUp]
        protected void SetUp ()
        {
            //Add Here the Initialization of the objects 
        }
        [Test ( Description = "Add here the description of this test method " )]
        protected void TestMethodNameOK ()
        { 
            //build ok use case scenario here - e.g. no exception should be raced '
            //Vegetable newCarrot = pool.GetItemByPropertyValue<Vegetable> ( "WriongByPurpose", "Orange" );
            //Assert.IsInstanceOfType ( typeof ( Vegetable ), newCarrot );
            //Assert.AreSame ( newCarrot, carrot );
            //logger.Info ( " I got the newCarrot which is " + newCarrot.Color );

        } //eof method 

        [Test ( Description = "Add here the description of this test method " )]
        protected void TestMethodNameNOK ()            //e.g. the one that should raze Exception
        {
            //build ok use case scenario here - e.g. no exception should be raced '
            //Vegetable newCarrot = pool.GetItemByPropertyValue<Vegetable> ( "WriongByPurpose", "Orange" );
            //Assert.IsInstanceOfType ( typeof ( Vegetable ), newCarrot );
            //Assert.AreSame ( newCarrot, carrot );
            //logger.Info ( " I got the newCarrot which is " + newCarrot.Color );

        } //eof method 

    } //eof class 

} //eof namespace 


//click inside , Ctrl + M , M to collapse - copy paste you own code 
namespace ClassesToTest
{

    class ClassToTest
    {
        //this is the name of the method to test 
        public void MethodName ( string param )
        { 
        
        }
    } //eof class 


} //eof class 

#region TheAppConfig
/*
 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net"
                 type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="LogTest2.txt" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header] \r\n" />
                <param name="Footer" value="[Footer] \r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
            </layout>
        </appender>

        <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
            <mapping>
                <level value="ERROR" />
                <foreColor value="White" />
                <backColor value="Red, HighIntensity" />
            </mapping>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>


        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
            <commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
            
            <parameter>
                <parameterName value="@log_date" />
                <dbType value="DateTime" />
                <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
            </parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout" value="%thread" />
            </parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="50" />
                <layout type="log4net.Layout.PatternLayout" value="%level" />
            </parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout" value="%logger" />
            </parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="4000" />
                <layout type="log4net.Layout.PatternLayout" value="%messag2e" />
            </parameter>
        </appender>
        <root>
            <level value="INFO" />
            <appender-ref ref="LogFileAppender" />
            <appender-ref ref="AdoNetAppender" />
            <appender-ref ref="ColoredConsoleAppender" />
        </root>
    </log4net>
</configuration>
 */
#endregion TheAppconfig

2009-04-28

svn cheat sheet (revised)

:: HINT COPY PASTE THE WHOLE TEST THE :: STANDS FOR COMMENTS IN CMD AND WILL NOT BE INCLUDED
::SOURCE:
::http://www.abbeyworkshop.com/howto/misc/svn01/

:: Setting up a Subversion Server under Windows

::ADD THE subversion bin directory to your PATH environmental variable
::


::ADD THE FOLLOWING ENVIRONMENTAL VARIABLE ENV
SVN_EDITOR
::AND THE VALUE the path to your favorite text editor with " " around the path !!!
"C:\Program Files\TextPad 5\textpad.exe"
pause

::GET HELP FOR SVN
svn help
pause

::GET HELP FOR SVN COMMAND
svn help revert
pause

::CREATE NEW REPOSITORY
svnadmin create d:/svn
pause

::EDIT THE USER NAME AND THE PASS IN THE REPOSITORY
START /MAX TEXTPAD "D:\svn\conf\svnserve.conf"
pause

::uncoment the following lines
[general]
anon-access = read
auth-access = write
password-db = passwd

::NOW MAKE THE DIRECTORY STRUCTURE
mkdir D:\svn\poc
mkdir D:\svn\poc\branches
mkdir D:\svn\poc\tags
mkdir D:\svn\poc\trunk

::uncomment the following lines ( replace for you users and passwords )
start /max textpad D:\svn\conf\passwd :
[users]
user1 = pass1
user2 = pass2

:: Start the subversion server by issuing this command in the command window:
:: THE CMD /C will start new version of the cmd.exe
start /max CMD /C "svnserve --daemon --root d:\SVN"


::JUST CHANGE TO THE D:\ DRIVE
d:

::NOW CHANGE TO THE DIRECTORY OF your project
:: ASSUMING THAT THE PROJECT IS BELLLOW THE D:\poc folder
cd D:\

::import for first time the project name
svn import poc file:///d:/svn/poc -m "Log Message"


::TO START USING THE VERSION CONTROL FEATURES CHECK OUT A PROJECT INTO YOUR LOCAL WORKING DIRECTORY, CREATE THE DIRECTORY TO WHICH
mkdir D:\temp\poc


::NOW GO TO THE WORKING DIRECTORY
mkdir D:\temp\poc
cd D:\temp\poc
::now checkout the poc project
svn checkout file:///d:/svn/poc/trunk poc

::TO GET A LIST OF THE CURRENT PROJECTS STORED IN A REPOSITORY, YOU CAN USE THE FOLLOWING COMMAND
svn list --verbose file:///svn/poc

svn status

::SUBVERSION DOES NOT TRACK THE VERSION NUMBERS FOR INDIVIDUAL PROJECTS AUTOMATICALLY. INSTEAD, IT TRACKS EACH UPDATE TO THE REPOSITORY AND TRACKS THE VERSIONS OF THESE UPDATES. TO CREATE INTERIM PROJECT RELEASES, YOU MUST CREATE "TAGS" WHICH IDENTIFY A SPECIFY VERSION OF A PROJECT. THIS IS DONE BY MAKING A VIRTUAL COPY OF A PROJECT IN THE TAGS DIRECTORY. FOR EXAMPLE
svn copy http://ysg/svn/poc/trunk http://ysg/svn/poc/tags/0.1.0 -m "Tagging the 0.1.0 release of the poc"

::THIS CREATES A SORT OF BOOKMARK OR SNAPSHOT WHICH RECORDS THE CURRENT STATE OF THE PROJECT. THEN, YOU CAN CHECKOUT THE PROJECT IN THIS STATE AT ANY TIME BY SIMPLY REFERRING TO THAT RELEASE NUMBER.

::TO GET A LIST OF THE RELEASES FOR A PROJECT.
svn list http://localhost/svn/repos/poc/tags 0.1.0/
ipconfig
svn list http://192.168.0.153/svn/repos/poc/tags 0.1.0/

The typical work cycle looks like this:

Update your working copy
svn update
Make changes
svn add
svn delete
svn copy
svn move
Examine your changes
svn status
svn diff
svn revert
Merge others' changes into your working copy
svn update
svn resolved
Commit your changes
svn commit

Update Your Working Copy

When working on a project with a team, you'll want to update your working copy to receive any changes made since your last update by other developers on the project. Use svn update to bring your working copy into sync with the latest revision in the repository.
$ svn update
U foo.c
U bar.c
Updated to revision 2.

L abc.c # svn has a lock in its .svn directory for abc.c
M bar.c # the content in bar.c has local modifications
M baz.c # baz.c has property but no content modifications
X 3rd_party # this dir is part of an externals definition
? foo.o # svn doesn't manage foo.o
! some_dir # svn manages this, but it's either missing or incomplete
~ qux # versioned as file/dir/link, but type has changed
I .screenrc # svn doesn't manage this, and is configured to ignore it
A + moved_dir # added with history of where it came from
M + moved_dir/README # added with history and has local modifications
D stuff/fish.c # this file is scheduled for deletion
A stuff/loot/bloo.h # this file is scheduled for addition
C stuff/loot/lump.c # this file has conflicts from an update
R xyz.c # this file is scheduled for replacement
S stuff/squawk # this file or dir has been switched to a branch

Meet the Object Pool !!!

Courtesy of Matthew Cochran , I added the total count , the search by prop name and value and AddItem without id




using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Reflection;
using log4net;
using log4net.Config;

namespace DH
{

    //DH - DataHolders
    /// <summary>
    /// This class models a storage structure for objects queriable by id or property name and property value
    /// </summary>
    public class ObjectPool
    {

        #region Props
        private int _TotalCount;
        public int TotalCount
        {
            get
            {
                return _TotalCount;
            }
        }

        public int ID { get; set; }


        #endregion Props


        public ObjectPool ()
        {
            m_pool = new Dictionary<Type, Dictionary<Int32, Object>> ();
        }


        private Dictionary<Type, Dictionary<Int32, Object>> m_pool;

        public void AddItem<T> ( Int32 pID, T value )
        {
            Type myType = typeof ( T );

            if (!m_pool.ContainsKey ( myType ))
            {
                m_pool.Add ( myType, new Dictionary<int, object> () );
                m_pool[myType].Add ( pID, value );

                _TotalCount++;
                return;
            }

            if (!m_pool[myType].ContainsKey ( pID ))
            {
                m_pool[myType].Add ( pID, value );
                _TotalCount++;
                return;
            }

            m_pool[myType][pID] = value;
            _TotalCount++;
            //Utils.Debugger.WriteIf("Adding 1 to pool count , pool count is " + this._TotalCount);
        }


        public void AddItem<T> ( T value )
        {
            Int32 pID = _TotalCount;
            Type myType = typeof ( T );

            if (!m_pool.ContainsKey ( myType ))
            {
                m_pool.Add ( myType, new Dictionary<int, object> () );
                m_pool[myType].Add ( pID, value );

                _TotalCount++;
                return;
            }

            if (!m_pool[myType].ContainsKey ( pID ))
            {
                m_pool[myType].Add ( pID, value );
                _TotalCount++;
                return;
            }

            m_pool[myType][pID] = value;
            _TotalCount++;
            //Utils.Debugger.WriteIf("Adding 1 to pool count , pool count is " + this._TotalCount);
        }


        public bool RemoveItem<T> ( Int32 pID )
        {
            Type myType = typeof ( T );

            if (!m_pool.ContainsKey ( myType ))
                return false;

            if (!m_pool[myType].ContainsKey ( pID ))
                return false;

            _TotalCount--;
            return m_pool[myType].Remove ( pID );
        }

        public bool ContainsKey<T> ( Int32 pID )
        {
            Type myType = typeof ( T );

            if (!m_pool.ContainsKey ( myType ))
                return false;

            if (!m_pool[myType].ContainsKey ( pID ))
                return false;

            return m_pool[myType].ContainsKey ( pID );
        }

        /// <summary>
        /// Gets an IEnumerable collections of objects with Type T
        /// </summary>
        /// <typeparam name="T">The type of the items</typeparam>
        /// <returns>the dictionary of objects</returns>
        public IEnumerable<T> GetItems<T> ()
        {
            Type myType = typeof ( T );

            if (!m_pool.ContainsKey ( myType ))
                return new T[0];

            return m_pool[myType].Values as IEnumerable<T>;
        }


        /// <summary>
        /// Gets the item.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pID">The p ID.</param>
        /// <returns></returns>
        /// <exception cref="KeyNotFoundException"></exception>
        public T GetItem<T> ( Int32 pID )
        {
            // will throw KeyNotFoundException if either of the dictionaries 
            // does not hold the required key
            return (T)m_pool[typeof ( T )][pID];
        }


        /// <summary>
        /// Returns the first Item from        the Collection by it's property name and its value
        /// </summary>
        /// <typeparam name="T">The Type of the Object to get </typeparam>
        /// <param name="strPropMetaName"> the string representation of the </param>
        /// <param name="strPropValue">the value of the property</param>
        /// <returns></returns>
        public T GetItemByPropertyValue<T> ( String strPropMetaName, String strPropValue )
        {
            Type myType = typeof ( T );

            for (int i = 0; i < this.TotalCount; i++)
            {
                if (!m_pool.ContainsKey ( myType ))
                {
                    return default ( T );
                }
                else
                {
                    if (this.ContainsKey<T> ( i ))
                    {
                        //get an item object having the same type
                        T item = this.GetItem<T> ( i );

                        //if the object has the same property -- check its value
                        MemberInfo[] members = myType.GetMembers ();
                        for (int j = 0; j < members.Length; j++)
                        {
                            //logger.Info ( "members[j].Name is " + members[j].Name );
                            //logger.Info ( ".MemberType.ToString() " + members[j].MemberType.ToString () );
                            //logger.Info ( "members[j].GetType().ToString() " + members[j].GetType ().ToString () );
                            //logger.Info ( " members[j].ToString () is " + members[j].ToString () );
                            //logger.Info ( " members[j].ToString () is " + members[j] );


                            if (members[j].Name.ToString ().Equals ( strPropMetaName ))
                            {


                                FieldInfo[] fi;
                                fi = myType.GetFields ( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );


                                foreach (FieldInfo f in fi)
                                {
                                    //logger.Info ( "f.GetValue( obj ) is " + f.GetValue ( item ) );
                                    if (f.GetValue ( item ).ToString ().Equals ( strPropValue ))
                                        return (T)m_pool[typeof ( T )][i];
                                    else
                                        continue;

                                } //eof foreach                                
                            }
                            else
                                continue;
                        } //eof for j

                    } //eof if 
                    else
                        continue;
                } //eof else if m_pool.ContainsKey
            }
            return default ( T );
        } //eof method


//    private static readonly ILog logger =
//LogManager.GetLogger ( typeof ( DH.ObjectPool ) );

    } //eof class pool    

} //eof namespace



//namespace TestPool
//{
//  class Program
//  {
//    private static readonly ILog logger =
//LogManager.GetLogger ( typeof ( Program ) ); //create the logging object 

//    public static DH.ObjectPool pool = new DH.ObjectPool ();

//    static void Main ( string[] args )
//    {
//      DOMConfigurator.Configure (); //tis configures the logger 

//      #region CreateTheBusinessObjects
//      Animal dog = new Animal () { Name = "Fido", ID = 1 };
//      Vegetable carrot = new Vegetable { Color = "Orange", Identifier = 2, IsTasty = true };
//      Mineral carbon = new Mineral () { UniqueID = 3, IsPoisonousToAnimal = false, Name = "some" };
//      HolderForStrings hfs = new HolderForStrings () { ID = 4, Value = "user_name", MetaName = "meta_nam" };
//      HolderForStrings hfs1 = new HolderForStrings () { ID = 5, Value = "user_name", MetaName = "hfs1" };
//      Mineral carbon1 = new Mineral () { UniqueID = 3, IsPoisonousToAnimal = false, Name = "some1" };
//      #endregion CreateTheBusinessObjects

//      #region AddTheBOToThePool
//      pool.AddItem ( dog );
//      pool.AddItem ( carrot );
//      pool.AddItem ( hfs );
//      pool.AddItem ( hfs1 );
//      #endregion AddTheBOToThePool

//      #region UncommentForMoreTesting
//      //pool.AddItem<Animal>(dog.ID, dog);
//      //pool.AddItem<Vegetable>(carrot.Identifier, carrot);
//      //pool.AddItem<Mineral> ( carbon );
//      //pool.AddItem<HolderForStrings> ( 1, hfs );

//      //logger.Info("Dog is in the pool -- this statement is " + pool.ContainsKey<Animal>(dog.ID));
//      //logger.Info("hfs is in the pool -- this statement is " + pool.ContainsKey<HolderForStrings>(hfs.ID));
//      //logger.Info("The hfs value is from the poos is " + pool.GetItem<HolderForStrings>(4).Value);

//      //logger.Info("poo.GetItems is " + pool.GetItems<HolderForStrings>());

//      #endregion UncommentForMoreTesting


//      #region while
//      //for (int i = 0; i < pool.Count -1 ; i++)
//      int i = 1;
//      do
//      {
//        try
//        {
//          logger.Info ( "counting" );
//          logger.Info ( " i is " + i.ToString () );
//          if (pool.ContainsKey<Animal> ( i ))
//          {
//            logger.Info ( " I see animal which is " + pool.GetItem<Animal> ( i ).Name );
//          }

//          if (pool.ContainsKey<Vegetable> ( i ))
//          {
//            logger.Info ( " I see Vegetable which is " + pool.GetItem<Vegetable> ( i ).Color );
//          }


//          if (pool.ContainsKey<Mineral> ( i ))
//          {
//            logger.Info ( " I see Mineral which is " + pool.GetItem<Mineral> ( i ).IsPoisonousToAnimal );
//          }


//          if (pool.ContainsKey<HolderForStrings> ( i ))
//          {
//            logger.Info ( " I see string which is " + pool.GetItem<HolderForStrings> ( i ).Value );
//          }

//          //logger.Info("pool.GetItem<HolderForStrings>(4).Value); is " + pool.GetItem<Object>(i).ToString());

//          i = i + 1;
//        }
//        catch (KeyNotFoundException e)
//        {
//          continue;
//        }

//      } //eof for 
//      while (i < pool.TotalCount);
//      #endregion while

//      #region AddHolders
//      ////this is the success identifier
//      //HoldInt16 holdVerifier = new HoldInt16()
//      //{
//      //  ID=0 ,
//      //  MetaName = "ret",
//      //  Value = 0
//      //};
//      //pool.AddItem<HoldInt16>(holdVerifier.ID, holdVerifier);

//      //ListDictionary lidMetaName = pool.LidMetaName;
//      ////this is the message
//      //HoldString holdMsg = new HoldString( ref lidMetaName)
//      //{
//      //  ID=1,
//      //  MetaName = "msg",
//      //  Value = msg,
//      //  Title = "title" 
//      //};
//      //pool.AddItem<HoldString>(holdMsg.ID, holdMsg);


//      //HoldString holdmmsg = new HoldString(ref lidMetaName)
//      //{
//      //  ID=2,
//      //  MetaName = "mmsg",
//      //  Value = "mmsg" , 
//      //  Title = "title" 
//      //};
//      #endregion AddHolders

//      //Utils.Debugger.DebugListDictionary(ref msg, "domainName", ref lidMetaName);
//      //get the value be metaName

//      logger.Info ( "I queried the pool by property with meta Value and value user_name " );

//      HolderForStrings HolderForStrings = pool.GetItemByPropertyValue<HolderForStrings> ( "MetaName", "hfs1" );
//      //logger.Info ( "object dump" + Utils.Log.ObjDumper.DumpObject ( HolderForStrings ) );
//      logger.Info ( "I found the following value for property with the name \"Name\" " );
//      logger.Info ( HolderForStrings.MetaName );

//      Console.ReadLine ();
//    } //eof Main

//  } //eof class 

//  #region ExampleBusinessObjects
//  public class Animal
//  {
//    public Int32 ID { get; set; }
//    public String Name { get; set; }
//  }

//  public class HolderForStrings
//  {
//    public Int32 ID { get; set; }
//    public String Value { get; set; }
//    public String MetaName { get; set; }
//    Type ObjType = typeof ( string );
//    public Int32 Size { get; set; }
//    public bool IsOptional { get; set; }
//    public bool IsPrimaryKey { get; set; }

//  } //eof class


//  public class Vegetable
//  {
//    public Int32 Identifier { get; set; }
//    public String Color { get; set; }
//    public Boolean IsTasty { get; set; }
//  }

//  public class Mineral
//  {
//    public Int32 UniqueID { get; set; }
//    public Boolean IsPoisonousToAnimal { get; set; }
//    public String Name { get; set; }
//  }

//  #endregion ExampleOfBusinessObjects
//} //eof class 

.Net regex cheat sheet

source:
http://regexlib.com/CheatSheet.aspx


RegExLib - Regular Expression Library

RegExLib.com Regular Expression Cheat Sheet (.NET)


Metacharacters Defined

MCharDefinition
^Start of a string.
$End of a string.
.Any character (except \n newline)
|Alternation.
{...}Explicit quantifier notation.
[...]Explicit set of characters to match.
(...)Logical grouping of part of an expression.
*0 or more of previous expression.
+1 or more of previous expression.
?0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string.
\Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below.

Metacharacter Examples

PatternSample Matches
^abcabc, abcdefg, abc123, ...
abc$abc, endsinabc, 123abc, ...
a.cabc, aac, acc, adc, aec, ...
bill|tedted, bill
ab{2}cabbc
a[bB]cabc, aBc
(abc){2}abcabc
ab*cac, abc, abbc, abbbc, ...
ab+cabc, abbc, abbbc, ...
ab?cac, abc
a\sca c

Character Escapes http://tinyurl.com/5wm3wl

Escaped CharDescription
ordinary charactersCharacters other than . $ ^ { [ ( | ) ] } * + ? \ match themselves.
\aMatches a bell (alarm) \u0007.
\bMatches a backspace \u0008 if in a []; otherwise matches a word boundary (between \w and \W characters).
\tMatches a tab \u0009.
\rMatches a carriage return \u000D.
\vMatches a vertical tab \u000B.
\fMatches a form feed \u000C.
\nMatches a new line \u000A.
\eMatches an escape \u001B.
\040Matches an ASCII character as octal (up to three digits); numbers with no leading zero are backreferences if they have only one digit or if they correspond to a capturing group number. (For more information, see Backreferences.) For example, the character \040 represents a space.
\x20Matches an ASCII character using hexadecimal representation (exactly two digits).
\cCMatches an ASCII control character; for example \cC is control-C.
\u0020Matches a Unicode character using a hexadecimal representation (exactly four digits).
\*When followed by a character that is not recognized as an escaped character, matches that character. For example, \* is the same as \x2A.

Character Classes http://tinyurl.com/5ck4ll

Char ClassDescription
.Matches any character except \n. If modified by the Singleline option, a period character matches any character. For more information, see Regular Expression Options.
[aeiou]Matches any single character included in the specified set of characters.
[^aeiou]Matches any single character not in the specified set of characters.
[0-9a-fA-F]Use of a hyphen (–) allows specification of contiguous character ranges.
\p{name}Matches any character in the named character class specified by {name}. Supported names are Unicode groups and block ranges. For example, Ll, Nd, Z, IsGreek, IsBoxDrawing.
\P{name}Matches text not included in groups and block ranges specified in {name}.
\wMatches any word character. Equivalent to the Unicode character categories
[\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \w is equivalent to [a-zA-Z_0-9].
\WMatches any nonword character. Equivalent to the Unicode categories [^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \W is equivalent to [^a-zA-Z_0-9].
\sMatches any white-space character. Equivalent to the Unicode character categories [\f\n\r\t\v\x85\p{Z}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \s is equivalent to [ \f\n\r\t\v].
\SMatches any non-white-space character. Equivalent to the Unicode character categories [^\f\n\r\t\v\x85\p{Z}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \S is equivalent to [^ \f\n\r\t\v].
\dMatches any decimal digit. Equivalent to \p{Nd} for Unicode and [0-9] for non-Unicode, ECMAScript behavior.
\DMatches any nondigit. Equivalent to \P{Nd} for Unicode and [^0-9] for non-Unicode, ECMAScript behavior.

2009-04-23

SVN WIN Cheat Sheet

:: HINT COPY PASTE THE WHOLE TEST THE :: STANDS FOR COMMENTS IN CMD AND WILL NOT BE INCLUDED
::SOURCE:
::http://www.abbeyworkshop.com/howto/misc/svn01/

:: Setting up a Subversion Server under Windows

::ADD THE subversion bin directory to your PATH environmental variable
::


::ADD THE FOLLOWING ENVIRONMENTAL VARIABLE ENV
SVN_EDITOR
::AND THE VALUE the path to your favorite text editor with " " around the path !!!
"C:\Program Files\TextPad 5\textpad.exe"
pause

::GET HELP FOR SVN
svn help
pause

::GET HELP FOR SVN COMMAND
svn help revert
pause

::CREATE NEW REPOSITORY
svnadmin create d:/svn
pause

::EDIT THE USER NAME AND THE PASS IN THE REPOSITORY
START /MAX TEXTPAD "D:\svn\conf\svnserve.conf"
pause

::uncoment the following lines
[general]
anon-access = read
auth-access = write
password-db = passwd

::NOW MAKE THE DIRECTORY STRUCTURE
mkdir D:\svn\poc
mkdir D:\svn\poc\branches
mkdir D:\svn\poc\tags
mkdir D:\svn\poc\trunk

::uncomment the following lines ( replace for you users and passwords )
start /max textpad D:\svn\conf\passwd :
[users]
user1 = pass1
user2 = pass2

:: Start the subversion server by issuing this command in the command window:
:: THE CMD /C will start new version of the cmd.exe
start /max CMD /C "svnserve --daemon --root d:\SVN"


::JUST CHANGE TO THE D:\ DRIVE
d:

::NOW CHANGE TO THE DIRECTORY OF your project
:: ASSUMING THAT THE PROJECT IS BELLLOW THE D:\poc folder
cd D:\

::import for first time the project name
svn import poc file:///d:/svn/poc -m "Log Message"


::TO START USING THE VERSION CONTROL FEATURES CHECK OUT A PROJECT INTO YOUR LOCAL WORKING DIRECTORY, CREATE THE DIRECTORY TO WHICH
mkdir D:\temp\poc


::NOW GO TO THE WORKING DIRECTORY
mkdir D:\temp\poc
cd D:\temp\poc
::now checkout the poc project
svn checkout file:///d:/svn/poc/trunk poc

::TO GET A LIST OF THE CURRENT PROJECTS STORED IN A REPOSITORY, YOU CAN USE THE FOLLOWING COMMAND
svn list --verbose file:///svn/poc

svn status

::SUBVERSION DOES NOT TRACK THE VERSION NUMBERS FOR INDIVIDUAL PROJECTS AUTOMATICALLY. INSTEAD, IT TRACKS EACH UPDATE TO THE REPOSITORY AND TRACKS THE VERSIONS OF THESE UPDATES. TO CREATE INTERIM PROJECT RELEASES, YOU MUST CREATE "TAGS" WHICH IDENTIFY A SPECIFY VERSION OF A PROJECT. THIS IS DONE BY MAKING A VIRTUAL COPY OF A PROJECT IN THE TAGS DIRECTORY. FOR EXAMPLE
svn copy http://ysg/svn/poc/trunk http://ysg/svn/poc/tags/0.1.0 -m "Tagging the 0.1.0 release of the poc"

::THIS CREATES A SORT OF BOOKMARK OR SNAPSHOT WHICH RECORDS THE CURRENT STATE OF THE PROJECT. THEN, YOU CAN CHECKOUT THE PROJECT IN THIS STATE AT ANY TIME BY SIMPLY REFERRING TO THAT RELEASE NUMBER.

::TO GET A LIST OF THE RELEASES FOR A PROJECT.
svn list http://localhost/svn/repos/poc/tags 0.1.0/
ipconfig
svn list http://192.168.0.153/svn/repos/poc/tags 0.1.0/

2009-04-22

db trigger to force versioning in ddl statements on sql server 2005 / 2008

This trigger demonstrates the enforcing of the someValue xml element in the sql command to be executed on a sql server 2005 / 2008
Thus one could modigy it to add more enforcements: for example :
I had to change the proc since ...

it also keeps track on all the sql commands and saves them into a history log table, so one could digg out the older version and rerun them straight away .

I would be glad to receive and improvement suggestions - how-to keep track on the versions , version rolling etc. Enjoy !


USE [GA_DEV]
GO

/****** Object:  DdlTrigger [TraceDbChanges]    Script Date: 05/07/2009 12:57:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




create trigger [TraceDbChanges]
on database
for create_procedure, alter_procedure, drop_procedure,
create_table, alter_table, drop_table,
create_function, alter_function, drop_function , 
create_trigger , alter_trigger , drop_trigger 
as

set nocount on

declare @data xml
set @data = EVENTDATA()
declare @DbVersion varchar(20)
set @DbVersion =(select ga.GetDbVersion())
declare @DbType varchar(20)
set @DbType =(select ga.GetDbType())
declare @DbName varchar(256)
set @DbName =@data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(256)')
declare @EventType varchar(256)
set @EventType =@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)')
declare @ObjectName varchar(256)
set @ObjectName  = @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(256)')
declare @ObjectType varchar(25)
set @ObjectType = @data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(25)')
declare @TSQLCommand varchar(max)
set @TSQLCommand = @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
declare @opentag varchar(4)
set @opentag= '&lt;'
declare @closetag varchar(4) 
set @closetag= '&gt;'
declare @newDataTxt varchar(max) 
set @newDataTxt= cast(@data as varchar(max))
set @newDataTxt = REPLACE ( REPLACE(@newDataTxt , @opentag , '<') , @closetag , '>')
-- print @newDataTxt
declare @newDataXml xml 
set @newDataXml = CONVERT ( xml , @newDataTxt)

declare @Version varchar(50)
set @Version = @newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/Version)[1]', 'varchar(50)')

-- if we are dropping take the version from the existing object 
if  ( SUBSTRING(@EventType , 0 , 5)) = 'DROP'
set @Version =( select top 1 [Version]  from ga.DbObjChangeLog where ObjectName=@ObjectName order by [LogId] desc)
if ( @Version is null)
set @Version = '1.0.0'

declare @Description varchar(max)
set @Description = @newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/Description)[1]', 'varchar(max)')

declare @ChangeDescription varchar(max)
set @ChangeDescription = @newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/ChangeDescription)[1]', 'varchar(max)')

declare @LoginName varchar(256) 
set @LoginName = @data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(256)')
declare @FirstName varchar(50)
set @FirstName= (select [FirstName] from [ga].[LoginsForUsers] where [LoginName] = @LoginName)
declare @LastName varchar(50)
set @LastName  = (select [LastName] from [ga].[LoginsForUsers] where [LoginName] = @LoginName)
declare @SchemaName sysname 
set @SchemaName = @data.value('(/EVENT_INSTANCE/SchemaName)[1]', 'sysname');
--declare @Description xml 
--set @Description = @data.query('(/EVENT_INSTANCE/TSQLCommand/text())')




--print 'VERSION IS ' + @Version
--print @newDataTxt
--print cast(@data as varchar(max))


-- select column_name from information_schema.columns where table_name ='DbObjChangeLog'
insert into [ga].[DbObjChangeLog]
(
[DatabaseName] ,
[SchemaName],
[DbVersion] ,
[DbType],
[EventType],
[ObjectName],
[ObjectType] ,
[Version],
[Description],
[ChangeDescription],
[SqlCommand] ,
[LoginName] ,
[FirstName],
[LastName] 
)

values(

@DbName,
@SchemaName,
@DbVersion,
@DbType,
@EventType, 
@ObjectName, 
@ObjectType , 
@Version,
@Description,
@ChangeDescription,
@newDataTxt, 
@LoginName , 
@FirstName , 
@LastName
)




GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

DISABLE TRIGGER [TraceDbChanges] ON DATABASE
GO

ENABLE TRIGGER [TraceDbChanges] ON DATABASE
GO


2009-04-21

Threading Best Practices

STRAIGHT COPY PASTE FROM
STACKOVERFLOW - Threading Best Practices

Immutability is great for multi-threading. Functional programming works well concurrently partly due to the emphasis on immutability.
Use locks when you access mutable shared data, both for reads and writes.
Don't try to go lock-free unless you really have to. Locks are expensive, but rarely the bottleneck.
Monitor.Wait should almost always be part of a condition loop, waiting for a condition to become true and waiting again if it's not.
Try to avoid holding locks for longer than you need to.
If you ever need to acquire two locks at once, document the ordering thoroughly and make sure you always use the same order.
Document the thread-safety of your types. Most types don't need to be thread-safe, they just need to not be thread hostile (i.e. "you can use them from multiple threads, but it's your responsible for taking out locks if you want to share them)
Don't access the UI (except in documented thread-safe ways) from a non-UI thread. In Windows Forms, use Control.Invoke/BeginInvoke


Before jumping into it, first understand that the the class boundary is not the same as a thread boundary. For example, if a callback method on your class is called by another thread (e.g., the AsyncCallback delegate to the TcpListener.BeginAcceptTcpClient() method), understand that the callback executes on that other thread. So even though the callback occurs on the same object, you still have to synchronize access to the members of the object within the callback method. Threads and classes are orthogonal; it is important to understand this point.
Identify what data needs to be shared between threads. Once you have defined the shared data, try to consolidate it into a single class if possible.
Limit the places where the shared data can be written and read. If you can get this down to one place for writing and one place for reading, you will be doing yourself a tremendous favor. This is not always possible, but it is a nice goal to shoot for.
Obviously make sure you synchronize access to the shared data using the Monitor class or the lock keyword.
If possible, use a single object to synchronize your shared data regardless of how many different shared fields there are. This will simplify things. However, it may also overly constrain things too, in which case, you may need a synchronization object for each shared field. And at this point, using immutable classes becomes very handy.
If you have one thread that needs to signal another thread(s), I would strongly recommend using the ManualResetEvent class to do this instead of using events/delegates.

2009-04-20

Log4Net example console program



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config; 


namespace UserAndAction
{
    class Program
    {

        private static readonly ILog logger =
             LogManager.GetLogger ( typeof ( Program ) );


        static void Main ( string[] args )
        {
            Console.WriteLine ( " START " );


XmlConfigurator.Configure( new FileInfo ( "D:\\libs\\path\\to\\App.config")); //tis configures the loo
; //tis configures the logger 
            
            logger.Debug ( "Here is a debug log." );
            logger.Info ( "... and an Info log." );
            logger.Warn ( "... and a warning." );
            logger.Error ( "... and an error." );
            logger.Fatal ( "... and a fatal error." );



            Console.WriteLine ( " HIT A KEY TO EXIT " );
            Console.ReadLine ();
            Console.WriteLine ( " END " );
        }
    } //eof class 

} //eof namespace 

log4net example console app configuration file



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net"
             type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="LogTest2.txt" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header] \r\n" />
                <param name="Footer" value="[Footer] \r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
            </layout>
        </appender>

        <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
            <mapping>
                <level value="ERROR" />
                <foreColor value="White" />
                <backColor value="Red, HighIntensity" />
            </mapping>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>


        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="data source=nameOfTheHostAndInstance;initial catalog=DbName;integrated security=true;persist security info=True;" />
            <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
            <parameter>
                <parameterName value="@log_date" />
                <dbType value="DateTime" />
                <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
            </parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout" value="%thread" />
            </parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="50" />
                <layout type="log4net.Layout.PatternLayout" value="%level" />
            </parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout" value="%logger" />
            </parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="4000" />
                <layout type="log4net.Layout.PatternLayout" value="%message" />
            </parameter>
        </appender>
        <root>
            <level value="INFO" />
            <appender-ref ref="LogFileAppender" />
            <appender-ref ref="AdoNetAppender" />
            <appender-ref ref="ColoredConsoleAppender" />
        </root>
    </log4net>
</configuration>

2009-04-19

Opera - again the best browser for blogging !

You might question why ?
Whell I have a shortcut for new tab + Ctrl + 5 and set the following url to it :
http://draft.blogger.com/posts.g?blogID=30804833

where the id 30804833 is the id of my blog so I am redirected straight to the posting page of my blog

So the creation of a new blog goes as follows:
Ctrl + T -- create a new tab
Ctrl + 5 -- go to the blogger list posting page
Shift + / -- to start searching on the page
type create -- to go the the create link
press Enter --- create new post
start fillign ---


I took me 45 seconds to create this post.
So again Opera rocks !
And of course Blogger also !!!!

Question : How to utilize your time to the maximum

Answer: Download
Ipodifier

and subscribe to the

GoogleTechTalks Channel

it takes some 30 seconds per tech talk additional effort to download it and later on move to your Ipod /mp4 player having phone.

Now you have your portable high-tech tv on demand in your pocket !

P.S. Needless to say that if you use it for downloading videos you are kind of pirating, so I do not support / recommend that ...

2009-04-18

Which phonomenom has been denied for 20 years and reanounced now ?

SOURCES:
Cold Fusion

check for required custom class attributes in C# assembly using reflection



        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Reflection;

        namespace MustHaveAttributes
        {
            [AttributeClass ( "Yordan Georgiev", "1.0.0" )]    
            class Program
            {
            
                
                static int Main ( string [] args )
                {
                    bool flagFoundCustomAttrOfTypeAttributeClass = false; 
                    Console.WriteLine ( " START " );

                    // what is in the assembly
                    Assembly a = Assembly.Load ( "MustHaveAttributes" );
                    Type[] types = a.GetTypes ();
                    foreach (Type t in types)
                    {
                        object[] arrCustomAttributes = t.GetCustomAttributes ( true );
                        

                        if (arrCustomAttributes == null || arrCustomAttributes.GetLength ( 0 ) == 0)
                        {
                            //DO NOT CHECK IN
                            ExitProgram ( t, "Found class without CustomAttributes" );
                        }


                        foreach (object objCustomAttribute in arrCustomAttributes)
                        {
                            Console.WriteLine ( "CustomAttribute for type  is {0}", t );
                            if (objCustomAttribute is AttributeClass)
                                flagFoundCustomAttrOfTypeAttributeClass = true; 
                        }

                        if (flagFoundCustomAttrOfTypeAttributeClass == false)
                        { //DO NOT CHECK IN 
                            ExitProgram ( t, "Did not found custom attribute of type AttributeClass" );
                        }
                        Console.WriteLine ( "Type is {0}", t );
                    }
                    Console.WriteLine ("{0} types found", types.Length );

                    //NOW REQUIREMENTS IS PASSED CHECK IN
                    Console.WriteLine ( " HIT A KEY TO EXIT " );
                    Console.ReadLine ();
                    Console.WriteLine ( " END " );
                    System.Environment.Exit ( 0 );
                    return 0; 
                }



                static void ExitProgram ( Type t, string strExitMsg  )
                {

                    Console.WriteLine ( strExitMsg );
                    Console.WriteLine ( "Type is {0}", t );
                    Console.WriteLine ( " HIT A KEY TO EXIT " );
                    Console.ReadLine ();

                    System.Environment.Exit ( 1 );

                }
            } //eof Program


            //This will fail even to compile since the constructor requires two params
            //[AttributeClass("OnlyAuthor")]        
            //class ClassOne
            //{ 
            
            //} //eof class 


            ////this will not check in since this class does not have required custom
            ////attribute
            //class ClassWithoutAttrbute
            //{ }



            [AttributeClass("another author name " , "another version")]
            class ClassTwo
            { 
            
            } //eof class


            [System.AttributeUsage ( System.AttributeTargets.Class |
                System.AttributeTargets.Struct, AllowMultiple = true )]
            public class AttributeClass : System.Attribute
            {

                public string MustHaveDescription { get; set; }
                public string MusHaveVersion { get; set; }


                public AttributeClass ( string mustHaveDescription, string mustHaveVersion )
                {
                    MustHaveDescription = mustHaveDescription;
                    MusHaveVersion = mustHaveVersion;
                }

            } //eof class 

        } //eof namespace 

A simple example Console program for quick testing



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace WriteNameSpace
{
class WriteClass
{
static void Main ( string[] args )
{
Console.WriteLine ( " START " );



Console.ReadLine ();
Console.WriteLine ( " HIT A KEY TO EXIT " );
Console.WriteLine ( " END " );
}
} //eof Program

} //eof namespace

2009-04-10

A great code formatter for Blogger ... Covers the most of the languages used here ...

Use it from :
http://www.manoli.net/csharpformat/


USE [DBGA_DEV]
GO
/****** Object:  DdlTrigger [trigMetaDoc_TraceDbChanges]    Script Date: 04/10/2009 21:31:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


create trigger [trigMetaDoc_TraceDbChanges]
on database
for create_procedure, alter_procedure, drop_procedure,
create_table, alter_table, drop_table,
create_function, alter_function, drop_function , 
create_trigger , alter_trigger , drop_trigger 
as

set nocount on

declare @data xml
set @data = EVENTDATA()
declare @DbVersion varchar(20)=(select ga.GetDbVersion())
declare @DbName varchar(256)=@data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(256)')
declare @DbType varchar(50)=(select ga.GetDbType())
declare @EventType varchar(256)=@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)')
declare @ObjectName varchar(256) = @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(256)')
declare @ObjectType varchar(25) = @data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(25)')
declare @TSQLCommand varchar(max) = @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
declare @LoginName varchar(256) = @data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(256)')
declare @FirstName varchar(50)= (select [FirstName] from [ga].[tb_BLSec_LoginsForUsers] where [LoginName] = @LoginName)
declare @LastName varchar(50) = (select [LastName] from [ga].[tb_BLSec_LoginsForUsers] where [LoginName] = @LoginName)
declare @SchemaName sysname = @data.value('(/EVENT_INSTANCE/SchemaName)[1]', 'sysname');
declare @Description xml = @data.query('(/EVENT_INSTANCE/TSQLCommand/text())')


print cast(@data as varchar(max))

declare @Desc varchar(200) = @Description.value('(/Description)[1]' , 'varchar(200)')
print @TSQLCommand
print @Desc

-- select column_name from information_schema.columns where table_name ='tb_DataMeta_ObjChangeLog'
insert into [ga].[tb_DataMeta_ObjChangeLog]
(
[DatabaseName] ,
[SchemaName],
[DbVersion] ,
[DbType],
[EventType],
[ObjectName],
[ObjectType] ,
[SqlCommand] ,
[LoginName] ,
[FirstName],
[LastName] 
)

values(

@DbName,
@SchemaName,
@DbVersion,
@DbType,
@EventType, 
@ObjectName, 
@ObjectType , 
@TSQLCommand, 
@LoginName , 
@FirstName , 
@LastName
)

-- if eventType like create -> add ext props ; 
-- if eventType like alter -> update ext props ;
-- if eventType like drop -> 
-- select name from sys.tables where name like '%ext%'

GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

DISABLE TRIGGER [trigMetaDoc_TraceDbChanges] ON DATABASE
GO

ENABLE TRIGGER [trigMetaDoc_TraceDbChanges] ON DATABASE
GO

Get name value from extended properties for tables and stored procedures



-- get stored procedure name , it's ext prop name and value
SELECT sp.name , ep.name , ep.value from sys.extended_properties as ep inner join sys.procedures as sp on ep.major_id = sp.object_id


--get ext props name value for tables
SELECT sp.name , ep.name , ep.value from sys.extended_properties as ep inner join sys.tables as sp on ep.major_id = sp.object_id

IT Programming Links

SOURCES:
Erland Sommarskog's home page - Sql server MVP


Monitoring changes to database schema
http://www.simple-talk.com/sql/database-administration/more-database-administration-and-development-automation-using-dmo/

www.codekeeper.net

Only for advanced students !!! Create a ddl trigger for each database

SOURCE:
http://stackoverflow.com/questions/334671/create-a-ddl-trigger-in-every-database-on-a-2005-instance
USE [SQL_DBA]
GO
/****** Object: Table [dbo].[DDL_Login_Log] Script Date: 03/03/2009 17:28:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DDL_Login_Log](
[DDL_Id] [int] IDENTITY(1,1) NOT NULL,
[PostTime] [datetime] NOT NULL,
[DB_User] [nvarchar](100) NULL,
[DBName] [nvarchar](100) NULL,
[Event] [nvarchar](100) NULL,
[TSQL] [nvarchar](2000) NULL,
[Object] [nvarchar](1000) NULL,
CONSTRAINT [PK_DDL_Login_Log] PRIMARY KEY CLUSTERED
(
[DDL_Id] ASC,
[PostTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--This creates the trigger on the model database so all new DBs get it
USE [model]
GO
/****** Object: DdlTrigger [ddl_DB_User] Script Date: 03/03/2009 17:26:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [ddl_DB_User]
ON DATABASE
FOR DDL_DATABASE_SECURITY_EVENTS
AS

DECLARE @data XML
declare @user nvarchar(100)

SET @data = EVENTDATA()
select @user = convert(nvarchar(100), SYSTEM_USER)

execute as login='domain\sqlagent'
INSERT sql_dba.dbo.DDL_Login_Log
(PostTime, DB_User, DBName, Event, TSQL,Object)
VALUES
(@data.value('(/EVENT_INSTANCE/PostTime)[1]', 'nvarchar(100)'),
@user,
db_name(),
@data.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'),
@data.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)'),
@data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(1000)')
)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--CREATE TRIGGER IN ALL NON SYSTEM DATABASES

DECLARE @dataname varchar(255),
@dataname_header varchar(255),
@command VARCHAR(MAX),
@usecommand VARCHAR(100)
SET @command = '';
DECLARE datanames_cursor CURSOR FOR SELECT name FROM sys.databases
WHERE name not in ('master', 'pubs', 'tempdb', 'model','msdb')
OPEN datanames_cursor
FETCH NEXT FROM datanames_cursor INTO @dataname
WHILE (@@fetch_status = 0)
BEGIN

PRINT '----------BEGIN---------'

PRINT 'DATANAME variable: ' + @dataname;

EXEC ('USE ' + @dataname);

PRINT 'CURRENT db: ' + db_name();

SELECT @command = 'CREATE TRIGGER DBA_Audit ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
DECLARE @data XML
DECLARE @cmd NVARCHAR(1000)
DECLARE @posttime NVARCHAR(24)
DECLARE @spid NVARCHAR(6)
DECLARE @loginname NVARCHAR(100)
DECLARE @hostname NVARCHAR(100)
SET @data = EVENTDATA()
SET @cmd = @data.value(''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'', ''NVARCHAR(1000)'')
SET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''','''')))
SET @posttime = @data.value(''(/EVENT_INSTANCE/PostTime)[1]'', ''DATETIME'')
SET @spid = @data.value(''(/EVENT_INSTANCE/SPID)[1]'', ''nvarchar(6)'')
SET @loginname = @data.value(''(/EVENT_INSTANCE/LoginName)[1]'',
''NVARCHAR(100)'')
SET @hostname = HOST_NAME()
INSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName)
VALUES(@cmd, @posttime, @hostname, @loginname);'

EXEC (@command);
FETCH NEXT FROM datanames_cursor INTO @dataname;
PRINT '----------END---------'
END
CLOSE datanames_cursor
DEALLOCATE datanames_cursor

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

----Disable all triggers when things go haywire
sp_msforeachdb @command1='use [?]; IF EXISTS (SELECT * FROM sys.triggers WHERE name = N''ddl_DB_User'' AND parent_class=0)disable TRIGGER [ddl_DB_User] ON DATABASE'

Labels

perl (41) Cheat Sheet (25) how-to (24) windows (14) sql server 2008 (13) linux (12) oracle (12) sql (12) Unix (11) cmd windows batch (10) mssql (10) cmd (9) script (9) textpad (9) netezza (8) sql server 2005 (8) cygwin (7) meta data mssql (7) metadata (7) bash (6) code generation (6) Informatica (5) cheatsheet (5) energy (5) tsql (5) utilities (5) excel (4) future (4) generic (4) git cheat sheet (4) html (4) perl modules (4) programs (4) settings (4) sh (4) shortcuts (4) поуки (4) принципи (4) Focus Fusion (3) Solaris (3) cool programs (3) development (3) economy (3) example (3) freeware (3) fusion (3) logging (3) morphus (3) mssql 2005 (3) nuclear (3) nz (3) parse (3) python (3) sftp (3) sofware development (3) source (3) sqlplus (3) table (3) vim (3) .Net (2) C# (2) China (2) GUI (2) Google (2) GoogleCL (2) Solaris Unix (2) architecture (2) ascii (2) awk (2) batch (2) cas (2) chrome extensions (2) code2html (2) columns (2) configuration (2) conversion (2) duplicates (2) excel shortcuts (2) export (2) file (2) free programs (2) informatica sql repository (2) linux cheat sheet (2) mssql 2008 (2) mysql (2) next big future (2) nsis (2) nz netezza cheat sheet (2) nzsql (2) ora (2) prediction (2) publish (2) release management (2) report (2) security (2) single-click (2) sqlserver 2005 (2) sqlserver 2008 (2) src (2) ssh (2) template (2) tools (2) vba (2) video (2) xlt (2) xml (2) youtube videos (2) *nix (1) .vimrc (1) .virmrc vim settings configs (1) BSD license (1) Bulgaria (1) Dallas (1) Database role (1) Dense plasma focus (1) Deployment (1) ERP (1) ExcelToHtml (1) GD (1) GDP (1) HP-UX (1) Hosting (1) IDEA (1) INC (1) IT general (1) ITIL management bullshit-management (1) IZarc (1) Java Web Start (1) JavaScript anchor html jquery (1) Khan Academy (1) LINUX UNIX BASH AND CYGWIN TIPS AND TRICKS (1) Linux Unix rpm cpio build install configure (1) Linux git source build .configure make (1) ListBox (1) MIT HYDROGEN VIRUS (1) OO (1) Obama (1) PowerShell (1) Run-time (1) SDL (1) SIWA (1) SOX (1) Scala (1) Services (1) Stacks (1) SubSonic (1) TED (1) abstractions (1) ansible hosts linux bash (1) ansible linux deployment how-to (1) ansible yum pip python (1) apache (1) apache 2.2 (1) application life cycle (1) architecture input output (1) archive (1) arguments (1) avatar (1) aws cheat sheet cli (1) aws cli (1) aws cli amazon cheat sheet (1) aws elb (1) backup (1) bash Linux open-ssh ssh ssh_server ssh_client public-private key authentication (1) bash perl search and replace (1) bash stub (1) bin (1) biofuels (1) biology (1) books (1) browser (1) bubblesort (1) bugs (1) build (1) byte (1) cas_sql_dev (1) chennai (1) chrome (1) class (1) claut (1) cmdow (1) code generation sqlserver (1) command (1) command line (1) conf (1) confluence (1) console (1) convert (1) cool programs windows free freeware (1) copy paste (1) copy-paste (1) csv (1) ctags (1) current local time (1) cygwin X11 port-forwarding mintty xclock Linux Unix X (1) cygwin bash how-to tips_n_tricks (1) cygwin conf how-to (1) data (1) data types (1) db2 cheat sheet (1) db2 starter ibm bash Linux (1) debt (1) diagram (1) dictionaries (1) digital (1) disk (1) disk space (1) documentation (1) dos (1) dubai (1) e-cars (1) electric cars (1) electricity (1) emulate (1) errors (1) exponents (1) export workflow (1) extract (1) fast export (1) fexp (1) file extension (1) file permissions (1) findtag (1) firewall (1) for loop (1) freaky (1) functions (1) fusion research (1) german (1) git gitlab issues handling system (1) google cli (1) google code (1) google command line interface (1) gpg (1) ha (1) head (1) helsinki (1) history (1) hop or flop (1) host-independant (1) how-to Windows cmd time date datetime (1) ibm db2 cognos installation example db deployment provisioning (1) ideas (1) image (1) informatica oracle sql (1) informatica repo sql workflows sessions file source dir (1) informatica source files etl (1) install (1) isg-pub issue-tracker architecture (1) it management best practices (1) java (1) jump to (1) keyboard shortcuts (1) ksh (1) level (1) linkedin (1) linux bash ansible hosts (1) linux bash commands (1) linux bash how-to shell expansion (1) linux bash shell grep xargs (1) linux bash tips and t ricks (1) linux bash unix cygwin cheatsheet (1) linux bash user accounts password (1) linux bash xargs space (1) linux cheat-sheet (1) linux cheatsheet cheat-sheet revised how-to (1) linux how-to non-root vim (1) linux ssh hosts parallel subshell bash oneliner (1) london (1) make (1) me (1) metacolumn (1) metadata functions (1) metaphonre (1) method (1) model (1) movie (1) multithreaded (1) mysql cheat sheet (1) mysql how-to table datatypes (1) n900 (1) nano (1) neteza (1) netezza bash linux nps (1) netezza nps (1) netezza nps nzsql (1) netezza nz Linux bash (1) netezza nz bash linux (1) netezza nz nzsql sql (1) netezza nzsql database db sizes (1) non-password (1) nord pol (1) nps backup nzsql schema (1) number formatting (1) nz db size (1) nz table count rows (1) nzsql date timestamp compare bigint to_date to_char now (1) on-lier (1) one-liners (1) one-to-many (1) oneliners (1) open (1) open source (1) openrowset (1) openssl (1) oracle PL/SQL (1) oracle Perl perl (1) oracle installation usability (1) oracle number formatting format-model ora-sql oracle (1) oracle templates create table (1) oracle trigger generic autoincrement (1) oracle vbox virtual box cheat sheet (1) oracle virtual box cheat sheet (1) outlook (1) parser (1) password (1) paths (1) perl @INC compile-time run-time (1) perl disk usage administration Linux Unix (1) perl modules configuration management (1) permissions (1) php (1) picasa (1) platform (1) postgreSQL how-to (1) powerShell cmd cygwin mintty.exe terminal (1) ppm (1) predictions (1) prices (1) principles (1) productivity (1) project (1) prompt (1) proxy account (1) public private key (1) publishing (1) putty (1) qt (1) read file (1) registry (1) relationship (1) repository (1) rm (1) scala ScalaFmt (1) scp (1) scripts (1) scsi (1) search and replace (1) sed (1) sendEmail (1) sh stub (1) shortcuts Windows sql developer Oracle (1) sidebar (1) silicon (1) smells (1) smtp (1) software development (1) software procurement (1) sofware (1) sort (1) sql script (1) sql_dev (1) sqlcmd (1) sqlite (1) sqlite3 (1) sshd (1) sshd cygwin (1) stackoverflow (1) stored procedure (1) stub (1) stupidity (1) subroutines (1) svn (1) sysinternals (1) system design (1) tail (1) tar (1) temp table (1) templates (1) teradata (1) terminal (1) test (1) testing (1) theory (1) thorium (1) time (1) tip (1) title (1) tmux .tmux.conf configuration (1) tmux efficiency bash (1) tool (1) ui code prototyping tips and tricks (1) umask Linux Unix bash file permissions chmod (1) url (1) urls (1) user (1) utility (1) utils (1) vb (1) vbox virtual box cheat sheet (1) vim perl regex bash search for string (1) vim recursively hacks (1) vim starter (1) vim-cheat-sheet vim cheat-sheet (1) vimeo (1) visual stuio (1) warsaw (1) wiki (1) wikipedia (1) window (1) windows 7 (1) windows 8 (1) windows programs (1) windows reinstall (1) windows utility batch perl space Windows::Clipboard (1) wisdoms (1) workflow (1) worth-reading (1) wrapper (1) xp_cmdshell (1) xslt (1) youtube (1)

Blog Archive

Translate with Google Translate

My Blog List