File: SharedConnectionWorkflowTransactionService.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (295 lines) | stat: -rw-r--r-- 12,500 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#pragma warning disable 1634, 1691
//------------------------------------------------------------------------------
// <copyright file="SharedConnectionWorkflowTransactionService.cs" company="Microsoft">
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

#region Using directives

using System;
using System.Transactions;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Threading;
#endregion

namespace System.Workflow.Runtime.Hosting
{
    [Obsolete("The System.Workflow.* types are deprecated.  Instead, please use the new types from System.Activities.*")]
    public class SharedConnectionWorkflowCommitWorkBatchService : WorkflowCommitWorkBatchService
    {
        private DbResourceAllocator dbResourceAllocator;
        private IDictionary<Transaction, SharedConnectionInfo> transactionConnectionTable;
        private object tableSyncObject = new object();

        // Saved from constructor input to be used in service start initialization        
        private NameValueCollection configParameters;
        string unvalidatedConnectionString;
        private bool _enableRetries = false;
        private bool _ignoreCommonEnableRetries = false;

        /// <summary>
        /// Enables the adding of this service programmatically.
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="connectionString"></param>
        public SharedConnectionWorkflowCommitWorkBatchService(string connectionString)
        {
            if (String.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString", ExecutionStringManager.MissingConnectionString);

            this.unvalidatedConnectionString = connectionString;
        }

        /// <summary>
        /// Enables adding of this service from a config file.
        /// Get the connection string from the runtime common parameter section or the particular service parameter section 
        /// of the configuration file, and instantiate a DbResourceAllocator object.
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="parameters"></param>
        public SharedConnectionWorkflowCommitWorkBatchService(NameValueCollection parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException("parameters", ExecutionStringManager.MissingParameters);

            if (parameters.Count > 0)
            {
                foreach (string key in parameters.Keys)
                {
                    if (0 == string.Compare("EnableRetries", key, StringComparison.OrdinalIgnoreCase))
                    {
                        _enableRetries = bool.Parse(parameters[key]);
                        _ignoreCommonEnableRetries = true;
                    }
                }
            }

            this.configParameters = parameters;
        }

        #region Accessors
        internal string ConnectionString
        {
            get
            {
#pragma warning disable 56503
                if (this.dbResourceAllocator == null)
                {
                    // Other hosting services may try to get the connection string during their initialization phase 
                    // (in WorkflowRuntimeService.Start) to dectect string mismatch conflict
                    if (this.Runtime == null)
                        throw new InvalidOperationException(ExecutionStringManager.WorkflowRuntimeNotStarted);
                    this.dbResourceAllocator = new DbResourceAllocator(this.Runtime, this.configParameters, this.unvalidatedConnectionString);
                }
#pragma warning restore 56503
                return this.dbResourceAllocator.ConnectionString;
            }
        }

        public bool EnableRetries
        {
            get { return _enableRetries; }
            set
            {
                _enableRetries = value;
                _ignoreCommonEnableRetries = true;
            }
        }
        #endregion Accessors

        #region WorkflowRuntimeService
        override protected internal void Start()
        {
            WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SharedConnectionWorkflowCommitWorkBatchService: Starting");

            this.dbResourceAllocator = new DbResourceAllocator(this.Runtime, this.configParameters, this.unvalidatedConnectionString);            
            if (this.transactionConnectionTable == null)
                this.transactionConnectionTable = new Dictionary<Transaction, SharedConnectionInfo>();

            //
            // If we didn't find a local value for enable retries
            // check in the common section
            if ((!_ignoreCommonEnableRetries) && (null != base.Runtime))
            {
                NameValueConfigurationCollection commonConfigurationParameters = base.Runtime.CommonParameters;
                if (commonConfigurationParameters != null)
                {
                    // Then scan for connection string in the common configuration parameters section
                    foreach (string key in commonConfigurationParameters.AllKeys)
                    {
                        if (string.Compare("EnableRetries", key, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            _enableRetries = bool.Parse(commonConfigurationParameters[key].Value);
                            break;
                        }
                    }
                }
            }

            base.Start();
        }

        protected override void OnStopped()
        {
            WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SharedConnectionWorkflowCommitWorkBatchService: Stopping");
            foreach (KeyValuePair<Transaction, SharedConnectionInfo> kvp in this.transactionConnectionTable)
            {
                kvp.Value.Dispose();
                WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "Removing transaction " + kvp.Key.GetHashCode());
            }
            this.transactionConnectionTable.Clear();
            this.dbResourceAllocator = null;
            base.OnStopped();
        }
        #endregion Public Methods

        #region Public Methods

        protected internal override void CommitWorkBatch(WorkflowCommitWorkBatchService.CommitWorkBatchCallback commitWorkBatchCallback)
        {
            //
            // Disable retries by default, reset to allow retries below if we own the tx
            DbRetry dbRetry = new DbRetry(_enableRetries);
            short retryCounter = dbRetry.MaxRetries;

            while (true)
            {
                //
                // When using LocalTransaction handle block access to the connection 
                // in the transaction event handlers until all IPendingWork members have completed
                ManualResetEvent handle = new ManualResetEvent(false);
                Transaction tx = null;
                SharedConnectionInfo connectionInfo = null;

                try
                {
                    if (null == Transaction.Current)
                    {
                        //
                        // It's OK to retry here as we own the tx
                        retryCounter = 0;
                        //
                        // Create a local, non promotable transaction that we share with our OOB services
                        tx = new CommittableTransaction();
                        connectionInfo = new SharedConnectionInfo(this.dbResourceAllocator, tx, false, handle);
                    }
                    else
                    {
                        //
                        // Can't retry as we don't own the tx
                        // Create a dependent transaction and don't restrict promotion.
                        tx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                        connectionInfo = new SharedConnectionInfo(this.dbResourceAllocator, tx, true, handle);
                    }

                    AddToConnectionInfoTable(tx, connectionInfo);

                    using (TransactionScope ts = new TransactionScope(tx))
                    {
                        try
                        {
                            commitWorkBatchCallback();
                            ts.Complete();
                        }
                        finally
                        {
                            RemoveConnectionFromInfoTable(tx);
                            //
                            // Unblock transaction event handlers
                            handle.Set();
                        }
                    }

                    CommittableTransaction committableTransaction = tx as CommittableTransaction;
                    if (committableTransaction != null)
                        committableTransaction.Commit();

                    DependentTransaction dependentTransaction = tx as DependentTransaction;
                    if (dependentTransaction != null)
                        dependentTransaction.Complete();

                    break;
                }
                catch (Exception e)
                {
                    tx.Rollback();

                    WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SharedConnectionWorkflowCommitWorkBatchService caught exception from commitWorkBatchCallback: " + e.ToString());

                    if (dbRetry.TryDoRetry(ref retryCounter))
                    {
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SharedConnectionWorkflowCommitWorkBatchService retrying commitWorkBatchCallback (retry attempt " + retryCounter.ToString(System.Globalization.CultureInfo.InvariantCulture) + ")");
                        continue;
                    }
                    else
                        throw;
                }
                finally
                {
                    handle.Close();
                    if (tx != null)
                    {
                        tx.Dispose();
                    }
                }
            }
        }
        /// <summary>
        /// Get the SharedConnectionInfo object from the hashtable keyed by the transaction
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns></returns>
        internal SharedConnectionInfo GetConnectionInfo(Transaction transaction)
        {
            return LookupConnectionInfoTable(transaction);
        }

        #endregion Public Methods

        #region Private Methods

        private void RemoveConnectionFromInfoTable(Transaction transaction)
        {
            lock (this.tableSyncObject)
            {
                SharedConnectionInfo connectionInfo;
                WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "TransactionCompleted " + transaction.GetHashCode());
                if (transactionConnectionTable.TryGetValue(transaction, out connectionInfo))
                {
                    connectionInfo.Dispose();
                    this.transactionConnectionTable.Remove(transaction);
                }
                else
                {
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "TransactionCompleted " + transaction.GetHashCode() +
                        " not found in table of count " + this.transactionConnectionTable.Count);                
                }
            } 
        }

        private void AddToConnectionInfoTable(Transaction transaction, SharedConnectionInfo connectionInfo)
        {
            lock (this.tableSyncObject)
            {
                this.transactionConnectionTable.Add(transaction, connectionInfo);
                WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "AddToConnectionInfoTable " + transaction.GetHashCode() +
                        " in table of count " + this.transactionConnectionTable.Count); 
            }
        }

        private SharedConnectionInfo LookupConnectionInfoTable(Transaction transaction)
        {
            lock (this.tableSyncObject)
            {
                return transactionConnectionTable[transaction];
            }
        }

        #endregion Private Methods
    }
}