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