2005-04-20 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[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
38 namespace System.Web.SessionState {
39
40         internal class SessionSQLServerHandler : ISessionHandler
41         {
42                 private static Type cncType = null;
43                 private IDbConnection cnc = null;
44                 private SessionConfig config;
45
46                 public void Dispose ()
47                 {
48                         if (cnc != null) {
49                                 cnc.Close ();
50                                 cnc = null;
51                         }
52                 }
53
54                 public void Init (SessionStateModule module, HttpApplication context, SessionConfig config)
55                 {
56                         string connectionTypeName;
57                         string providerAssemblyName;
58                         string cncString;
59
60                         this.config = config;
61
62                         GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
63                         if (cncType == null) {
64                                 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
65                                 cncType = dbAssembly.GetType (connectionTypeName, true);
66                                 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
67                                         throw new ApplicationException ("The type '" + cncType +
68                                                         "' does not implement IDB Connection.\n" +
69                                                         "Check 'DbConnectionType' in server.exe.config.");
70                         }
71
72                         cnc = (IDbConnection) Activator.CreateInstance (cncType);
73                         cnc.ConnectionString = cncString;
74                         try {
75                                 cnc.Open ();
76                         } catch (Exception exc) {
77                                 cnc = null;
78                                 throw exc;
79                         }
80                 }
81
82                 public void UpdateHandler (HttpContext context, SessionStateModule module)
83                 {
84                         if (context.Session == null || context.Session.IsReadOnly)
85                                 return;
86
87                         string id = context.Session.SessionID;
88                         SessionDictionary dict = context.Session.SessionDictionary;
89
90                         UpdateSession (id, dict);
91                 }
92
93                 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
94                                                         bool required, bool read_only, ref bool isNew)
95                 {
96                         if (!required)
97                                 return null;
98
99                         HttpSessionState session = null;
100                         string id = SessionId.Lookup (context.Request, config.CookieLess);
101
102                         if (id != null) {
103                                 session = SelectSession (id, read_only);
104                                 if (session != null)
105                                         return session;
106                         }
107
108                         id = SessionId.Create (module.Rng);
109                         session = new HttpSessionState (id, new SessionDictionary (),
110                                         HttpApplicationFactory.ApplicationState.SessionObjects, config.Timeout,
111                                         true, config.CookieLess, SessionStateMode.SQLServer, read_only);
112
113                         InsertSession (session, config.Timeout);
114                         isNew = true;
115                         return session;
116                 }
117
118                 private void GetConnectionData (out string providerAssembly,
119                                 out string cncTypeName, out string cncString)
120                 {
121                         providerAssembly = null;
122                         cncTypeName = null;
123                         cncString = null;
124
125                         NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
126                         if (config != null) {
127                                 foreach (string s in config.Keys) {
128                                         if (0 == String.Compare ("StateDBProviderAssembly", s, true)) {
129                                                 providerAssembly = config [s];
130                                         } else if (0 == String.Compare ("StateDBConnectionType", s, true)) {
131                                                 cncTypeName = config [s];
132                                         }
133                                 }
134                         }
135
136                         cncString = this.config.SqlConnectionString;
137
138                         if (providerAssembly == null || providerAssembly == String.Empty)
139                                 providerAssembly = "Npgsql.dll";
140
141                         if (cncTypeName == null || cncTypeName == String.Empty)
142                                 cncTypeName = "Npgsql.NpgsqlConnection";
143
144                         if (cncString == null || cncString == String.Empty)
145                                 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
146                 }
147
148                 private HttpSessionState SelectSession (string id, bool read_only)
149                 {
150                         HttpSessionState session = null;
151                         IDbCommand command = cnc.CreateCommand();
152                         IDataReader reader;
153
154                         string select = "SELECT * from aspstatetempsessions WHERE SessionID = :SessionID";
155
156                         command.CommandText = select;
157
158                         command.Parameters.Add (CreateParam (command, DbType.String, ":SessionID", id));
159
160                         try {
161                                 reader = command.ExecuteReader ();
162
163                                 if (!reader.Read ())
164                                         return null;
165
166                                 SessionDictionary dict; 
167                                 HttpStaticObjectsCollection sobjs;
168                                 
169                                 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
170                                 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
171                                 
172                                 session = new HttpSessionState (id, dict, sobjs, 100, false, config.CookieLess,
173                                                 SessionStateMode.SQLServer, read_only);
174                                 return session;
175                         } catch {
176                                 throw;
177                         }
178                 }
179
180                 private void InsertSession (HttpSessionState session, int timeout)
181                 {
182                         IDbCommand command = cnc.CreateCommand ();
183                         IDataParameterCollection param;
184
185                         string insert = "INSERT INTO ASPStateTempSessions VALUES " +
186                         "(:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
187
188                         command.CommandText = insert;
189
190                         param = command.Parameters;
191                         param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
192                         param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
193                         param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
194                         param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
195                         param.Add (CreateParam (command, DbType.Binary, ":StaticObjectsData",
196                                                    session.StaticObjects.ToByteArray ()));
197                         param.Add (CreateParam (command, DbType.Binary, ":SessionData",
198                                                    session.SessionDictionary.ToByteArray ()));
199
200                         command.ExecuteNonQuery ();
201                 }
202
203                 private void UpdateSession (string id, SessionDictionary dict)
204                 {
205                         IDbCommand command = cnc.CreateCommand ();
206                         IDataParameterCollection param;
207
208                         string update = "UPDATE ASPStateTempSessions SET " +
209                         "SessionData = :SessionData WHERE SessionId = :SessionID";
210
211                         command.CommandText = update;
212
213                         param = command.Parameters;
214                         param.Add (CreateParam (command, DbType.String, ":SessionID", id));
215                         param.Add (CreateParam (command, DbType.Binary, ":SessionData",
216                                                                 dict.ToByteArray ()));
217
218                         command.ExecuteNonQuery ();
219                 }
220
221                 private IDataParameter CreateParam (IDbCommand command, DbType type,
222                                 string name, object value)
223                 {
224                         IDataParameter result = command.CreateParameter ();
225                         result.DbType = type;
226                         result.ParameterName = name;
227                         result.Value = value;
228                         return result;
229                 }
230
231                 private DateTime Tommorow ()
232                 {
233                         return DateTime.Now.AddDays (1);
234                 }
235
236                 private byte [] ReadBytes (IDataReader reader, int index)
237                 {
238                         int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
239                         byte [] data = new byte [len];
240                         reader.GetBytes (index, 0, data, 0, len);
241                         return data;
242                 }
243         }
244 }
245