Search This Blog

Loading...

4.29.2009

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

4.28.2009

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.

4.26.2009

If you care about Global Warming and fast cars watch this !!!

SOURCES:
Talk of Better Place's CEO Shi Agasi

The new videos for VSTM ... Funny ; )

4.23.2009

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/

4.22.2009

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


4.21.2009

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.

4.20.2009

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>

4.19.2009

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 ...

4.18.2009

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

4.10.2009

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'

4.09.2009

the small functions helping self aware database



--so remember to set the ext props on db level ... 
USE [DBGA_DEV]
GO

/****** Object:  UserDefinedFunction [ga].[GetDbType]    Script Date: 04/09/2009 22:40:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




CREATE FUNCTION [ga].[GetDbType]()
RETURNS VARCHAR(30)
BEGIN
RETURN convert(varchar(30) , (select value from sys.extended_properties where name='DbType' and class_desc='DATABASE') )
END




GO


USE [DBGA_DEV]
GO

/****** Object:  UserDefinedFunction [ga].[GetDbVersion]    Script Date: 04/09/2009 22:41:27 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE FUNCTION [ga].[GetDbVersion]()
RETURNS VARCHAR(20)
BEGIN
RETURN convert(varchar(20) , (select value from sys.extended_properties where name='DbVersion' and class_desc='DATABASE') )
END



GO

EXEC sys.sp_addextendedproperty @name=N'AuthorName', @value=N'Yordan Georgiev' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO

EXEC sys.sp_addextendedproperty @name=N'ChangeDescription', @value=N'Initial creation' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO

EXEC sys.sp_addextendedproperty @name=N'CreatedWhen', @value=N'getDate()' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO

EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Gets the current version of the database ' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'FUNCTION',@level1name=N'GetDbVersion'
GO

the table structures supporting the self aware database



USE [DBGA_DEV]
GO

/****** Object:  Table [ga].[tb_DataMeta_ObjChangeLog]    Script Date: 04/09/2009 22:38:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [ga].[tb_DataMeta_ObjChangeLog](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[TimeStamp] [timestamp] NOT NULL,
[DatabaseName] [varchar](256) NOT NULL,
[DbVersion] [varchar](20) NOT NULL,
[DbType] [varchar](20) NOT NULL,
[EventType] [varchar](50) NOT NULL,
[ObjectName] [varchar](256) NOT NULL,
[ObjectType] [varchar](25) NOT NULL,
[SqlCommand] [varchar](max) NOT NULL,
[EventDate] [datetime] NOT NULL,
[LoginName] [varchar](256) NOT NULL,
[FirstName] [varchar](256) NULL,
[LastName] [varchar](50) NULL,
[ChangeDescription] [varchar](1000) NULL,
[Description] [varchar](1000) NULL,
[ObjVersion] [varchar](20) NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING ON
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_DataMeta_ObjChangeLog', @level2type=N'COLUMN',@level2name=N'Description'
GO

ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_DbVersion]  DEFAULT ('select ga.GetDbVersion()') FOR [DbVersion]
GO

ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_EventDate]  DEFAULT (getdate()) FOR [EventDate]
GO

ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_ChangeDescription]  DEFAULT ('TODO:DESCRIBE HERE WHAT KIND OF CHANGE YOU HAVE PERFORMED') FOR [ChangeDescription]
GO

ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_Description]  DEFAULT ('TODO:DESCRIBE HERE WHAT IS THE PURPOSE OF THIS OBJECT') FOR [Description]
GO

ALTER TABLE [ga].[tb_DataMeta_ObjChangeLog] ADD  CONSTRAINT [DF_tb_DataMeta_ObjChangeLog_ObjVersion]  DEFAULT ('0.0.0') FOR [ObjVersion]
GO




USE [DBGA_DEV]
GO

/****** Object:  Table [ga].[tb_BLSec_LoginsForUsers]    Script Date: 04/09/2009 22:39:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [ga].[tb_BLSec_LoginsForUsers](
[LoginsForUsersId] [int] IDENTITY(1,1) NOT NULL,
[LoginName] [nvarchar](100) NOT NULL,
[FirstName] [varchar](100) NOT NULL,
[SecondName] [varchar](100) NULL,
[LastName] [varchar](100) NOT NULL,
[DomainName] [varchar](100) NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING ON
GO



USE [DBGA_DEV]
GO

/****** Object:  Table [ga].[tb_BLSec_Users]    Script Date: 04/09/2009 22:39:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [ga].[tb_BLSec_Users](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](100) NOT NULL,
[SecondName] [varchar](100) NULL,
[LastName] [varchar](100) NOT NULL,
[DomainName] [varchar](100) NOT NULL,
[RoleId] [int] NOT NULL,
[Password] [nvarchar](100) NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING ON
GO

EXEC sys.sp_addextendedproperty @name=N'AuthorId', @value=N'1' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'AuthorName', @value=N'Yordan Georgiev' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'ChangeDescription', @value=N'Describe the change you have created while changing the table here' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'DbVersion', @value=N'0.1.0.20090406.1200' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'TableDescription', @value=N'TODO:ADD DESCRPTION' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'TableDescrpiption', @value=N'Models a user using the GenApp , with the minimum set of properties which enables it the usage of the ' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'TABLETYPE', @value=N'SECURITY' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

EXEC sys.sp_addextendedproperty @name=N'TableVersion', @value=N'0.1.0.20090406.1317' , @level0type=N'SCHEMA',@level0name=N'ga', @level1type=N'TABLE',@level1name=N'tb_BLSec_Users'
GO

A trigger forcing the sql server 2005 2008 to meta know itself

/****** Object: DdlTrigger [trig_BackUpDbObjects] Script Date: 04/09/2009 20:55:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




create trigger [trig_BackUpDbObjects]
on database
for create_procedure, alter_procedure, drop_procedure,
create_table, alter_table, drop_table,
create_function, alter_function, drop_function
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)


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

values(

@DbName,
@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 [trig_BackUpDbObjects] ON DATABASE
GO

ENABLE TRIGGER [trig_BackUpDbObjects] 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

4.04.2009

an example of easy to create and use multilingual dictionary page

SOURCES:
http://fs18545.flosoft-servers.net/dic/index.html

I have set it up in Opera ( Nowadays it should be possible also in Firefox 3 and chrome ) on the Ctrl + 3, Thus to find a new English word in my mother language + Finnish , Swedish ..etc . is as simple as
- Select and copy word
- Ctrl + 3
- Ctrl + V
- Enter

So the trick is to find dictionary sites which do expose post url params and find out the pattern to recreate it in a simple frame page ...


Of course if you start getting greedy and put some advert banners etc. you might want to check first the juridic stuff on the sites you are utilizing ...

I dare to say that in the last 3 years despite of my age I have improved my overall English , Finnish , German and Swedish skills by using this type of home grown mashup ...

4.03.2009

Get back up no matter how-many times you fail ...

Born with no limbs, Nick Vujicic faces obstacles every day of his life. It's not how you start, it's how you finish. Want to motivate your sales team, employees, studen...

exec sp_HelpText procUtils_SqlCheatSheet

CREATE PROCEDURE [procUtils_SqlCheatSheet]

as
set nocount on

--what was the name of the table with something like role
/*
SELECT * from sys.tables where [name] like '%POC%'
*/
-- what are the columns of this table
/*
select column_name , DATA_TYPE , CHARACTER_MAXIMUM_LENGTH, table_name from Information_schema.columns where table_name='tbGui_ExecutePOC'
*/

-- find proc
--what was the name of procedure with something like role
/*
select * from sys.procedures where [name] like '%ext%'
exec sp_HelpText procName
*/
/*
exec sp_helpText procUtils_InsertGenerator
*/
--how to list all databases in sql server
/*
SELECT database_id AS ID, NULL AS ParentID, name AS Text FROM sys.databases ORDER BY [name]
*/

--HOW-TO LIST ALL TABLES IN A SQL SERVER 2005 DATABASE
/*
SELECT TABLE_NAME FROM [POC].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME <> 'dtproperties'
ORDER BY TABLE_NAME


*/
--HOW-TO ENABLE XP_CMDSHELL START
-------------------------------------------------------------------------
-- configure verbose mode temporarily
-- EXECUTE sp_configure 'show advanced options', 1
-- RECONFIGURE WITH OVERRIDE
--GO


--ENABLE xp_cmdshell
-- EXECUTE sp_configure 'xp_cmdshell', '1'
-- RECONFIGURE WITH OVERRIDE
-- EXEC SP_CONFIGURE 'show advanced option', '1';
-- SHOW THE CONFIGURATION
-- EXEC SP_CONFIGURE;


--turn show advance options off
-- GO
--EXECUTE sp_configure 'show advanced options', 0
-- RECONFIGURE WITH OVERRIDE
-- GO

--HOW-TO ENABLE XP_CMDSHELL END
-------------------------------------------------------------------------

--HOW-TO IMPLEMENT SLEEP
-- sleep for 10 seconds
-- WAITFOR DELAY '00:00:10' SELECT * FROM My_Table

/* LIST ALL PRIMARY KEYS

SELECT
INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME AS TABLE_NAME,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE.COLUMN_NAME AS COLUMN_NAME,
REPLACE(INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE,' ', '_') AS CONSTRAINT_TYPE
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON
INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME =
INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME
WHERE
INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME <> N'sysdiagrams'
ORDER BY
INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME ASC

*/

--HOW-TO COPY TABLE AND THE WHOLE TABLE DATA , COPY TABLE FROM DB TO DB
--==================================================START
/*
use Poc_Dev
go
drop table tbGui_LinksVisibility

use POc_test
go
select *
INTO [POC_Dev].[dbo].[tbGui_LinksVisibility]
from [POC_TEST].[dbo].[tbGui_LinksVisibility]


*/
--HOW-TO COPY TABLE AND THE WHOLE TABLE DATA , COPY TABLE FROM DB TO DB
--====================================================END
--=================================================== SEE TABLE METADATA START
/*



SELECT c.name AS [COLUMN_NAME], sc.data_type AS [DATA_TYPE], [value] AS
[DESCRIPTION] , c.max_length as [MAX_LENGTH] , c.is_nullable AS [OPTIONAL]
, c.is_identity AS [IS_PRIMARY_KEY] FROM sys.extended_properties AS ep
INNER JOIN sys.tables AS t ON ep.major_id = t.object_id
INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id
= c.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and
c.name = sc.column_name
WHERE class = 1 and t.name = 'tbGui_ExecutePOC' ORDER BY SC.DATA_TYPE


*/
--=================================================== SEE TABLE METADATA END
/*
select * from Information_schema.columns
select table_name , column_name from Information_schema.columns where table_name='tbGui_Wizards'
*/


--=================================================== LIST ALL TABLES AND THEIR DESCRIPTOINS START
/*

SELECT T.name AS TableName, CAST(Props.value AS varchar(1000)) AS
TableDescription
FROM sys.tables AS T LEFT OUTER JOIN
(SELECT class, class_desc, major_id, minor_id,
name, value
FROM sys.extended_properties
WHERE (minor_id = 0) AND (class = 1)) AS
Props ON T.object_id = Props.major_id
WHERE (T.type = 'U') AND (T.name <> N'sysdiagrams')
ORDER BY TableName
*/
--=================================================== LIST ALL TABLES AND THEIR DESCRIPTOINS START

--=================================================== LIST ALL OBJECTS FROM DB START
/*


use DB
--HOW-TO LIST ALL PROCEDURE IN A DATABASE
select s.name from sysobjects s where type = 'P'
--HOW-TO LIST ALL TRIGGERS BY NAME IN A DATABASE
select s.name from sysobjects s where type = 'TR'
--HOW-TO LIST TABLES IN A DATABASE
select s.name from sysobjects s where type = 'U'
--how-to list all system tables in a database
select s.name from sysobjects s where type = 's'
--how-to list all the views in a database
select s.name from sysobjects s where type = 'v'


*/

/*
Similarly you can find out other objects created by user, simple change type =

C = CHECK constraint

D = Default or DEFAULT constraint

F = FOREIGN KEY constraint

L = Log

FN = Scalar function

IF = In-lined table-function

P = Stored procedure

PK = PRIMARY KEY constraint (type is K)

RF = Replication filter stored procedure

S = System table

TF = Table function

TR = Trigger

U = User table ( this is the one I discussed above in the example)

UQ = UNIQUE constraint (type is K)

V = View

X = Extended stored procedure
*/



--=================================================== HOW-TO SEE ALL MY PERMISSIONS START


/*

SELECT * FROM fn_my_permissions(NULL, 'SERVER');
USE poc_qa;
SELECT * FROM fn_my_permissions (NULL, 'database');
GO

*/
--=================================================== HOW-TO SEE ALL MY PERMISSIONS END

/*
--find table

use poc_dev
go
select s.name from sysobjects s where type = 'u' and s.name like '%Visibility%'
select * from tbGui_LinksVisibility

*/

/* find cursor

use poc
go
DECLARE @procName varchar(100)
DECLARE @cursorProcNames CURSOR
SET @cursorProcNames = CURSOR FOR
select name from sys.procedures where modify_date > '2009-02-05 13:12:15.273' order by modify_date desc

OPEN @cursorProcNames
FETCH NEXT
FROM @cursorProcNames INTO @procName
WHILE @@FETCH_STATUS = 0
BEGIN

set nocount off;
exec sp_HelpText @procName --- or print them
-- print @procName

FETCH NEXT
FROM @cursorProcNames INTO @procName
END
CLOSE @cursorProcNames

select @@error

*/


/* -- SEE STORED PROCEDURE EXT PROPS

SELECT ep.name as 'EXT_PROP_NAME' , SP.NAME , [value] as 'DESCRIPTION' FROM sys.extended_properties as ep left join sys.procedures as sp on sp.object_id = ep.major_id where sp.type='P'

-- SEE STORED PROCEDURE EXT PROPS end*/
set nocount off

Blog Archive

My Blog List

Video Bar

Loading...

About Me

My Photo
Yordan Georgiev
It is one thing to know what to want, second to really want it, third to know how to do it, fourth to be skillful to do it, fifth to actually do it and last but not least to go on without regrets after having done it. LinkedIn Profile
View my complete profile