* HttpSessionState.cs: Make the SessionDictionary accessable
[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 using System;
11 using System.IO;
12 using System.Data;
13 using System.Reflection;
14 using System.Configuration;
15 using System.Collections.Specialized;
16
17 namespace System.Web.SessionState {
18
19         internal class SessionSQLServerHandler : ISessionHandler
20         {
21                 const string CookieName = "ASPSESSION";
22                 const int DefTimeout = 600;
23
24                 private Type cncType = null;
25                 private IDbConnection cnc = null;
26                 private SessionConfig config;
27
28                 public void Dispose ()
29                 {
30                         if (cnc != null) {
31                                 cnc.Close ();
32                                 cnc = null;
33                         }
34                 }
35
36                 public void Init (HttpApplication context, SessionConfig config)
37                 {
38                         string connectionTypeName;
39                         string providerAssemblyName;
40                         string cncString;
41
42                         this.config = config;
43
44                         GetConnectionData (out providerAssemblyName, out connectionTypeName, out cncString);
45                         if (cncType == null) {
46                                 Assembly dbAssembly = Assembly.Load (providerAssemblyName);
47                                 cncType = dbAssembly.GetType (connectionTypeName, true);
48                                 if (!typeof (IDbConnection).IsAssignableFrom (cncType))
49                                         throw new ApplicationException ("The type '" + cncType +
50                                                         "' does not implement IDB Connection.\n" +
51                                                         "Check 'DbConnectionType' in server.exe.config.");
52                         }
53
54                         cnc = (IDbConnection) Activator.CreateInstance (cncType);
55                         cnc.ConnectionString = cncString;
56                         try {
57                                 cnc.Open ();
58                         } catch (Exception exc) {
59                                 cnc = null;
60                                 throw exc;
61                         }
62                 }
63
64                 public void UpdateHandler (HttpContext context)
65                 {
66                         if (context.Session == null)
67                                 return;
68
69                         string id = context.Session.SessionID;
70                         SessionDictionary dict = context.Session.SessionDictionary;
71
72                         UpdateSession (id, dict);
73                 }
74
75                 public bool UpdateContext (HttpContext context)
76                 {
77                         HttpSessionState session = null;
78                         string id = GetId (context);
79
80                         if (id != null) {
81                                 session = SelectSession (id);
82                                 if (session != null) {
83                                         context.SetSession (session);
84                                         return false;
85                                 }
86                         }
87
88                         id = System.Guid.NewGuid ().ToString ();
89                         session = new HttpSessionState (id, new SessionDictionary (),
90                                         new HttpStaticObjectsCollection (), config.Timeout, true,
91                                         false, SessionStateMode.SQLServer, false);
92
93                         InsertSession (session, config.Timeout);
94                         context.SetSession (session);
95                         context.Session.IsNewSession = true;
96                         context.Response.AppendCookie (new HttpCookie (CookieName, id));
97
98                         return true;
99                 }
100
101                 private void GetConnectionData (out string providerAssembly,
102                                 out string cncTypeName, out string cncString)
103                 {
104                         providerAssembly = null;
105                         cncTypeName = null;
106                         cncString = null;
107
108                         NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
109                         if (config != null) {
110                                 foreach (string s in config.Keys) {
111                                         if (0 == String.Compare ("StateDBProviderAssembly", s, true)) {
112                                                 providerAssembly = config [s];
113                                         } else if (0 == String.Compare ("StateDBConnectionType", s, true)) {
114                                                 cncTypeName = config [s];
115                                         }
116                                 }
117                         }
118
119                         cncString = this.config.SqlConnectionString;
120
121                         if (providerAssembly == null || providerAssembly == String.Empty)
122                                 providerAssembly = "Npgsql.dll";
123
124                         if (cncTypeName == null || cncTypeName == String.Empty)
125                                 cncTypeName = "Npgsql.NpgsqlConnection";
126
127                         if (cncString == null || cncString == String.Empty)
128                                 cncString = "SERVER=127.0.0.1;USER ID=monostate;PASSWORD=monostate;dbname=monostate";
129                 }
130
131                 private HttpSessionState SelectSession (string id)
132                 {
133                         HttpSessionState session = null;
134                         IDbCommand command = cnc.CreateCommand();
135                         IDataReader reader;
136
137                         string select = "SELECT * from aspstatetempsessions WHERE SessionID = :SessionID";
138
139                         command.CommandText = select;
140
141                         command.Parameters.Add (CreateParam (command, DbType.String, ":SessionID", id));
142
143                         try {
144                                 reader = command.ExecuteReader ();
145
146                                 if (!reader.Read ())
147                                         return null;
148
149                                 SessionDictionary dict = null;
150                                 MemoryStream stream = null;
151                                 int len = (int) reader.GetBytes (reader.FieldCount-1, 0, null, 0, 0);
152                                 byte[] data = new byte[len];
153                                 reader.GetBytes (reader.FieldCount-1, 0, data, 0, len);
154                                 try {
155                                         stream = new MemoryStream (data);
156                                         dict = SessionDictionary.Deserialize (new BinaryReader (stream));
157                                 } catch {
158                                         throw;
159                                 } finally {
160                                         if (stream != null)
161                                                 stream.Close ();
162                                 }
163
164                                 session = new HttpSessionState (id, dict,
165                                                 new HttpStaticObjectsCollection (),
166                                                 100, true, false,
167                                                 SessionStateMode.SQLServer, false);
168                                 return session;
169                         } catch {
170                                 throw;
171                         }
172
173                 }
174
175                 private void InsertSession (HttpSessionState session, int timeout)
176                 {
177                         IDbCommand command = cnc.CreateCommand ();
178                         IDataParameterCollection param;
179
180                         string insert = "INSERT INTO ASPStateTempSessions VALUES " +
181                         "(:SessionID, :Created, :Expires, :Timeout, :SessionData)";
182
183                         command.CommandText = insert;
184
185                         param = command.Parameters;
186                         param.Add (CreateParam (command, DbType.String, ":SessionID", session.SessionID));
187                         param.Add (CreateParam (command, DbType.DateTime, ":Created", DateTime.Now));
188                         param.Add (CreateParam (command, DbType.DateTime, ":Expires", Tommorow ()));
189                         param.Add (CreateParam (command, DbType.Int32, ":Timeout", timeout));
190                         param.Add (CreateParam (command, DbType.Binary, ":SessionData",
191                                                    GetDictData (session.SessionDictionary)));
192
193                         command.ExecuteNonQuery ();
194                 }
195
196                 private void UpdateSession (string id, SessionDictionary dict)
197                 {
198                         IDbCommand command = cnc.CreateCommand ();
199                         IDataParameterCollection param;
200
201                         string update = "UPDATE ASPStateTempSessions SET " +
202                         "SessionData = :SessionData WHERE SessionId = :SessionID";
203
204                         command.CommandText = update;
205
206                         param = command.Parameters;
207                         param.Add (CreateParam (command, DbType.String, ":SessionID", id));
208                         param.Add (CreateParam (command, DbType.Binary, ":SessionData",
209                                                                 GetDictData (dict)));
210
211                         command.ExecuteNonQuery ();
212                 }
213
214                 private IDataParameter CreateParam (IDbCommand command, DbType type,
215                                 string name, object value)
216                 {
217                         IDataParameter result = command.CreateParameter ();
218                         result.DbType = type;
219                         result.ParameterName = name;
220                         result.Value = value;
221                         return result;
222                 }
223
224                 private byte[] GetDictData (SessionDictionary dict)
225                 {
226                         MemoryStream stream = null;
227                         try {
228                                 stream = new MemoryStream ();
229                                 dict.Serialize (new BinaryWriter (stream));
230                                 return stream.GetBuffer ();
231                         } catch {
232                                 throw;
233                         } finally {
234                                 if (stream != null)
235                                         stream.Close ();
236                         }
237                 }
238
239                 private DateTime Tommorow ()
240                 {
241                         return DateTime.Now.AddDays (1);
242                 }
243
244                 private string GetId (HttpContext context)
245                 {
246                         if (!config.CookieLess &&
247                                         context.Request.Cookies [CookieName] != null)
248                                 return context.Request.Cookies [CookieName].Value;
249
250                         return null;
251                 }
252         }
253 }
254