New test.
[mono.git] / mcs / class / System.Web / System.Web.SessionState / SessionSQLServerHandler.cs
1 //
2 // System.Web.SessionState.SessionSQLServerHandler
3 //
4 // Author(s):
5 //  Jackson Harper (jackson@ximian.com)
6 //
7 // (C) 2003 Novell, Inc. (http://www.novell.com), All rights reserved
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.IO;
33 using System.Data;
34 using System.Reflection;
35 using System.Configuration;
36 using System.Collections.Specialized;
37 using System.Web.Configuration;
38
39 namespace System.Web.SessionState {
40
41         internal class SessionSQLServerHandler : ISessionHandler
42         {
43                 private static Type cncType = null;
44                 private IDbConnection cnc = null;
45 #if NET_2_0
46                 private SessionStateSection config;
47 #else
48                 private SessionConfig config;
49 #endif
50                 
51                 const string defaultParamPrefix = ":";
52                 string paramPrefix;
53                 string selectCommand = "SELECT timeout,staticobjectsdata,sessiondata FROM ASPStateTempSessions WHERE SessionID = :SessionID AND Expires > :Expires";
54                 string insertCommand = "INSERT INTO ASPStateTempSessions (SessionId, Created, expires, timeout, StaticObjectsData, SessionData)  VALUES (:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
55                 string updateCommand = "UPDATE ASPStateTempSessions SET expires = :Expires, timeout = :Timeout, SessionData = :SessionData WHERE SessionId = :SessionID";
56                 string deleteCommand = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
57
58                 public void Dispose ()
59                 {
60                         if (cnc != null) {
61                                 cnc.Close ();
62                                 cnc = null;
63                         }
64                 }
65
66                 public void Init (SessionStateModule module, HttpApplication context,
67 #if NET_2_0
68                                   SessionStateSection config
69 #else
70                                   SessionConfig config
71 #endif
72                                   )
73                 {
74                         string connectionTypeName;
75                         string providerAssemblyName;
76                         string cncString;
77
78                         this.config = config;
79
80                         GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
81                         if (cncType == null) {
82                                 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
83                                 cncType = dbAssembly.GetType (connectionTypeName, true);
84                                 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
85                                         throw new ApplicationException ("The type '" + cncType +
86                                                         "' does not implement IDB Connection.\n" +
87                                                         "Check 'DbConnectionType' in server.exe.config.");
88                         }
89
90                         cnc = (IDbConnection) Activator.CreateInstance (cncType);
91                         cnc.ConnectionString = cncString;
92                         try {
93                                 cnc.Open ();
94                         } catch (Exception exc) {
95                                 cnc = null;
96                                 throw exc;
97                         }
98
99                         if (paramPrefix != defaultParamPrefix) {
100                                 ReplaceParamPrefix (ref selectCommand);
101                                 ReplaceParamPrefix (ref insertCommand);
102                                 ReplaceParamPrefix (ref updateCommand);
103                                 ReplaceParamPrefix (ref deleteCommand);
104                         }
105                 }
106
107                 void ReplaceParamPrefix(ref string command)
108                 {
109                         command = command.Replace (defaultParamPrefix, paramPrefix);
110                 }
111
112                 public void UpdateHandler (HttpContext context, SessionStateModule module)
113                 {
114                         HttpSessionState session = context.Session;
115                         if (session == null || session.IsReadOnly)
116                                 return;
117
118                         string id = session.SessionID;
119                         if (!session._abandoned) {
120                                 SessionDictionary dict = session.SessionDictionary;
121                                 UpdateSessionWithRetry (id, session.Timeout, dict);
122                         } else {
123                                 DeleteSessionWithRetry (id);
124                         }
125                 }
126
127                 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
128                                                         bool required, bool read_only, ref bool isNew)
129                 {
130                         if (!required)
131                                 return null;
132
133                         HttpSessionState session = null;
134                         string id = SessionId.Lookup (context.Request, config.CookieLess);
135
136                         if (id != null) {
137                                 session = SelectSession (id, read_only);
138                                 if (session != null)
139                                         return session;
140                         }
141
142                         id = SessionId.Create (module.Rng);
143                         session = new HttpSessionState (id, new SessionDictionary (),
144                                         HttpApplicationFactory.ApplicationState.SessionObjects,
145 #if NET_2_0
146                                         (int)config.Timeout.TotalMinutes,
147 #else
148                                         config.Timeout,
149 #endif
150                                         true, config.CookieLess, SessionStateMode.SQLServer, read_only);
151
152                         InsertSessionWithRetry (session,
153 #if NET_2_0
154                                        (int)config.Timeout.TotalMinutes
155 #else
156                                        config.Timeout
157 #endif
158                                        );
159                         isNew = true;
160                         return session;
161                 }
162
163                 private void GetConnectionData (out string providerAssembly,
164                                 out string cncTypeName, out string cncString)
165                 {
166                         providerAssembly = null;
167                         cncTypeName = null;
168                         cncString = null;
169
170                         NameValueCollection config = ConfigurationSettings.AppSettings;
171                         if (config != null) {
172                                 providerAssembly = config ["StateDBProviderAssembly"];
173                                 cncTypeName = config ["StateDBConnectionType"];
174                                 paramPrefix = config ["StateDBParamPrefix"];
175                         }
176
177                         cncString = this.config.SqlConnectionString;
178
179                         if (providerAssembly == null || providerAssembly == String.Empty)
180                                 providerAssembly = "Npgsql.dll";
181
182                         if (cncTypeName == null || cncTypeName == String.Empty)
183                                 cncTypeName = "Npgsql.NpgsqlConnection";
184
185                         if (cncString == null || cncString == String.Empty)
186                                 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
187
188                         if (paramPrefix == null || paramPrefix == String.Empty)
189                                 paramPrefix = defaultParamPrefix;
190                 }
191
192                 IDataReader GetReader (string id)
193                 {
194                         IDbCommand command = null;
195                         command = cnc.CreateCommand();
196                         command.CommandText = selectCommand;
197                         command.Parameters.Add (CreateParam (command, DbType.String, "SessionID", id));
198                         command.Parameters.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now ));
199                         return command.ExecuteReader ();
200                 }
201
202                 IDataReader GetReaderWithRetry (string id)
203                 {
204                         try {
205                                 return GetReader (id);
206                         } catch {
207                         }
208
209                         try {
210                                 cnc.Close ();
211                         } catch {
212                         }
213
214                         cnc.Open ();
215                         return GetReader (id);
216                 }
217
218                 private HttpSessionState SelectSession (string id, bool read_only)
219                 {
220                         HttpSessionState session = null;
221                         using (IDataReader reader = GetReaderWithRetry (id)) {
222                                 if (!reader.Read ())
223                                         return null;
224
225                                 SessionDictionary dict; 
226                                 HttpStaticObjectsCollection sobjs;
227                                 int timeout;
228                                 
229                                 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
230                                 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
231                                 // try to support as many DBs/int types as possible
232                                 timeout = Convert.ToInt32 (reader.GetValue (reader.FieldCount-3));
233                                 
234                                 session = new HttpSessionState (id, dict, sobjs, timeout, false, config.CookieLess,
235                                                 SessionStateMode.SQLServer, read_only);
236                                 return session;
237                         }
238                 }
239
240                 void InsertSession (HttpSessionState session, int timeout)
241                 {
242                         IDbCommand command = cnc.CreateCommand ();
243                         IDataParameterCollection param;
244
245                         command.CommandText = insertCommand;
246
247                         param = command.Parameters;
248                         param.Add (CreateParam (command, DbType.String, "SessionID", session.SessionID));
249                         param.Add (CreateParam (command, DbType.DateTime, "Created", DateTime.Now));
250                         param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
251                         param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
252                         param.Add (CreateParam (command, DbType.Binary, "StaticObjectsData",
253                                                    session.StaticObjects.ToByteArray ()));
254                         param.Add (CreateParam (command, DbType.Binary, "SessionData",
255                                                    session.SessionDictionary.ToByteArray ()));
256
257                         command.ExecuteNonQuery ();
258                 }
259
260                 void InsertSessionWithRetry (HttpSessionState session, int timeout)
261                 {
262                         try {
263                                 InsertSession (session, timeout);
264                                 return;
265                         } catch {
266                         }
267
268                         try {
269                                 cnc.Close ();
270                         } catch {
271                         }
272
273                         cnc.Open ();
274                         InsertSession (session, timeout);
275                 }
276
277                 void UpdateSession (string id, int timeout, SessionDictionary dict)
278                 {
279                         IDbCommand command = cnc.CreateCommand ();
280                         IDataParameterCollection param;
281
282                         command.CommandText = updateCommand;
283
284                         param = command.Parameters;
285                         param.Add (CreateParam (command, DbType.String, "SessionID", id));
286                         param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
287                         param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
288                         param.Add (CreateParam (command, DbType.Binary, "SessionData",
289                                                                 dict.ToByteArray ()));
290
291                         command.ExecuteNonQuery ();
292                 }
293
294                 void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
295                 {
296                         try {
297                                 UpdateSession (id, timeout, dict);
298                                 return;
299                         } catch {
300                         }
301
302                         try {
303                                 cnc.Close ();
304                         } catch {
305                         }
306
307                         cnc.Open ();
308                         UpdateSession (id, timeout, dict);
309                 }
310
311                 void DeleteSession (string id)
312                 {
313                         IDbCommand command = cnc.CreateCommand ();
314                         IDataParameterCollection param;
315
316                         command.CommandText = deleteCommand;
317                         param = command.Parameters;
318                         param.Add (CreateParam (command, DbType.String, "SessionID", id));
319                         command.ExecuteNonQuery ();
320                 }
321
322                 void DeleteSessionWithRetry (string id)
323                 {
324                         try {
325                                 DeleteSession (id);
326                                 return;
327                         } catch {
328                         }
329
330                         try {
331                                 cnc.Close ();
332                         } catch {
333                         }
334
335                         cnc.Open ();
336                         DeleteSession (id);
337                 }
338
339                 private IDataParameter CreateParam (IDbCommand command, DbType type,
340                                 string name, object value)
341                 {
342                         IDataParameter result = command.CreateParameter ();
343                         result.DbType = type;
344                         result.ParameterName = paramPrefix + name;
345                         result.Value = value;
346                         return result;
347                 }
348
349                 private byte [] ReadBytes (IDataReader reader, int index)
350                 {
351                         int len = (int) reader.GetBytes (index, 0, null, 0, 0);
352                         byte [] data = new byte [len];
353                         reader.GetBytes (index, 0, data, 0, len);
354                         return data;
355                 }
356         }
357 }
358