merge -r 58784:58785
[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                         HttpSessionState session = context.Session;
85                         if (session == null || session.IsReadOnly)
86                                 return;
87
88                         string id = session.SessionID;
89                         if (!session._abandoned) {
90                                 SessionDictionary dict = session.SessionDictionary;
91                                 UpdateSession (id, dict);
92                         } else {
93                                 DeleteSession (id);
94                         }
95                 }
96
97                 public HttpSessionState UpdateContext (HttpContext context, SessionStateModule module,
98                                                         bool required, bool read_only, ref bool isNew)
99                 {
100                         if (!required)
101                                 return null;
102
103                         HttpSessionState session = null;
104                         string id = SessionId.Lookup (context.Request, config.CookieLess);
105
106                         if (id != null) {
107                                 session = SelectSession (id, read_only);
108                                 if (session != null)
109                                         return session;
110                         }
111
112                         id = SessionId.Create (module.Rng);
113                         session = new HttpSessionState (id, new SessionDictionary (),
114                                         HttpApplicationFactory.ApplicationState.SessionObjects, config.Timeout,
115                                         true, config.CookieLess, SessionStateMode.SQLServer, read_only);
116
117                         InsertSession (session, config.Timeout);
118                         isNew = true;
119                         return session;
120                 }
121
122                 private void GetConnectionData (out string providerAssembly,
123                                 out string cncTypeName, out string cncString)
124                 {
125                         providerAssembly = null;
126                         cncTypeName = null;
127                         cncString = null;
128
129                         NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
130                         if (config != null) {
131                                 foreach (string s in config.Keys) {
132                                         if (0 == String.Compare ("StateDBProviderAssembly", s, true)) {
133                                                 providerAssembly = config [s];
134                                         } else if (0 == String.Compare ("StateDBConnectionType", s, true)) {
135                                                 cncTypeName = config [s];
136                                         }
137                                 }
138                         }
139
140                         cncString = this.config.SqlConnectionString;
141
142                         if (providerAssembly == null || providerAssembly == String.Empty)
143                                 providerAssembly = "Npgsql.dll";
144
145                         if (cncTypeName == null || cncTypeName == String.Empty)
146                                 cncTypeName = "Npgsql.NpgsqlConnection";
147
148                         if (cncString == null || cncString == String.Empty)
149                                 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
150                 }
151
152                 private HttpSessionState SelectSession (string id, bool read_only)
153                 {
154                         HttpSessionState session = null;
155                         IDbCommand command = cnc.CreateCommand();
156                         IDataReader reader;
157
158                         string select = "SELECT * from aspstatetempsessions WHERE SessionID = :SessionID";
159
160                         command.CommandText = select;
161
162                         command.Parameters.Add (CreateParam (command, DbType.String, ":SessionID", id));
163
164                         try {
165                                 reader = command.ExecuteReader ();
166
167                                 if (!reader.Read ())
168                                         return null;
169
170                                 SessionDictionary dict; 
171                                 HttpStaticObjectsCollection sobjs;
172                                 
173                                 dict = SessionDictionary.FromByteArray (ReadBytes (reader, reader.FieldCount-1));
174                                 sobjs = HttpStaticObjectsCollection.FromByteArray (ReadBytes (reader, reader.FieldCount-2));
175                                 
176                                 session = new HttpSessionState (id, dict, sobjs, 100, false, config.CookieLess,
177                                                 SessionStateMode.SQLServer, read_only);
178                                 return session;
179                         } catch {
180                                 throw;
181                         }
182                 }
183
184                 private void InsertSession (HttpSessionState session, int timeout)
185                 {
186                         IDbCommand command = cnc.CreateCommand ();
187                         IDataParameterCollection param;
188
189                         string insert = "INSERT INTO ASPStateTempSessions VALUES " +
190                         "(:SessionID, :Created, :Expires, :Timeout, :StaticObjectsData, :SessionData)";
191
192                         command.CommandText = insert;
193
194                         param = command.Parameters;
195                         param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
196                         param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
197                         param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
198                         param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
199                         param.Add (CreateParam (command, DbType.Binary, ":StaticObjectsData",
200                                                    session.StaticObjects.ToByteArray ()));
201                         param.Add (CreateParam (command, DbType.Binary, ":SessionData",
202                                                    session.SessionDictionary.ToByteArray ()));
203
204                         command.ExecuteNonQuery ();
205                 }
206
207                 private void UpdateSession (string id, SessionDictionary dict)
208                 {
209                         IDbCommand command = cnc.CreateCommand ();
210                         IDataParameterCollection param;
211
212                         string update = "UPDATE ASPStateTempSessions SET " +
213                         "SessionData = :SessionData WHERE SessionId = :SessionID";
214
215                         command.CommandText = update;
216
217                         param = command.Parameters;
218                         param.Add (CreateParam (command, DbType.String, ":SessionID", id));
219                         param.Add (CreateParam (command, DbType.Binary, ":SessionData",
220                                                                 dict.ToByteArray ()));
221
222                         command.ExecuteNonQuery ();
223                 }
224
225                 private void DeleteSession (string id)
226                 {
227                         IDbCommand command = cnc.CreateCommand ();
228                         IDataParameterCollection param;
229
230                         string update = "DELETE FROM ASPStateTempSessions WHERE SessionId = :SessionID";
231                         command.CommandText = update;
232                         param = command.Parameters;
233                         param.Add (CreateParam (command, DbType.String, ":SessionID", id));
234                         command.ExecuteNonQuery ();
235                 }
236
237                 private IDataParameter CreateParam (IDbCommand command, DbType type,
238                                 string name, object value)
239                 {
240                         IDataParameter result = command.CreateParameter ();
241                         result.DbType = type;
242                         result.ParameterName = name;
243                         result.Value = value;
244                         return result;
245                 }
246
247                 private DateTime Tommorow ()
248                 {
249                         return DateTime.Now.AddDays (1);
250                 }
251
252                 private byte [] ReadBytes (IDataReader reader, int index)
253                 {
254                         int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
255                         byte [] data = new byte [len];
256                         reader.GetBytes (index, 0, data, 0, len);
257                         return data;
258                 }
259         }
260 }
261