summaryrefslogtreecommitdiffstats
path: root/projecttemplates/RelyingPartyLogic/Utilities.cs
blob: affbe26e0558f2c8f81dd6c024e66bb5aac8b31f (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
//-----------------------------------------------------------------------
// <copyright file="Utilities.cs" company="Andrew Arnott">
//     Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace RelyingPartyLogic {
	using System;
	using System.Collections.Generic;
	using System.Globalization;
	using System.IO;
	using System.Linq;
	using System.Reflection;
	using System.Text;
	using System.Web;
	using DotNetOpenAuth.OpenId;
	using Microsoft.SqlServer.Management.Common;
	using Microsoft.SqlServer.Management.Smo;

	public class Utilities {
		internal const string DefaultNamespace = "RelyingPartyLogic";

		/// <summary>
		/// Gets the full URI of the web application root.  Guaranteed to end in a slash.
		/// </summary>
		public static Uri ApplicationRoot {
			get {
				string appRoot = HttpContext.Current.Request.ApplicationPath;
				if (!appRoot.EndsWith("/", StringComparison.Ordinal)) {
					appRoot += "/";
				}

				return new Uri(HttpContext.Current.Request.Url, appRoot);
			}
		}

		public static void CreateDatabase(Identifier claimedId, string friendlyId) {
			const string SqlFormat = @"
CREATE DATABASE [{0}] ON (NAME='{0}', FILENAME='{0}')
GO
USE ""{0}""
GO
{1}
EXEC [dbo].[AddUser] 'admin', 'admin', '{2}', '{3}'
GO
";
			string schemaSql;
			using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(DefaultNamespace + ".CreateDatabase.sql"))) {
				schemaSql = sr.ReadToEnd();
			}
			string databasePath = HttpContext.Current.Server.MapPath("~/App_Data/Database.mdf");
			string sql = string.Format(CultureInfo.InvariantCulture, SqlFormat, databasePath, schemaSql, claimedId, "Admin");

			var serverConnection = new ServerConnection(".\\sqlexpress");
			try {
				serverConnection.ExecuteNonQuery(sql);
				var server = new Server(serverConnection);
				server.DetachDatabase(databasePath, true);
			} finally {
				serverConnection.Disconnect();
			}
		}

		internal static void VerifyThrowNotLocalTime(DateTime value) {
			// When we want UTC time, we have to accept Unspecified kind
			// because that's how it is set to us in the database.
			if (value.Kind == DateTimeKind.Local) {
				throw new ArgumentException("DateTime must be given in UTC time but was " + value.Kind.ToString());
			}
		}
	}
}