Implementation of the 2.0 session state model
[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 #if !NET_2_0
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                 private SessionConfig config;
46                 
47                 const string defaultParamPrefix = ":";
48                 string paramPrefix;
49                 string selectCommand = "SELECT timeout,staticobjectsdata,sessiondata FROM ASPStateTempSessions WHERE SessionID = :SessionID AND Expires > :Expires";
50                 string insertCommand = "INSERT INTO ASPStateTempSessions (SessionId, Created, expires, timeout, StaticObjectsData, SessionData)  VALUES (:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
51                 string updateCommand = "UPDATE ASPStateTempSessions SET expires = :Expires, timeout = :Timeout, SessionData = :SessionData WHERE SessionId = :SessionID";
52                 string deleteCommand = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
53
54                 public void Dispose ()
55                 {
56                         if (cnc != null) {
57                                 cnc.Close ();
58                                 cnc = null;
59                         }
60                 }
61
62                 public void Init (SessionStateModule module, HttpApplication context,
63                                   SessionConfig config)
64                 {
65                         string connectionTypeName;
66                         string providerAssemblyName;
67                         string cncString;
68
69                         this.config = config;
70
71                         GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
72                         if (cncType == null) {
73                                 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
74                                 cncType = dbAssembly.GetType (connectionTypeName, true);
75                                 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
76                                         throw new ApplicationException ("The type '" + cncType +
77                                                         "' does not implement IDB Connection.\n" +
78                                                         "Check 'DbConnectionType' in server.exe.config.");
79                         }
80
81                         cnc = (IDbConnection) Activator.CreateInstance (cncType);
82                         cnc.ConnectionString = cncString;
83                         try {
84                                 cnc.Open ();
85                         } catch (Exception exc) {
86                                 cnc = null;
87                                 throw exc;
88                         }
89
90                         if (paramPrefix != defaultParamPrefix) {
91                                 ReplaceParamPrefix (ref selectCommand);
92                                 ReplaceParamPrefix (ref insertCommand);
93                                 ReplaceParamPrefix (ref updateCommand);
94                                 ReplaceParamPrefix (ref deleteCommand);
95                         }
96                 }
97
98                 void ReplaceParamPrefix(ref string command)
99                 {
100                         command = command.Replace (defaultParamPrefix, paramPrefix);
101                 }
102
103                 public void UpdateHandler (HttpContext context, SessionStateModule module)
104                 {
105                         HttpSessionState session = context.Session;
106                         if (session == null || session.IsReadOnly)
107                                 return;
108
109                         string id = session.SessionID;
110                         if (!session._abandoned) {
111                                 SessionDictionary dict = session.SessionDictionary;
112                                 UpdateSessionWithRetry (id, session.Timeout, dict);
113                         } else {
114                                 DeleteSessionWithRetry (id);
115                         }
116                 }
117
118                 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
119                                                         bool required, bool read_only, ref bool isNew)
120                 {
121                         if (!required)
122                                 return null;
123
124                         HttpSessionState session = null;
125                         string id = SessionId.Lookup (context.Request, config.CookieLess);
126
127                         if (id != null) {
128                                 session = SelectSession (id, read_only);
129                                 if (session != null)
130                                         return session;
131                         }
132
133                         id = SessionId.Create ();
134                         session = new HttpSessionState (id, new SessionDictionary (),
135                                         HttpApplicationFactory.ApplicationState.SessionObjects,
136                                         config.Timeout,
137                                         true, config.CookieLess, SessionStateMode.SQLServer, read_only);
138
139                         InsertSessionWithRetry (session, config.Timeout);
140                         isNew = true;
141                         return session;
142                 }
143
144                 private void GetConnectionData (out string providerAssembly,
145                                 out string cncTypeName, out string cncString)
146                 {
147                         providerAssembly = null;
148                         cncTypeName = null;
149                         cncString = null;
150
151                         NameValueCollection config = ConfigurationSettings.AppSettings;
152                         if (config != null) {
153                                 providerAssembly = config ["StateDBProviderAssembly"];
154                                 cncTypeName = config ["StateDBConnectionType"];
155                                 paramPrefix = config ["StateDBParamPrefix"];
156                         }
157
158                         cncString = this.config.SqlConnectionString;
159
160                         if (providerAssembly == null || providerAssembly == String.Empty)
161                                 providerAssembly = "Npgsql.dll";
162
163                         if (cncTypeName == null || cncTypeName == String.Empty)
164                                 cncTypeName = "Npgsql.NpgsqlConnection";
165
166                         if (cncString == null || cncString == String.Empty)
167                                 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
168
169                         if (paramPrefix == null || paramPrefix == String.Empty)
170                                 paramPrefix = defaultParamPrefix;
171                 }
172
173                 IDataReader GetReader (string id)
174                 {
175                         IDbCommand command = null;
176                         command = cnc.CreateCommand();
177                         command.CommandText = selectCommand;
178                         command.Parameters.Add (CreateParam (command, DbType.String, "SessionID", id));
179                         command.Parameters.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now ));
180                         command.Prepare ();
181                         return command.ExecuteReader ();
182                 }
183
184                 IDataReader GetReaderWithRetry (string id)
185                 {
186                         try {
187                                 return GetReader (id);
188                         } catch {
189                         }
190
191                         try {
192                                 cnc.Close ();
193                         } catch {
194                         }
195
196                         cnc.Open ();
197                         return GetReader (id);
198                 }
199
200                 private HttpSessionState SelectSession (string id, bool read_only)
201                 {
202                         HttpSessionState session = null;
203                         using (IDataReader reader = GetReaderWithRetry (id)) {
204                                 if (!reader.Read ())
205                                         return null;
206
207                                 SessionDictionary dict; 
208                                 HttpStaticObjectsCollection sobjs;
209                                 int timeout;
210                                 
211                                 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
212                                 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
213                                 // try to support as many DBs/int types as possible
214                                 timeout = Convert.ToInt32 (reader.GetValue (reader.FieldCount-3));
215                                 
216                                 session = new HttpSessionState (id, dict, sobjs, timeout, false, config.CookieLess,
217                                                 SessionStateMode.SQLServer, read_only);
218                                 return session;
219                         }
220                 }
221
222                 void InsertSession (HttpSessionState session, int timeout)
223                 {
224                         IDbCommand command = cnc.CreateCommand ();
225                         IDataParameterCollection param;
226
227                         command.CommandText = insertCommand;
228
229                         param = command.Parameters;
230                         param.Add (CreateParam (command, DbType.String, "SessionID", session.SessionID));
231                         param.Add (CreateParam (command, DbType.DateTime, "Created", DateTime.Now));
232                         param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
233                         param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
234                         param.Add (CreateParam (command, DbType.Binary, "StaticObjectsData",
235                                                    session.StaticObjects.ToByteArray ()));
236                         param.Add (CreateParam (command, DbType.Binary, "SessionData",
237                                                    session.SessionDictionary.ToByteArray ()));
238
239                         command.Prepare ();
240                         command.ExecuteNonQuery ();
241                 }
242
243                 void InsertSessionWithRetry (HttpSessionState session, int timeout)
244                 {
245                         try {
246                                 InsertSession (session, timeout);
247                                 return;
248                         } catch {
249                         }
250
251                         try {
252                                 cnc.Close ();
253                         } catch {
254                         }
255
256                         cnc.Open ();
257                         InsertSession (session, timeout);
258                 }
259
260                 void UpdateSession (string id, int timeout, SessionDictionary dict)
261                 {
262                         IDbCommand command = cnc.CreateCommand ();
263                         IDataParameterCollection param;
264
265                         command.CommandText = updateCommand;
266
267                         param = command.Parameters;
268                         param.Add (CreateParam (command, DbType.String, "SessionID", id));
269                         param.Add (CreateParam (command, DbType.DateTime, "Expires", DateTime.Now.AddMinutes (timeout)));
270                         param.Add (CreateParam (command, DbType.Int32, "Timeout", timeout));
271                         param.Add (CreateParam (command, DbType.Binary, "SessionData",
272                                                                 dict.ToByteArray ()));
273
274                         command.Prepare ();
275                         command.ExecuteNonQuery ();
276                 }
277
278                 void UpdateSessionWithRetry (string id, int timeout, SessionDictionary dict)
279                 {
280                         try {
281                                 UpdateSession (id, timeout, dict);
282                                 return;
283                         } catch {
284                         }
285
286                         try {
287                                 cnc.Close ();
288                         } catch {
289                         }
290
291                         cnc.Open ();
292                         UpdateSession (id, timeout, dict);
293                 }
294
295                 void DeleteSession (string id)
296                 {
297                         IDbCommand command = cnc.CreateCommand ();
298                         IDataParameterCollection param;
299
300                         command.CommandText = deleteCommand;
301                         param = command.Parameters;
302                         param.Add (CreateParam (command, DbType.String, "SessionID", id));
303                         command.Prepare ();
304                         command.ExecuteNonQuery ();
305                 }
306
307                 void DeleteSessionWithRetry (string id)
308                 {
309                         try {
310                                 DeleteSession (id);
311                                 return;
312                         } catch {
313                         }
314
315                         try {
316                                 cnc.Close ();
317                         } catch {
318                         }
319
320                         cnc.Open ();
321                         DeleteSession (id);
322                 }
323
324                 private IDataParameter CreateParam (IDbCommand command, DbType type,
325                                 string name, object value)
326                 {
327                         IDataParameter result = command.CreateParameter ();
328                         result.DbType = type;
329                         result.ParameterName = paramPrefix + name;
330                         result.Value = value;
331                         return result;
332                 }
333
334                 private byte [] ReadBytes (IDataReader reader, int index)
335                 {
336                         int len = (int) reader.GetBytes (index, 0, null, 0, 0);
337                         byte [] data = new byte [len];
338                         reader.GetBytes (index, 0, data, 0, len);
339                         return data;
340                 }
341         }
342 }
343 #endif