-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathCurrentEnvironment.cs
More file actions
248 lines (231 loc) · 9.55 KB
/
CurrentEnvironment.cs
File metadata and controls
248 lines (231 loc) · 9.55 KB
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
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;
using System.Data;
using MySql.Data.MySqlClient;
/// <summary>
/// Evaluates the running environment.
/// </summary>
public class CurrentEnvironment
{
private static readonly string PORT_ENV_VARIABLE_NAME = "PORT";
private static readonly string INSTANCE_GUID_ENV_VARIABLE_NAME = "INSTANCE_GUID";
private static readonly string INSTANCE_INDEX_ENV_VARIABLE_NAME = "INSTANCE_INDEX";
private static readonly string BOUND_SERVICES_ENV_VARIABLE_NAME = "VCAP_SERVICES";
private static readonly string SQLSERVER_CONNECTION_STRING_ENV_VARIABLE_NAME = "SQLSERVER_CONNECTION_STRING";
private static readonly string MYSQL_CONNECTION_STRING_ENV_VARIABLE_NAME = "MYSQL_CONNECTION_STRING";
private static readonly string NOT_ON_CLOUD_FOUNDRY_MESSAGE = "Not running in cloud foundry.";
/// <summary>
/// static constructor to determine the state of the environment and set defaults
/// </summary>
static CurrentEnvironment()
{
// Not on cloud foundry filling in the blanks.
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME)))
{
Environment.SetEnvironmentVariable(BOUND_SERVICES_ENV_VARIABLE_NAME, "{}");
Environment.SetEnvironmentVariable(PORT_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
Environment.SetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
Environment.SetEnvironmentVariable(INSTANCE_INDEX_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
}
// check to see if DB is bound via VCAP_SERVICES (CF)
// if not, check for environment variables (k8s)
// if also not set, check the web.config (local dev)
// finally default to no DB
if (BoundServices.GetValue("mssql-dev") != null) // sql server
{
DbEngine = DatabaseEngine.SqlServer;
_connectionString = BoundServices["mssql-dev"][0]["credentials"]["connectionString"].ToString();
}
else if (BoundServices.GetValue("p-mysql") != null)
{
DbEngine = DatabaseEngine.MySql;
MySqlConnectionStringBuilder csbuilder = new MySqlConnectionStringBuilder();
csbuilder.Add("server", BoundServices["p-mysql"][0]["credentials"]["hostname"].ToString());
csbuilder.Add("port", BoundServices["p-mysql"][0]["credentials"]["port"].ToString());
csbuilder.Add("uid", BoundServices["p-mysql"][0]["credentials"]["username"].ToString());
csbuilder.Add("pwd", BoundServices["p-mysql"][0]["credentials"]["password"].ToString());
csbuilder.Add("database", BoundServices["p-mysql"][0]["credentials"]["name"].ToString());
_connectionString = csbuilder.ToString();
}
else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(SQLSERVER_CONNECTION_STRING_ENV_VARIABLE_NAME)))
{
DbEngine = DatabaseEngine.SqlServer;
_connectionString = Environment.GetEnvironmentVariable(SQLSERVER_CONNECTION_STRING_ENV_VARIABLE_NAME);
}
else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(MYSQL_CONNECTION_STRING_ENV_VARIABLE_NAME)))
{
DbEngine = DatabaseEngine.MySql;
_connectionString = Environment.GetEnvironmentVariable(MYSQL_CONNECTION_STRING_ENV_VARIABLE_NAME);
}
else if (ConfigurationManager.ConnectionStrings["sqlserver"] != null)
{
DbEngine = DatabaseEngine.SqlServer;
_connectionString = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;
}
else if (ConfigurationManager.ConnectionStrings["mysql"] != null)
{
DbEngine = DatabaseEngine.MySql;
_connectionString = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
}
else
{
DbEngine = DatabaseEngine.None;
}
}
/// <summary>
/// Current server time.
/// </summary>
public static string CurrentTime
{
get { return DateTime.Now.ToString(); }
}
/// <summary>
/// .NET runtime version
/// </summary>
public static string CLRVersion
{
get { return Environment.Version.ToString(); }
}
/// <summary>
/// Uptime. This method appears to be machine wide and specific to the container.
/// </summary>
public static string Uptime
{
get {return DateTime.Now.Subtract(TimeSpan.FromMilliseconds(Environment.TickCount)).ToString(); }
}
/// <summary>
/// The local port the container is listening on
/// </summary>
public static string Port
{
get { return Environment.GetEnvironmentVariable(PORT_ENV_VARIABLE_NAME); }
}
/// <summary>
/// The instance GUID Cloud Foundry assigned to this app instance.
/// </summary>
public static string InstanceID
{
get { return Environment.GetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME); }
}
/// <summary>
/// The zero based index assigned to this instance of the app.
/// </summary>
public static string InstanceIndex
{
get { return Environment.GetEnvironmentVariable(INSTANCE_INDEX_ENV_VARIABLE_NAME); }
}
public static JObject BoundServices
{
get { return JObject.Parse(Environment.GetEnvironmentVariable(BOUND_SERVICES_ENV_VARIABLE_NAME)); }
}
private static string _connectionString = string.Empty;
/// <summary>
/// Detect a bound service for database, no database found will return an empty string. Currently only supports SQL Server
/// </summary>
public static string DbConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Looks to see if the connection string could be found in a bound service.
/// </summary>
public static bool hasDbConnection
{
get { return DbEngine != DatabaseEngine.None ? true : false; }
}
/// <summary>
/// Tells which DB engine was detected during app startup.
/// </summary>
public static DatabaseEngine DbEngine
{
get;
set;
}
/// <summary>
/// Checks the database to see if it has the proper tables. If not, add the table and an attendee.
/// </summary>
public static void CheckDBstructure()
{
Console.WriteLine("Checking DB structure.");
if (DbEngine == DatabaseEngine.SqlServer)
{
Console.WriteLine("Detected an mssql-dev service binding.");
// make sure tables exist
using (SqlConnection conn = new SqlConnection(CurrentEnvironment.DbConnectionString))
// if the table doesn't exist, create it
using (SqlCommand command = new SqlCommand()
{
CommandText = @"IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'attendee'))
BEGIN
CREATE TABLE attendee (
id bigint IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
address varchar(255) DEFAULT NULL,
city varchar(255) DEFAULT NULL,
email_address varchar(255) DEFAULT NULL,
first_name varchar(255) DEFAULT NULL,
last_name varchar(255) DEFAULT NULL,
phone_number varchar(255) DEFAULT NULL,
state varchar(255) DEFAULT NULL,
zip_code varchar(255) DEFAULT NULL)
END",
Connection = conn,
CommandType = CommandType.Text
})
{
conn.Open();
int rows = command.ExecuteNonQuery();
if (rows > -1)
Console.WriteLine("table didn't exist, creating it: " + rows + " rows affected.");
}
}
else if (DbEngine == DatabaseEngine.MySql)
{
using (MySqlConnection conn = new MySqlConnection(CurrentEnvironment.DbConnectionString))
// if the table doesn't exist, create it
using (MySqlCommand command = new MySqlCommand()
{
CommandText = @"CREATE TABLE IF NOT EXISTS `attendee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`address` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`email_address` varchar(255) DEFAULT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`phone_number` varchar(255) DEFAULT NULL,
`state` varchar(255) DEFAULT NULL,
`zip_code` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;",
Connection = conn,
CommandType = CommandType.Text
})
{
conn.Open();
int rows = command.ExecuteNonQuery();
if (rows > 0)
Console.WriteLine("table didn't exist, creating it: " + rows + " rows affected.");
};
}
else
{
Console.WriteLine("No DB found.");
}
}
public static void KillApp()
{
Console.WriteLine("Kaboom.");
Environment.Exit(-1);
}
public enum DatabaseEngine
{
None=0,
SqlServer=1,
MySql=2
}
}