Click here to Skip to main content
12,446,525 members (54,888 online)
Click here to Skip to main content

Stats

15.7K views
960 downloads
21 bookmarked
Posted

Signum Framework Tutorials Part 2 – Southwind Logic

, 15 Nov 2012 LGPL3
In this part, we will focus on writing business logic, LINQ queries and explain inheritance
Northwind.bak
signumframework-signumframework-c6436e1
.gitignore
Local.testsettings
README.md
Signum.Engine
ClassDiagram1.cd
Connection
DynamicQuery
Engine
Linq
ExpressionVisitor
Meta
Properties
Schema
Schema.cd
SchemaBuilder
SignumFramework.pfx
Signum.Entities
Attributes.cd
Basics
ClassDiagram1.cd
Diagram.cd
DynamicQuery
Tokens
Patterns
Properties
Reflection
Services
SignumFramework.pfx
Signum.Framework.vsmdi
Signum.Test
ClassDiagram1.cd
LinqProvider
Properties
Signum.Utilities
DataStructures
IntervalDictionaries
ExpressionTrees
Properties
Reflection
SignumFramework.pfx
Synchronization
Signum.Web
ButtonBar
ControllerAttributes
Facades
HtmlHelpers
JSRenderer
LineHelpers
Lines
Mappings
PortableAreas
Repositories
Properties
Signum
Content
Controllers
Images
asc.gif
calendar.png
desc.gif
lineButtons.gif
sign_error.gif
Models
Scripts
Views
Widgets
SignumFramework.pfx
TypeContext
Widgets
Signum.Windows
Basics
Controls
ColorUtils
Converters
DynamicQuery
EntityControls
Facades
Fluent
Images
admin.png
alert.png
calendar.png
cancel.png
close.png
entity.png
find.png
forbidden.png
newColumn.png
newFilter.png
note.png
ok.png
pin.png
reload.png
save.png
star.png
Localization
MarkupExtensions
Properties
SignumFramework.pfx
Themes
Utilities
Widgets
SignumFrameworkSetup
SignumFrameworkSetup.vdproj
logo.ico
signumFramework2.0.jpg
Snippets
DroidSansMono.ttf
RazorSingleFileGenerator.vsix
Signum.Fonts.vssettings
T4template
entity.snippet
entityWithName.snippet
expressionMethod.snippet
expressionMethodQuery.snippet
expressionProperty.snippet
field.snippet
fieldCreacion.snippet
fieldEuro.snippet
fieldInicioFin.snippet
fieldString.snippet
fiff.snippet
propiedad.snippet
tran.snippet
Template
EntityControlTemplate
MyTemplate.vstemplate
SignumEntityControl.zip
__TemplateIcon.ico
Template
MyTemplate.vstemplate
ProjectName.Entities
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
ProjectName.Load
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
ProjectName.Logic
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
ProjectName.Web
Code
Content
smoothness
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Controllers
Global.asax
MyTemplate.vstemplate
Properties
Scripts
ServerCapri.svc
Views
Capri
Home
Shared
__TemplateIcon.ico
favicon.ico
ProjectName.Windows
Controls
MyTemplate.vstemplate
Properties
__TemplateIcon.ico
SignumFramework2ClientServer.zip
__TemplateIcon.ico
WizardProjectName
Test
Properties
WizardProjectName
Isolated
Properties
SignumFramework.pfx
TraceAndTestImpact.testsettings
SignumFramework2Setup.msi
.gitignore
README.md
Southwind.vssscc
Southwind
Southwind.Entities
Properties
Southwind.Load
Properties
Southwind.Logic
Properties
Southwind.Web
Code
Content
smoothness
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Controllers
Global.asax
Properties
Scripts
ServerSouthwind.svc
Views
Home
Shared
Southwind
favicon.ico
Southwind.Windows
Controls
Properties
Southwind.bak
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Signum.Utilities.DataStructures;
using Signum.Utilities;
using System.Diagnostics;
using System.IO;
using Signum.Engine.Properties;
using Signum.Entities;

namespace Signum.Engine
{
    /// <summary>
    /// Allows easy nesting of transaction using 'using' statement
    /// Keeps an implicit stack of Transaction objects over the StackTrace of the current Thread
    /// and an explicit ThreadStatic stack of RealTransaction objects.
    /// Usually, just the first Transaccion creates a RealTransaction, but you can create more using 
    /// forceNew = true
    /// All Transaction can cancel but only the one that created the RealTransaction can Commit 
    /// </summary>
    public class Transaction : IDisposable
    {
        public static Action<string, StackTrace> UnexpectedBehaviourCallback { get; set; }

        static Transaction()
        {
            UnexpectedBehaviourCallback = (msg, st) => Debug.WriteLine(msg); 
        }

        static void NotifyRollback()
        {
            UnexpectedBehaviourCallback("TRANSACTION ROLLBACKED!", new StackTrace(2, true));
        }

        [ThreadStatic]
        static Dictionary<BaseConnection, ICoreTransaction> currents;

        bool commited;
        ICoreTransaction coreTransaction; 

        interface ICoreTransaction
        {
            event Action RealCommit;
            event Action PreRealCommit;
            SqlConnection Connection { get; }
            SqlTransaction Transaction { get; }
            DateTime Time { get; }
            bool RolledBack { get; }
            bool Started { get; }
            void Rollback();
            void Commit();
            ICoreTransaction Finish();
            void Start();

            Dictionary<string, object> UserData { get; }
        }
     
        class FakedTransaction : ICoreTransaction
        {
            ICoreTransaction parent;

            public FakedTransaction(ICoreTransaction parent)
            {
                this.parent = parent;
            }

            public event Action RealCommit
            {
                add { parent.RealCommit += value; }
                remove { parent.RealCommit -= value; }
            }

            public event Action PreRealCommit
            {
                add { parent.PreRealCommit += value; }
                remove { parent.PreRealCommit -= value; }
            }

            public SqlConnection Connection{ get { return parent.Connection; } }
            public SqlTransaction Transaction{ get { return parent.Transaction; } }
            public DateTime Time{ get { return parent.Time;} }
            public bool RolledBack { get{ return parent.RolledBack;} }
            public bool Started { get { return parent.Started; } }

            public void Start() { parent.Start(); }

            public void Rollback()
            {
                parent.Rollback(); 
            }

            public void Commit(){ }

            public ICoreTransaction Finish() { return parent; }

            public Dictionary<string, object> UserData
            {
                get { return parent.UserData; }
            }
        }

        class RealTransaction : ICoreTransaction
        {
            ICoreTransaction parent; 

            public SqlConnection Connection { get; private set; }
            public SqlTransaction Transaction { get; private set; }
            public DateTime Time { get; private set; }
            public bool RolledBack { get; private set; }
            public bool Started { get; private set; }
            public event Action RealCommit;
            public event Action PreRealCommit;

            IsolationLevel? IsolationLevel;

            public RealTransaction(ICoreTransaction parent, IsolationLevel? isolationLevel)
            {
                IsolationLevel = isolationLevel;
                Time = TimeZoneManager.Now;
                this.parent = parent;
            }

            public void Start()
            {
                if (!Started)
                {
                    Connection con = (Connection)ConnectionScope.Current;
                    Connection = new SqlConnection(con.ConnectionString);
                    
                    Connection.Open();
                    Transaction = Connection.BeginTransaction(IsolationLevel ?? con.IsolationLevel);
                    Started = true;
                }
            }

            public void Commit()
            {
                if (Started)
                {
                    if (PreRealCommit != null)
                        PreRealCommit(); 

                    Transaction.Commit();

                    if (RealCommit != null)
                        RealCommit();  
                }
            }

            public void Rollback()
            {
                if (Started && !RolledBack)
                {
                    Transaction.Rollback();
                    NotifyRollback();
                    RolledBack = true;
                }
            }

            public ICoreTransaction Finish()
            {
                if (Transaction != null)
                {
                    Transaction.Dispose();
                    Transaction = null;
                }

                if (Connection != null)
                {
                    Connection.Dispose();
                    Connection = null;
                }

                return parent;
            }

            Dictionary<string, object> userData;
            public Dictionary<string, object> UserData
            {
                get { return userData ?? (userData = new Dictionary<string, object>());  }
            }
        }

        class NamedTransaction : ICoreTransaction
        {
            ICoreTransaction parent;
            string savePointName;
            public bool RolledBack { get; private set; }
            public bool Started { get; private set; }

            public NamedTransaction(ICoreTransaction parent, string savePointName)
            {
                this.parent = parent;
                this.savePointName = savePointName;
            }

            public event Action RealCommit
            {
                add { parent.RealCommit += value; }
                remove { parent.RealCommit -= value; }
            }

            public event Action PreRealCommit
            {
                add { parent.PreRealCommit += value; }
                remove { parent.PreRealCommit -= value; }
            }

            public SqlConnection Connection { get { return parent.Connection; } }
            public SqlTransaction Transaction { get { return parent.Transaction; } }
            public DateTime Time { get { return parent.Time; } }

            public void Start()
            {
                if (!Started)
                {
                    parent.Start();
                    Transaction.Save(savePointName);
                    Started = true;
                }
            }

            public void Rollback()
            {
                if (Started && !RolledBack)
                {
                    Transaction.Rollback(savePointName);
                    NotifyRollback();
                    RolledBack = true;
                }
            }

            public void Commit() { }

            public ICoreTransaction Finish() { return parent; }

            public Dictionary<string, object> UserData
            {
                get { return parent.UserData; }
            }
        }

        class NoneTransaction : ICoreTransaction
        {
            ICoreTransaction parent;

            public SqlConnection Connection { get; private set; }
            public SqlTransaction Transaction { get{return null;}}
            public DateTime Time { get; private set; }
            public bool RolledBack { get; private set; }
            public bool Started { get; private set; }
            public event Action RealCommit;
            public event Action PreRealCommit;

            public NoneTransaction(ICoreTransaction parent)
            {
                Time = TimeZoneManager.Now;
                this.parent = parent;
            }

            public void Start()
            {
                if (!Started)
                {
                    Connection con = (Connection)ConnectionScope.Current;
                    Connection = new SqlConnection(con.ConnectionString);

                    Connection.Open();
                    //Transaction = Connection.BeginTransaction(IsolationLevel ?? con.IsolationLevel);
                    Started = true;
                }
            }

            public void Commit()
            {
                if (Started)
                {
                    if (PreRealCommit != null)
                        PreRealCommit();

                    //Transaction.Commit();

                    if (RealCommit != null)
                        RealCommit();
                }
            }

            public void Rollback()
            {
                if (Started && !RolledBack)
                {
                    //Transaction.Rollback();
                    NotifyRollback();
                    RolledBack = true;
                }
            }

            public ICoreTransaction Finish()
            {
                //if (Transaction != null)
                //{
                //    Transaction.Dispose();
                //    Transaction = null;
                //}

                if (Connection != null)
                {
                    Connection.Dispose();
                    Connection = null;
                }

                return parent;
            }

            Dictionary<string, object> userData;
            public Dictionary<string, object> UserData
            {
                get { return userData ?? (userData = new Dictionary<string, object>()); }
            }
        }

        public Transaction():this(false){}

        public Transaction(bool forceNew)
        {
            BaseConnection bc = AssertConnection();

            ICoreTransaction parent = currents.TryGetC(bc);
            if (parent == null || forceNew)
            {
                currents[bc] = coreTransaction = new RealTransaction(parent, null);
            }
            else
            {
                AssertTransaction();
                currents[bc] = coreTransaction = new FakedTransaction(parent);
            }
        }
    
        Transaction(BaseConnection bc, ICoreTransaction transaction)
        {
            currents[bc] = coreTransaction = transaction;
        }

        public static Transaction None()
        {
            BaseConnection bc = AssertConnection();

            ICoreTransaction parent = currents.TryGetC(bc);

            return new Transaction(bc, new NoneTransaction(parent));
        }

        public static Transaction NamedSavePoint(string savePointName)
        {
            BaseConnection bc = AssertConnection();

            ICoreTransaction parent = GetCurrent();
            return new Transaction(bc, new NamedTransaction(parent, savePointName));
        }

        public static Transaction ForceNew()
        {
            return ForceNew(null);
        }

        public static Transaction ForceNew(IsolationLevel? isolationLevel)
        {
            BaseConnection bc = AssertConnection();

            ICoreTransaction parent = currents.TryGetC(bc);

            return new Transaction(bc, new RealTransaction(parent, isolationLevel));
        }

        private static BaseConnection AssertConnection()
        {
            if (currents == null)
                currents = new Dictionary<BaseConnection, ICoreTransaction>();

            BaseConnection bc = ConnectionScope.Current;

            if (bc == null)
                throw new InvalidOperationException("ConnectionScope.Current not established. Use ConnectionScope.Default to do it.");
            return bc;
        }

        
        void AssertTransaction()
        {
            if (GetCurrent().RolledBack)
                throw new InvalidOperationException("The transation is RolledBack");
        }

        static ICoreTransaction GetCurrent()
        {
            return currents.GetOrThrow(ConnectionScope.Current, "No Transaction created yet");
        }

        public static event Action RealCommit
        {
            add { GetCurrent().RealCommit += value; }
            remove { GetCurrent().RealCommit -= value; }
        }

        public static event Action PreRealCommit
        {
            add { GetCurrent().PreRealCommit += value; }
            remove { GetCurrent().PreRealCommit -= value; }
        }

        public static Dictionary<string, object> UserData
        {
            get { return GetCurrent().UserData; }
        }

        public static bool HasTransaction
        {
            get { return currents != null && currents.ContainsKey(ConnectionScope.Current); }
        }

        public static SqlConnection CurrentConnection
        {
            get
            {
                ICoreTransaction tran = GetCurrent();
                tran.Start();
                return tran.Connection;
            }
        }

        public static SqlTransaction CurrentTransaccion
        {
            get
            {
                ICoreTransaction tran = GetCurrent();
                tran.Start();
                return tran.Transaction;
            }
        }


        public static DateTime StartTime
        {
            get
            {
                ICoreTransaction tran = GetCurrent();
                return tran.Time;
            }
        }

        public T Commit<T>(T returnValue)
        {
            Commit();
            return returnValue;
        }

        public void Commit()
        {
            AssertTransaction();

            coreTransaction.Commit();

            commited = true;
        }

        public void Dispose()
        {
            if (!commited)
                coreTransaction.Rollback();

            ICoreTransaction parent = coreTransaction.Finish();

            if (parent == null)
                currents.Remove(ConnectionScope.Current);
            else
                currents[ConnectionScope.Current] = parent;
        }

        public static void ForceClean()
        {
            if (currents != null && currents.Count != 0)
            {
                UnexpectedBehaviourCallback("DIRTY TRANSACTIONS FOUND!", new StackTrace(1));
                currents.Clear();
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

Olmo del Corral
Software Developer (Senior) Signum Software
Spain Spain
I'm Computer Scientist, one of the founders of Signum Software, and the lead developer behind Signum Framework.

www.signumframework.com

I love programming in C#, Linq, Compilers, Algorithms, Functional Programming, Computer Graphics, Maths...

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160811.3 | Last Updated 15 Nov 2012
Article Copyright 2011 by Olmo del Corral
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid