summaryrefslogtreecommitdiffstats
path: root/projecttemplates/RelyingPartyLogic/Database.cs
blob: 58f372f8c5844df0b07475547231df5984f033bc (plain)
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
//-----------------------------------------------------------------------
// <copyright file="Database.cs" company="Outercurve Foundation">
//     Copyright (c) Outercurve Foundation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace RelyingPartyLogic {
	using System;
	using System.Collections.Generic;
	using System.Data;
	using System.Data.EntityClient;
	using System.Data.SqlClient;
	using System.Linq;
	using System.ServiceModel;
	using System.Text;
	using System.Web;

	public class Database : IHttpModule, IDisposable {
		private const string DataContextKey = "DataContext";

		private const string DataContextTransactionKey = "DataContextTransaction";

		/// <summary>
		/// Initializes a new instance of the <see cref="Database"/> class.
		/// </summary>
		public Database() {
		}

		public static User LoggedInUser {
			get { return DataContext.AuthenticationTokens.Where(token => token.ClaimedIdentifier == HttpContext.Current.User.Identity.Name).Select(token => token.User).FirstOrDefault(); }
		}

		/// <summary>
		/// Gets the transaction-protected database connection for the current request.
		/// </summary>
		public static DatabaseEntities DataContext {
			get {
				DatabaseEntities dataContext = DataContextSimple;
				if (dataContext == null) {
					dataContext = new DatabaseEntities();
					dataContext.Connection.Open();
					DataContextTransaction = (EntityTransaction)dataContext.Connection.BeginTransaction();
					DataContextSimple = dataContext;
				}

				return dataContext;
			}
		}

		/// <summary>
		/// Gets a value indicating whether the data context is already initialized.
		/// </summary>
		internal static bool IsDataContextInitialized {
			get { return DataContextSimple != null; }
		}

		internal static EntityTransaction DataContextTransaction {
			get {
				if (HttpContext.Current != null) {
					return HttpContext.Current.Items[DataContextTransactionKey] as EntityTransaction;
				} else if (OperationContext.Current != null) {
					object data;
					if (OperationContext.Current.IncomingMessageProperties.TryGetValue(DataContextTransactionKey, out data)) {
						return data as EntityTransaction;
					} else {
						return null;
					}
				} else {
					throw new InvalidOperationException();
				}
			}

			private set {
				if (HttpContext.Current != null) {
					HttpContext.Current.Items[DataContextTransactionKey] = value;
				} else if (OperationContext.Current != null) {
					OperationContext.Current.IncomingMessageProperties[DataContextTransactionKey] = value;
				} else {
					throw new InvalidOperationException();
				}
			}
		}

		private static DatabaseEntities DataContextSimple {
			get {
				if (HttpContext.Current != null) {
					return HttpContext.Current.Items[DataContextKey] as DatabaseEntities;
				} else if (OperationContext.Current != null) {
					object data;
					if (OperationContext.Current.IncomingMessageProperties.TryGetValue(DataContextKey, out data)) {
						return data as DatabaseEntities;
					} else {
						return null;
					}
				} else {
					throw new InvalidOperationException();
				}
			}

			set {
				if (HttpContext.Current != null) {
					HttpContext.Current.Items[DataContextKey] = value;
				} else if (OperationContext.Current != null) {
					OperationContext.Current.IncomingMessageProperties[DataContextKey] = value;
				} else {
					throw new InvalidOperationException();
				}
			}
		}

		public void Dispose() {
		}

		void IHttpModule.Init(HttpApplication context) {
			context.EndRequest += this.Application_EndRequest;
			context.Error += this.Application_Error;
		}

		protected void Application_EndRequest(object sender, EventArgs e) {
			CommitAndCloseDatabaseIfNecessary();
		}

		protected void Application_Error(object sender, EventArgs e) {
			if (DataContextTransaction != null) {
				DataContextTransaction.Rollback();
				DataContextTransaction.Dispose();
				DataContextTransaction = null;
			}
		}

		private static void CommitAndCloseDatabaseIfNecessary() {
			var dataContext = DataContextSimple;
			if (dataContext != null) {
				dataContext.SaveChanges();
				if (DataContextTransaction != null) {
					DataContextTransaction.Commit();
					DataContextTransaction.Dispose();
				}

				dataContext.Dispose();
				DataContextSimple = null;
			}
		}
	}
}