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