aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim')
-rw-r--r--OpenSim/ApplicationPlugins/Rest/Inventory/Rest.cs4
-rw-r--r--OpenSim/ApplicationPlugins/Rest/RestXmlWriter.cs3
-rw-r--r--OpenSim/Client/Linden/LLProxyLoginModule.cs184
-rw-r--r--OpenSim/Client/MXP/ClientStack/MXPClientView.cs2
-rw-r--r--OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs13
-rw-r--r--OpenSim/Data/MSSQL/AutoClosingSqlCommand.cs15
-rw-r--r--OpenSim/Data/MSSQL/MSSQLInventoryData.cs2
-rw-r--r--OpenSim/Data/MSSQL/MSSQLManager.cs4
-rw-r--r--OpenSim/Data/MSSQL/MSSQLMigration.cs1
-rw-r--r--OpenSim/Data/Migration.cs79
-rw-r--r--OpenSim/Data/MySQL/MySQLAssetData.cs102
-rw-r--r--OpenSim/Data/MySQL/MySQLAuthenticationData.cs50
-rw-r--r--OpenSim/Data/MySQL/MySQLEstateData.cs310
-rw-r--r--OpenSim/Data/MySQL/MySQLFramework.cs14
-rw-r--r--OpenSim/Data/MySQL/MySQLGridData.cs171
-rw-r--r--OpenSim/Data/MySQL/MySQLInventoryData.cs335
-rw-r--r--OpenSim/Data/MySQL/MySQLLegacyRegionData.cs531
-rw-r--r--OpenSim/Data/MySQL/MySQLManager.cs60
-rw-r--r--OpenSim/Data/MySQL/MySQLRegionData.cs240
-rw-r--r--OpenSim/Data/MySQL/MySQLUserAccountData.cs141
-rw-r--r--OpenSim/Data/MySQL/MySQLUserData.cs370
-rw-r--r--OpenSim/Data/SQLite/SQLiteRegionData.cs14
-rw-r--r--OpenSim/Framework/AssetLandmark.cs2
-rw-r--r--OpenSim/Framework/Capabilities/LLSD.cs4
-rw-r--r--OpenSim/Framework/Capabilities/LLSDStreamHandler.cs2
-rw-r--r--OpenSim/Framework/Communications/Clients/RegionClient.cs31
-rw-r--r--OpenSim/Framework/Communications/XMPP/XmppWriter.cs2
-rw-r--r--OpenSim/Framework/Configuration/HTTP/HTTPConfiguration.cs2
-rw-r--r--OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs30
-rw-r--r--OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs2
-rw-r--r--OpenSim/Framework/Servers/HttpServer/RestSessionService.cs20
-rw-r--r--OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs34
-rw-r--r--OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs23
-rw-r--r--OpenSim/Framework/Util.cs10
-rw-r--r--OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs71
-rw-r--r--OpenSim/Grid/UserServer.Modules/UserLoginService.cs1
-rw-r--r--OpenSim/Region/Application/Application.cs11
-rw-r--r--OpenSim/Region/Application/OpenSimBase.cs6
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs299
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs4
-rw-r--r--OpenSim/Region/ClientStack/LindenUDP/LLImageManager.cs242
-rw-r--r--OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs4
-rw-r--r--OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs25
-rw-r--r--OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs4
-rw-r--r--OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs18
-rw-r--r--OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs10
-rw-r--r--OpenSim/Region/DataSnapshot/DataSnapshotManager.cs2
-rw-r--r--OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs2
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs7
-rw-r--r--OpenSim/Region/Framework/Scenes/TerrainChannel.cs2
-rw-r--r--OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs4
-rw-r--r--OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs4
-rw-r--r--OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs2
-rw-r--r--OpenSim/Region/Physics/Meshing/Meshmerizer.cs31
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs2
-rw-r--r--OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs2
-rw-r--r--OpenSim/Server/Base/ServerUtils.cs2
-rw-r--r--OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs2
-rw-r--r--OpenSim/Server/Handlers/Simulation/AgentHandlers.cs2
-rw-r--r--OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs7
60 files changed, 1769 insertions, 1804 deletions
diff --git a/OpenSim/ApplicationPlugins/Rest/Inventory/Rest.cs b/OpenSim/ApplicationPlugins/Rest/Inventory/Rest.cs
index 1e3539f..7db705e 100644
--- a/OpenSim/ApplicationPlugins/Rest/Inventory/Rest.cs
+++ b/OpenSim/ApplicationPlugins/Rest/Inventory/Rest.cs
@@ -163,7 +163,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
163 get { return Plugin.RequestId; } 163 get { return Plugin.RequestId; }
164 } 164 }
165 165
166 internal static Encoding Encoding = Encoding.UTF8; 166 internal static Encoding Encoding = Util.UTF8;
167 167
168 /// <summary> 168 /// <summary>
169 /// Version control for REST implementation. This 169 /// Version control for REST implementation. This
@@ -435,7 +435,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
435 try 435 try
436 { 436 {
437 byte[] encData_byte = new byte[str.Length]; 437 byte[] encData_byte = new byte[str.Length];
438 encData_byte = Encoding.UTF8.GetBytes(str); 438 encData_byte = Util.UTF8.GetBytes(str);
439 return Convert.ToBase64String(encData_byte); 439 return Convert.ToBase64String(encData_byte);
440 } 440 }
441 catch 441 catch
diff --git a/OpenSim/ApplicationPlugins/Rest/RestXmlWriter.cs b/OpenSim/ApplicationPlugins/Rest/RestXmlWriter.cs
index 9abb0c8..283fa2e 100644
--- a/OpenSim/ApplicationPlugins/Rest/RestXmlWriter.cs
+++ b/OpenSim/ApplicationPlugins/Rest/RestXmlWriter.cs
@@ -45,7 +45,8 @@ namespace OpenSim.ApplicationPlugins.Rest
45 { 45 {
46 } 46 }
47 47
48 public RestXmlWriter(Stream stream) : this(stream, Encoding.UTF8) 48 public RestXmlWriter(Stream stream)
49 : this(stream, Encoding.UTF8)
49 { 50 {
50 } 51 }
51 52
diff --git a/OpenSim/Client/Linden/LLProxyLoginModule.cs b/OpenSim/Client/Linden/LLProxyLoginModule.cs
index ccd38d4..f9cb3a9 100644
--- a/OpenSim/Client/Linden/LLProxyLoginModule.cs
+++ b/OpenSim/Client/Linden/LLProxyLoginModule.cs
@@ -148,8 +148,8 @@ namespace OpenSim.Client.Linden
148 protected void AddHttpHandlers() 148 protected void AddHttpHandlers()
149 { 149 {
150 //we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change? 150 //we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change?
151 MainServer.Instance.AddXmlRPCHandler("expect_user", ExpectUser); 151 MainServer.Instance.AddXmlRPCHandler("expect_user", ExpectUser, false);
152 MainServer.Instance.AddXmlRPCHandler("logoff_user", LogOffUser); 152 MainServer.Instance.AddXmlRPCHandler("logoff_user", LogOffUser, false);
153 } 153 }
154 154
155 protected void AddScene(Scene scene) 155 protected void AddScene(Scene scene)
@@ -182,104 +182,126 @@ namespace OpenSim.Client.Linden
182 /// <returns></returns> 182 /// <returns></returns>
183 public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient) 183 public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient)
184 { 184 {
185 Hashtable requestData = (Hashtable)request.Params[0];
186 AgentCircuitData agentData = new AgentCircuitData();
187 agentData.SessionID = new UUID((string)requestData["session_id"]);
188 agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
189 agentData.firstname = (string)requestData["firstname"];
190 agentData.lastname = (string)requestData["lastname"];
191 agentData.AgentID = new UUID((string)requestData["agent_id"]);
192 agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
193 agentData.CapsPath = (string)requestData["caps_path"];
194 ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
195
196 // Appearance
197 if (requestData["appearance"] != null)
198 agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
199
200 m_log.DebugFormat(
201 "[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
202 agentData.firstname, agentData.lastname, agentData.AgentID, agentData.circuitcode);
203
204 if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
205 {
206 //m_log.Debug("[CLIENT]: Child agent detected");
207 agentData.child = true;
208 }
209 else
210 {
211 //m_log.Debug("[CLIENT]: Main agent detected");
212 agentData.startpos =
213 new Vector3((float)Convert.ToDecimal((string)requestData["startpos_x"]),
214 (float)Convert.ToDecimal((string)requestData["startpos_y"]),
215 (float)Convert.ToDecimal((string)requestData["startpos_z"]));
216 agentData.child = false;
217 }
218
219 XmlRpcResponse resp = new XmlRpcResponse(); 185 XmlRpcResponse resp = new XmlRpcResponse();
220 186
221 if (!RegionLoginsEnabled) 187 try
222 { 188 {
223 m_log.InfoFormat( 189 ulong regionHandle = 0;
224 "[CLIENT]: Denying access for user {0} {1} because region login is currently disabled", 190 Hashtable requestData = (Hashtable)request.Params[0];
225 agentData.firstname, agentData.lastname); 191 AgentCircuitData agentData = new AgentCircuitData();
192 if (requestData.ContainsKey("session_id"))
193 agentData.SessionID = new UUID((string)requestData["session_id"]);
194 if (requestData.ContainsKey("secure_session_id"))
195 agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
196 if (requestData.ContainsKey("firstname"))
197 agentData.firstname = (string)requestData["firstname"];
198 if (requestData.ContainsKey("lastname"))
199 agentData.lastname = (string)requestData["lastname"];
200 if (requestData.ContainsKey("agent_id"))
201 agentData.AgentID = new UUID((string)requestData["agent_id"]);
202 if (requestData.ContainsKey("circuit_code"))
203 agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
204 if (requestData.ContainsKey("caps_path"))
205 agentData.CapsPath = (string)requestData["caps_path"];
206 if (requestData.ContainsKey("regionhandle"))
207 regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
208 else
209 m_log.Warn("[CLIENT]: request from login server did not contain regionhandle");
226 210
227 Hashtable respdata = new Hashtable(); 211 // Appearance
228 respdata["success"] = "FALSE"; 212 if (requestData.ContainsKey("appearance"))
229 respdata["reason"] = "region login currently disabled"; 213 agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
230 resp.Value = respdata;
231 }
232 else
233 {
234 bool success = false;
235 string denyMess = "";
236 214
237 Scene scene; 215 m_log.DebugFormat(
238 if (TryGetRegion(regionHandle, out scene)) 216 "[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
239 { 217 agentData.firstname, agentData.lastname, agentData.AgentID, agentData.circuitcode);
240 if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
241 {
242 denyMess = "User is banned from this region";
243 m_log.InfoFormat(
244 "[CLIENT]: Denying access for user {0} {1} because user is banned",
245 agentData.firstname, agentData.lastname);
246 }
247 else
248 {
249 string reason;
250 if (scene.NewUserConnection(agentData, out reason))
251 {
252 success = true;
253 }
254 else
255 {
256 denyMess = String.Format("Login refused by region: {0}", reason);
257 m_log.InfoFormat(
258 "[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region",
259 agentData.firstname, agentData.lastname);
260 }
261 }
262 218
219 if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
220 {
221 //m_log.Debug("[CLIENT]: Child agent detected");
222 agentData.child = true;
263 } 223 }
264 else 224 else
265 { 225 {
266 denyMess = "Region not found"; 226 //m_log.Debug("[CLIENT]: Main agent detected");
227 agentData.startpos =
228 new Vector3((float)Convert.ToDecimal((string)requestData["startpos_x"]),
229 (float)Convert.ToDecimal((string)requestData["startpos_y"]),
230 (float)Convert.ToDecimal((string)requestData["startpos_z"]));
231 agentData.child = false;
267 } 232 }
268 233
269 if (success) 234 if (!RegionLoginsEnabled)
270 { 235 {
236 m_log.InfoFormat(
237 "[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
238 agentData.firstname, agentData.lastname);
239
271 Hashtable respdata = new Hashtable(); 240 Hashtable respdata = new Hashtable();
272 respdata["success"] = "TRUE"; 241 respdata["success"] = "FALSE";
242 respdata["reason"] = "region login currently disabled";
273 resp.Value = respdata; 243 resp.Value = respdata;
274 } 244 }
275 else 245 else
276 { 246 {
277 Hashtable respdata = new Hashtable(); 247 bool success = false;
278 respdata["success"] = "FALSE"; 248 string denyMess = "";
279 respdata["reason"] = denyMess; 249
280 resp.Value = respdata; 250 Scene scene;
251 if (TryGetRegion(regionHandle, out scene))
252 {
253 if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
254 {
255 denyMess = "User is banned from this region";
256 m_log.InfoFormat(
257 "[CLIENT]: Denying access for user {0} {1} because user is banned",
258 agentData.firstname, agentData.lastname);
259 }
260 else
261 {
262 string reason;
263 if (scene.NewUserConnection(agentData, out reason))
264 {
265 success = true;
266 }
267 else
268 {
269 denyMess = String.Format("Login refused by region: {0}", reason);
270 m_log.InfoFormat(
271 "[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region",
272 agentData.firstname, agentData.lastname);
273 }
274 }
275
276 }
277 else
278 {
279 denyMess = "Region not found";
280 }
281
282 if (success)
283 {
284 Hashtable respdata = new Hashtable();
285 respdata["success"] = "TRUE";
286 resp.Value = respdata;
287 }
288 else
289 {
290 Hashtable respdata = new Hashtable();
291 respdata["success"] = "FALSE";
292 respdata["reason"] = denyMess;
293 resp.Value = respdata;
294 }
281 } 295 }
282 } 296 }
297 catch (Exception e)
298 {
299 m_log.WarnFormat("[CLIENT]: Unable to receive user. Reason: {0}", e);
300 Hashtable respdata = new Hashtable();
301 respdata["success"] = "FALSE";
302 respdata["reason"] = "Exception occurred";
303 resp.Value = respdata;
304 }
283 305
284 return resp; 306 return resp;
285 } 307 }
diff --git a/OpenSim/Client/MXP/ClientStack/MXPClientView.cs b/OpenSim/Client/MXP/ClientStack/MXPClientView.cs
index e901ff6..bc1b2e5 100644
--- a/OpenSim/Client/MXP/ClientStack/MXPClientView.cs
+++ b/OpenSim/Client/MXP/ClientStack/MXPClientView.cs
@@ -886,7 +886,7 @@ namespace OpenSim.Client.MXP.ClientStack
886 chatActionEvent.ActionFragment.SourceObjectId = fromAgentID.Guid; 886 chatActionEvent.ActionFragment.SourceObjectId = fromAgentID.Guid;
887 chatActionEvent.ActionFragment.ObservationRadius = 180.0f; 887 chatActionEvent.ActionFragment.ObservationRadius = 180.0f;
888 chatActionEvent.ActionFragment.ExtensionDialect = "TEXT"; 888 chatActionEvent.ActionFragment.ExtensionDialect = "TEXT";
889 chatActionEvent.SetPayloadData(Encoding.UTF8.GetBytes(message)); 889 chatActionEvent.SetPayloadData(Util.UTF8.GetBytes(message));
890 890
891 Session.Send(chatActionEvent); 891 Session.Send(chatActionEvent);
892 } 892 }
diff --git a/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs b/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs
index 8c9eb5f..c649c5a 100644
--- a/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs
+++ b/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs
@@ -95,16 +95,15 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
95 95
96 ManagedImage tmp; 96 ManagedImage tmp;
97 Image imgData; 97 Image imgData;
98 byte[] jpegdata;
98 99
99 OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData); 100 OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData);
100
101 MemoryStream ms = new MemoryStream();
102 101
103 imgData.Save(ms, ImageFormat.Jpeg); 102 using (MemoryStream ms = new MemoryStream())
104 103 {
105 byte[] jpegdata = ms.GetBuffer(); 104 imgData.Save(ms, ImageFormat.Jpeg);
106 105 jpegdata = ms.GetBuffer();
107 ms.Close(); 106 }
108 107
109 resp.ContentType = "image/jpeg"; 108 resp.ContentType = "image/jpeg";
110 resp.ContentLength = jpegdata.Length; 109 resp.ContentLength = jpegdata.Length;
diff --git a/OpenSim/Data/MSSQL/AutoClosingSqlCommand.cs b/OpenSim/Data/MSSQL/AutoClosingSqlCommand.cs
index 93e48cd..0e21880 100644
--- a/OpenSim/Data/MSSQL/AutoClosingSqlCommand.cs
+++ b/OpenSim/Data/MSSQL/AutoClosingSqlCommand.cs
@@ -197,20 +197,11 @@ namespace OpenSim.Data.MSSQL
197 public void Dispose() 197 public void Dispose()
198 { 198 {
199 SqlConnection conn = realCommand.Connection; 199 SqlConnection conn = realCommand.Connection;
200 try 200 try { realCommand.Dispose(); }
201 {
202 realCommand.Dispose();
203 }
204 finally 201 finally
205 { 202 {
206 try 203 try { conn.Dispose(); }
207 { 204 finally { }
208 conn.Close();
209 }
210 finally
211 {
212 conn.Dispose();
213 }
214 } 205 }
215 } 206 }
216 207
diff --git a/OpenSim/Data/MSSQL/MSSQLInventoryData.cs b/OpenSim/Data/MSSQL/MSSQLInventoryData.cs
index 1482184..d49c2b3 100644
--- a/OpenSim/Data/MSSQL/MSSQLInventoryData.cs
+++ b/OpenSim/Data/MSSQL/MSSQLInventoryData.cs
@@ -348,8 +348,6 @@ namespace OpenSim.Data.MSSQL
348 //Delete the actual row 348 //Delete the actual row
349 DeleteOneFolder(folderID, connection); 349 DeleteOneFolder(folderID, connection);
350 DeleteItemsInFolder(folderID, connection); 350 DeleteItemsInFolder(folderID, connection);
351
352 connection.Close();
353 } 351 }
354 } 352 }
355 353
diff --git a/OpenSim/Data/MSSQL/MSSQLManager.cs b/OpenSim/Data/MSSQL/MSSQLManager.cs
index 3d7a768..992ce02 100644
--- a/OpenSim/Data/MSSQL/MSSQLManager.cs
+++ b/OpenSim/Data/MSSQL/MSSQLManager.cs
@@ -340,8 +340,6 @@ namespace OpenSim.Data.MSSQL
340 MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore); 340 MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
341 341
342 migration.Update(); 342 migration.Update();
343
344 connection.Close();
345 } 343 }
346 } 344 }
347 345
@@ -385,9 +383,7 @@ namespace OpenSim.Data.MSSQL
385 m_log.Error(e.ToString()); 383 m_log.Error(e.ToString());
386 } 384 }
387 } 385 }
388 tables.Close();
389 } 386 }
390
391 } 387 }
392 388
393 /// <summary> 389 /// <summary>
diff --git a/OpenSim/Data/MSSQL/MSSQLMigration.cs b/OpenSim/Data/MSSQL/MSSQLMigration.cs
index aea31c9..549bcb3 100644
--- a/OpenSim/Data/MSSQL/MSSQLMigration.cs
+++ b/OpenSim/Data/MSSQL/MSSQLMigration.cs
@@ -56,7 +56,6 @@ namespace OpenSim.Data.MSSQL
56 { 56 {
57 version = Convert.ToInt32(reader["version"]); 57 version = Convert.ToInt32(reader["version"]);
58 } 58 }
59 reader.Close();
60 } 59 }
61 } 60 }
62 catch 61 catch
diff --git a/OpenSim/Data/Migration.cs b/OpenSim/Data/Migration.cs
index e51dc22..7a99d4a 100644
--- a/OpenSim/Data/Migration.cs
+++ b/OpenSim/Data/Migration.cs
@@ -131,25 +131,26 @@ namespace OpenSim.Data
131 m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type); 131 m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type);
132 m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!"); 132 m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
133 133
134 DbCommand cmd = _conn.CreateCommand(); 134 using (DbCommand cmd = _conn.CreateCommand())
135 foreach (KeyValuePair<int, string> kvp in migrations)
136 { 135 {
137 int newversion = kvp.Key; 136 foreach (KeyValuePair<int, string> kvp in migrations)
138 cmd.CommandText = kvp.Value;
139 // we need to up the command timeout to infinite as we might be doing long migrations.
140 cmd.CommandTimeout = 0;
141 cmd.ExecuteNonQuery();
142
143 if (version == 0)
144 {
145 InsertVersion(_type, newversion);
146 }
147 else
148 { 137 {
149 UpdateVersion(_type, newversion); 138 int newversion = kvp.Key;
139 cmd.CommandText = kvp.Value;
140 // we need to up the command timeout to infinite as we might be doing long migrations.
141 cmd.CommandTimeout = 0;
142 cmd.ExecuteNonQuery();
143
144 if (version == 0)
145 {
146 InsertVersion(_type, newversion);
147 }
148 else
149 {
150 UpdateVersion(_type, newversion);
151 }
152 version = newversion;
150 } 153 }
151 version = newversion;
152 cmd.Dispose();
153 } 154 }
154 } 155 }
155 156
@@ -189,43 +190,45 @@ namespace OpenSim.Data
189 protected virtual int FindVersion(DbConnection conn, string type) 190 protected virtual int FindVersion(DbConnection conn, string type)
190 { 191 {
191 int version = 0; 192 int version = 0;
192 DbCommand cmd = conn.CreateCommand(); 193
193 try 194 using (DbCommand cmd = conn.CreateCommand())
194 { 195 {
195 cmd.CommandText = "select version from migrations where name='" + type +"' order by version desc"; 196 try
196 using (IDataReader reader = cmd.ExecuteReader())
197 { 197 {
198 if (reader.Read()) 198 cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
199 using (IDataReader reader = cmd.ExecuteReader())
199 { 200 {
200 version = Convert.ToInt32(reader["version"]); 201 if (reader.Read())
202 version = Convert.ToInt32(reader["version"]);
201 } 203 }
202 reader.Close(); 204 }
205 catch
206 {
207 // Something went wrong, so we're version 0
203 } 208 }
204 } 209 }
205 catch 210
206 {
207 // Something went wrong, so we're version 0
208 }
209 cmd.Dispose();
210 return version; 211 return version;
211 } 212 }
212 213
213 private void InsertVersion(string type, int version) 214 private void InsertVersion(string type, int version)
214 { 215 {
215 DbCommand cmd = _conn.CreateCommand(); 216 using (DbCommand cmd = _conn.CreateCommand())
216 cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")"; 217 {
217 m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version); 218 cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
218 cmd.ExecuteNonQuery(); 219 m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
219 cmd.Dispose(); 220 cmd.ExecuteNonQuery();
221 }
220 } 222 }
221 223
222 private void UpdateVersion(string type, int version) 224 private void UpdateVersion(string type, int version)
223 { 225 {
224 DbCommand cmd = _conn.CreateCommand(); 226 using (DbCommand cmd = _conn.CreateCommand())
225 cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'"; 227 {
226 m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version); 228 cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
227 cmd.ExecuteNonQuery(); 229 m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
228 cmd.Dispose(); 230 cmd.ExecuteNonQuery();
231 }
229 } 232 }
230 233
231 // private SortedList<int, string> GetAllMigrations() 234 // private SortedList<int, string> GetAllMigrations()
diff --git a/OpenSim/Data/MySQL/MySQLAssetData.cs b/OpenSim/Data/MySQL/MySQLAssetData.cs
index 0502b2b..8f97440 100644
--- a/OpenSim/Data/MySQL/MySQLAssetData.cs
+++ b/OpenSim/Data/MySQL/MySQLAssetData.cs
@@ -142,46 +142,45 @@ namespace OpenSim.Data.MySQL
142 { 142 {
143 _dbConnection.CheckConnection(); 143 _dbConnection.CheckConnection();
144 144
145 MySqlCommand cmd = 145 using (MySqlCommand cmd = new MySqlCommand(
146 new MySqlCommand( 146 "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id",
147 "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id", 147 _dbConnection.Connection))
148 _dbConnection.Connection);
149 cmd.Parameters.AddWithValue("?id", assetID.ToString());
150
151 try
152 { 148 {
153 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) 149 cmd.Parameters.AddWithValue("?id", assetID.ToString());
150
151 try
154 { 152 {
155 if (dbReader.Read()) 153 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
156 { 154 {
157 asset = new AssetBase(); 155 if (dbReader.Read())
158 asset.Data = (byte[]) dbReader["data"];
159 asset.Description = (string) dbReader["description"];
160 asset.FullID = assetID;
161 try
162 {
163 asset.Local = (bool)dbReader["local"];
164 }
165 catch (InvalidCastException)
166 { 156 {
167 asset.Local = false; 157 asset = new AssetBase();
158 asset.Data = (byte[])dbReader["data"];
159 asset.Description = (string)dbReader["description"];
160 asset.FullID = assetID;
161
162 string local = dbReader["local"].ToString();
163 if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
164 asset.Local = true;
165 else
166 asset.Local = false;
167
168 asset.Name = (string)dbReader["name"];
169 asset.Type = (sbyte)dbReader["assetType"];
170 asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
168 } 171 }
169 asset.Name = (string) dbReader["name"];
170 asset.Type = (sbyte) dbReader["assetType"];
171 asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
172 } 172 }
173 dbReader.Close(); 173
174 cmd.Dispose(); 174 if (asset != null)
175 UpdateAccessTime(asset);
176 }
177 catch (Exception e)
178 {
179 m_log.ErrorFormat(
180 "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
181 + Environment.NewLine + "Reconnecting", assetID);
182 _dbConnection.Reconnect();
175 } 183 }
176 if (asset != null)
177 UpdateAccessTime(asset);
178 }
179 catch (Exception e)
180 {
181 m_log.ErrorFormat(
182 "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
183 + Environment.NewLine + "Reconnecting", assetID);
184 _dbConnection.Reconnect();
185 } 184 }
186 } 185 }
187 return asset; 186 return asset;
@@ -297,32 +296,27 @@ namespace OpenSim.Data.MySQL
297 { 296 {
298 _dbConnection.CheckConnection(); 297 _dbConnection.CheckConnection();
299 298
300 MySqlCommand cmd = 299 using (MySqlCommand cmd = new MySqlCommand(
301 new MySqlCommand( 300 "SELECT id FROM assets WHERE id=?id",
302 "SELECT id FROM assets WHERE id=?id", 301 _dbConnection.Connection))
303 _dbConnection.Connection);
304
305 cmd.Parameters.AddWithValue("?id", uuid.ToString());
306
307 try
308 { 302 {
309 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) 303 cmd.Parameters.AddWithValue("?id", uuid.ToString());
304
305 try
310 { 306 {
311 if (dbReader.Read()) 307 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
312 { 308 {
313 assetExists = true; 309 if (dbReader.Read())
310 assetExists = true;
314 } 311 }
315
316 dbReader.Close();
317 cmd.Dispose();
318 } 312 }
319 } 313 catch (Exception e)
320 catch (Exception e) 314 {
321 { 315 m_log.ErrorFormat(
322 m_log.ErrorFormat( 316 "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
323 "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString() 317 + Environment.NewLine + "Attempting reconnection", uuid);
324 + Environment.NewLine + "Attempting reconnection", uuid); 318 _dbConnection.Reconnect();
325 _dbConnection.Reconnect(); 319 }
326 } 320 }
327 } 321 }
328 322
diff --git a/OpenSim/Data/MySQL/MySQLAuthenticationData.cs b/OpenSim/Data/MySQL/MySQLAuthenticationData.cs
index e508b52..e96a123 100644
--- a/OpenSim/Data/MySQL/MySQLAuthenticationData.cs
+++ b/OpenSim/Data/MySQL/MySQLAuthenticationData.cs
@@ -55,44 +55,38 @@ namespace OpenSim.Data.MySQL
55 AuthenticationData ret = new AuthenticationData(); 55 AuthenticationData ret = new AuthenticationData();
56 ret.Data = new Dictionary<string, object>(); 56 ret.Data = new Dictionary<string, object>();
57 57
58 MySqlCommand cmd = new MySqlCommand( 58 using (MySqlCommand cmd = new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID"))
59 "select * from `"+m_Realm+"` where UUID = ?principalID"
60 );
61
62 cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
63
64 IDataReader result = ExecuteReader(cmd);
65
66 if (result.Read())
67 { 59 {
68 ret.PrincipalID = principalID; 60 cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
69 61
70 if (m_ColumnNames == null) 62 using (IDataReader result = ExecuteReader(cmd))
71 { 63 {
72 m_ColumnNames = new List<string>(); 64 if (result.Read())
65 {
66 ret.PrincipalID = principalID;
73 67
74 DataTable schemaTable = result.GetSchemaTable(); 68 if (m_ColumnNames == null)
75 foreach (DataRow row in schemaTable.Rows) 69 {
76 m_ColumnNames.Add(row["ColumnName"].ToString()); 70 m_ColumnNames = new List<string>();
77 }
78 71
79 foreach (string s in m_ColumnNames) 72 DataTable schemaTable = result.GetSchemaTable();
80 { 73 foreach (DataRow row in schemaTable.Rows)
81 if (s == "UUID") 74 m_ColumnNames.Add(row["ColumnName"].ToString());
82 continue; 75 }
83 76
84 ret.Data[s] = result[s].ToString(); 77 foreach (string s in m_ColumnNames)
85 } 78 {
79 if (s == "UUID")
80 continue;
86 81
87 result.Close(); 82 ret.Data[s] = result[s].ToString();
88 CloseReaderCommand(cmd); 83 }
89 84
90 return ret; 85 return ret;
86 }
87 }
91 } 88 }
92 89
93 result.Close();
94 CloseReaderCommand(cmd);
95
96 return null; 90 return null;
97 } 91 }
98 92
diff --git a/OpenSim/Data/MySQL/MySQLEstateData.cs b/OpenSim/Data/MySQL/MySQLEstateData.cs
index e8694fc..7166b29 100644
--- a/OpenSim/Data/MySQL/MySQLEstateData.cs
+++ b/OpenSim/Data/MySQL/MySQLEstateData.cs
@@ -95,21 +95,17 @@ namespace OpenSim.Data.MySQL
95 95
96 protected void GetWaitTimeout() 96 protected void GetWaitTimeout()
97 { 97 {
98 MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, 98 using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, m_connection))
99 m_connection);
100
101 using (MySqlDataReader dbReader =
102 cmd.ExecuteReader(CommandBehavior.SingleRow))
103 { 99 {
104 if (dbReader.Read()) 100 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
105 { 101 {
106 m_waitTimeout 102 if (dbReader.Read())
107 = Convert.ToInt32(dbReader["@@wait_timeout"]) * 103 {
108 TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; 104 m_waitTimeout
105 = Convert.ToInt32(dbReader["@@wait_timeout"]) *
106 TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
107 }
109 } 108 }
110
111 dbReader.Close();
112 cmd.Dispose();
113 } 109 }
114 110
115 m_lastConnectionUse = DateTime.Now.Ticks; 111 m_lastConnectionUse = DateTime.Now.Ticks;
@@ -147,110 +143,103 @@ namespace OpenSim.Data.MySQL
147 143
148 CheckConnection(); 144 CheckConnection();
149 145
150 MySqlCommand cmd = m_connection.CreateCommand(); 146 bool migration = true;
151 147
152 cmd.CommandText = sql; 148 using (MySqlCommand cmd = m_connection.CreateCommand())
153 cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
154
155 IDataReader r = cmd.ExecuteReader();
156
157 if (r.Read())
158 { 149 {
159 foreach (string name in FieldList) 150 cmd.CommandText = sql;
160 { 151 cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
161 if (m_FieldMap[name].GetValue(es) is bool)
162 {
163 int v = Convert.ToInt32(r[name]);
164 if (v != 0)
165 m_FieldMap[name].SetValue(es, true);
166 else
167 m_FieldMap[name].SetValue(es, false);
168 }
169 else if (m_FieldMap[name].GetValue(es) is UUID)
170 {
171 UUID uuid = UUID.Zero;
172 152
173 UUID.TryParse(r[name].ToString(), out uuid); 153 using (IDataReader r = cmd.ExecuteReader())
174 m_FieldMap[name].SetValue(es, uuid); 154 {
175 } 155 if (r.Read())
176 else
177 { 156 {
178 m_FieldMap[name].SetValue(es, r[name]); 157 migration = false;
158
159 foreach (string name in FieldList)
160 {
161 if (m_FieldMap[name].GetValue(es) is bool)
162 {
163 int v = Convert.ToInt32(r[name]);
164 if (v != 0)
165 m_FieldMap[name].SetValue(es, true);
166 else
167 m_FieldMap[name].SetValue(es, false);
168 }
169 else if (m_FieldMap[name].GetValue(es) is UUID)
170 {
171 UUID uuid = UUID.Zero;
172
173 UUID.TryParse(r[name].ToString(), out uuid);
174 m_FieldMap[name].SetValue(es, uuid);
175 }
176 else
177 {
178 m_FieldMap[name].SetValue(es, r[name]);
179 }
180 }
179 } 181 }
180 } 182 }
181 r.Close();
182 } 183 }
183 else 184
185 if (migration)
184 { 186 {
185 // Migration case 187 // Migration case
186 //
187 r.Close();
188
189 List<string> names = new List<string>(FieldList); 188 List<string> names = new List<string>(FieldList);
190 189
191 names.Remove("EstateID"); 190 names.Remove("EstateID");
192 191
193 sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; 192 sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")";
194 193
195 cmd.CommandText = sql; 194 using (MySqlCommand cmd = m_connection.CreateCommand())
196 cmd.Parameters.Clear();
197
198 foreach (string name in FieldList)
199 { 195 {
200 if (m_FieldMap[name].GetValue(es) is bool) 196 cmd.CommandText = sql;
197 cmd.Parameters.Clear();
198
199 foreach (string name in FieldList)
201 { 200 {
202 if ((bool)m_FieldMap[name].GetValue(es)) 201 if (m_FieldMap[name].GetValue(es) is bool)
203 cmd.Parameters.AddWithValue("?" + name, "1"); 202 {
203 if ((bool)m_FieldMap[name].GetValue(es))
204 cmd.Parameters.AddWithValue("?" + name, "1");
205 else
206 cmd.Parameters.AddWithValue("?" + name, "0");
207 }
204 else 208 else
205 cmd.Parameters.AddWithValue("?" + name, "0"); 209 {
210 cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
211 }
206 } 212 }
207 else
208 {
209 cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
210 }
211 }
212
213 cmd.ExecuteNonQuery();
214 213
215 cmd.CommandText = "select LAST_INSERT_ID() as id"; 214 cmd.ExecuteNonQuery();
216 cmd.Parameters.Clear();
217
218 r = cmd.ExecuteReader();
219 215
220 r.Read(); 216 cmd.CommandText = "select LAST_INSERT_ID() as id";
217 cmd.Parameters.Clear();
221 218
222 es.EstateID = Convert.ToUInt32(r["id"]); 219 using (IDataReader r = cmd.ExecuteReader())
220 {
221 r.Read();
222 es.EstateID = Convert.ToUInt32(r["id"]);
223 }
223 224
224 r.Close(); 225 cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
226 cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
227 cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
225 228
226 cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; 229 // This will throw on dupe key
227 cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); 230 try { cmd.ExecuteNonQuery(); }
228 cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); 231 catch (Exception) { }
229 232
230 // This will throw on dupe key 233 // Munge and transfer the ban list
231 try 234 cmd.Parameters.Clear();
232 { 235 cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
233 cmd.ExecuteNonQuery(); 236 cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
234 }
235 catch (Exception)
236 {
237 }
238 237
239 // Munge and transfer the ban list 238 try { cmd.ExecuteNonQuery(); }
240 // 239 catch (Exception) { }
241 cmd.Parameters.Clear();
242 cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
243 cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
244 240
245 try 241 es.Save();
246 {
247 cmd.ExecuteNonQuery();
248 }
249 catch (Exception)
250 {
251 } 242 }
252
253 es.Save();
254 } 243 }
255 244
256 LoadBanList(es); 245 LoadBanList(es);
@@ -267,26 +256,27 @@ namespace OpenSim.Data.MySQL
267 256
268 CheckConnection(); 257 CheckConnection();
269 258
270 MySqlCommand cmd = m_connection.CreateCommand(); 259 using (MySqlCommand cmd = m_connection.CreateCommand())
271
272 cmd.CommandText = sql;
273
274 foreach (string name in FieldList)
275 { 260 {
276 if (m_FieldMap[name].GetValue(es) is bool) 261 cmd.CommandText = sql;
262
263 foreach (string name in FieldList)
277 { 264 {
278 if ((bool)m_FieldMap[name].GetValue(es)) 265 if (m_FieldMap[name].GetValue(es) is bool)
279 cmd.Parameters.AddWithValue("?" + name, "1"); 266 {
267 if ((bool)m_FieldMap[name].GetValue(es))
268 cmd.Parameters.AddWithValue("?" + name, "1");
269 else
270 cmd.Parameters.AddWithValue("?" + name, "0");
271 }
280 else 272 else
281 cmd.Parameters.AddWithValue("?" + name, "0"); 273 {
282 } 274 cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
283 else 275 }
284 {
285 cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
286 } 276 }
287 }
288 277
289 cmd.ExecuteNonQuery(); 278 cmd.ExecuteNonQuery();
279 }
290 280
291 SaveBanList(es); 281 SaveBanList(es);
292 SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); 282 SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
@@ -300,50 +290,52 @@ namespace OpenSim.Data.MySQL
300 290
301 CheckConnection(); 291 CheckConnection();
302 292
303 MySqlCommand cmd = m_connection.CreateCommand(); 293 using (MySqlCommand cmd = m_connection.CreateCommand())
304
305 cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
306 cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
307
308 IDataReader r = cmd.ExecuteReader();
309
310 while (r.Read())
311 { 294 {
312 EstateBan eb = new EstateBan(); 295 cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
296 cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
297
298 using (IDataReader r = cmd.ExecuteReader())
299 {
300 while (r.Read())
301 {
302 EstateBan eb = new EstateBan();
313 303
314 UUID uuid = new UUID(); 304 UUID uuid = new UUID();
315 UUID.TryParse(r["bannedUUID"].ToString(), out uuid); 305 UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
316 306
317 eb.BannedUserID = uuid; 307 eb.BannedUserID = uuid;
318 eb.BannedHostAddress = "0.0.0.0"; 308 eb.BannedHostAddress = "0.0.0.0";
319 eb.BannedHostIPMask = "0.0.0.0"; 309 eb.BannedHostIPMask = "0.0.0.0";
320 es.AddBan(eb); 310 es.AddBan(eb);
311 }
312 }
321 } 313 }
322 r.Close();
323 } 314 }
324 315
325 private void SaveBanList(EstateSettings es) 316 private void SaveBanList(EstateSettings es)
326 { 317 {
327 CheckConnection(); 318 CheckConnection();
328 319
329 MySqlCommand cmd = m_connection.CreateCommand(); 320 using (MySqlCommand cmd = m_connection.CreateCommand())
330
331 cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
332 cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
333
334 cmd.ExecuteNonQuery();
335
336 cmd.Parameters.Clear();
337
338 cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
339
340 foreach (EstateBan b in es.EstateBans)
341 { 321 {
322 cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
342 cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); 323 cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
343 cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
344 324
345 cmd.ExecuteNonQuery(); 325 cmd.ExecuteNonQuery();
326
346 cmd.Parameters.Clear(); 327 cmd.Parameters.Clear();
328
329 cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
330
331 foreach (EstateBan b in es.EstateBans)
332 {
333 cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
334 cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
335
336 cmd.ExecuteNonQuery();
337 cmd.Parameters.Clear();
338 }
347 } 339 }
348 } 340 }
349 341
@@ -351,24 +343,25 @@ namespace OpenSim.Data.MySQL
351 { 343 {
352 CheckConnection(); 344 CheckConnection();
353 345
354 MySqlCommand cmd = m_connection.CreateCommand(); 346 using (MySqlCommand cmd = m_connection.CreateCommand())
355
356 cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
357 cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
358
359 cmd.ExecuteNonQuery();
360
361 cmd.Parameters.Clear();
362
363 cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )";
364
365 foreach (UUID uuid in data)
366 { 347 {
348 cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
367 cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); 349 cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
368 cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
369 350
370 cmd.ExecuteNonQuery(); 351 cmd.ExecuteNonQuery();
352
371 cmd.Parameters.Clear(); 353 cmd.Parameters.Clear();
354
355 cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )";
356
357 foreach (UUID uuid in data)
358 {
359 cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
360 cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
361
362 cmd.ExecuteNonQuery();
363 cmd.Parameters.Clear();
364 }
372 } 365 }
373 } 366 }
374 367
@@ -378,23 +371,24 @@ namespace OpenSim.Data.MySQL
378 371
379 CheckConnection(); 372 CheckConnection();
380 373
381 MySqlCommand cmd = m_connection.CreateCommand(); 374 using (MySqlCommand cmd = m_connection.CreateCommand())
382
383 cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
384 cmd.Parameters.AddWithValue("?EstateID", EstateID);
385
386 IDataReader r = cmd.ExecuteReader();
387
388 while (r.Read())
389 { 375 {
390 // EstateBan eb = new EstateBan(); 376 cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
377 cmd.Parameters.AddWithValue("?EstateID", EstateID);
391 378
392 UUID uuid = new UUID(); 379 using (IDataReader r = cmd.ExecuteReader())
393 UUID.TryParse(r["uuid"].ToString(), out uuid); 380 {
381 while (r.Read())
382 {
383 // EstateBan eb = new EstateBan();
394 384
395 uuids.Add(uuid); 385 UUID uuid = new UUID();
386 UUID.TryParse(r["uuid"].ToString(), out uuid);
387
388 uuids.Add(uuid);
389 }
390 }
396 } 391 }
397 r.Close();
398 392
399 return uuids.ToArray(); 393 return uuids.ToArray();
400 } 394 }
diff --git a/OpenSim/Data/MySQL/MySQLFramework.cs b/OpenSim/Data/MySQL/MySQLFramework.cs
index 6c73249..c756c9c 100644
--- a/OpenSim/Data/MySQL/MySQLFramework.cs
+++ b/OpenSim/Data/MySQL/MySQLFramework.cs
@@ -40,6 +40,8 @@ namespace OpenSim.Data.MySQL
40 /// </summary> 40 /// </summary>
41 public class MySqlFramework 41 public class MySqlFramework
42 { 42 {
43 private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
44
43 protected MySqlConnection m_Connection; 45 protected MySqlConnection m_Connection;
44 46
45 protected MySqlFramework(string connectionString) 47 protected MySqlFramework(string connectionString)
@@ -70,12 +72,11 @@ namespace OpenSim.Data.MySQL
70 } 72 }
71 catch (MySqlException e) 73 catch (MySqlException e)
72 { 74 {
73Console.WriteLine(e.ToString()); 75 m_log.Error(e.Message, e);
74 if (errorSeen) 76 if (errorSeen)
75 throw; 77 throw;
76 78
77 // This is "Server has gone away" and "Server lost" 79 // This is "Server has gone away" and "Server lost"
78 //
79 if (e.Number == 2006 || e.Number == 2013) 80 if (e.Number == 2006 || e.Number == 2013)
80 { 81 {
81 errorSeen = true; 82 errorSeen = true;
@@ -94,7 +95,7 @@ Console.WriteLine(e.ToString());
94 } 95 }
95 catch (Exception e) 96 catch (Exception e)
96 { 97 {
97Console.WriteLine(e.ToString()); 98 m_log.Error(e.Message, e);
98 return 0; 99 return 0;
99 } 100 }
100 } 101 }
@@ -112,12 +113,5 @@ Console.WriteLine(e.ToString());
112 113
113 return cmd.ExecuteReader(); 114 return cmd.ExecuteReader();
114 } 115 }
115
116 protected void CloseReaderCommand(MySqlCommand cmd)
117 {
118 cmd.Connection.Close();
119 cmd.Connection.Dispose();
120 cmd.Dispose();
121 }
122 } 116 }
123} 117}
diff --git a/OpenSim/Data/MySQL/MySQLGridData.cs b/OpenSim/Data/MySQL/MySQLGridData.cs
index 1ec2609..38cb3b7 100644
--- a/OpenSim/Data/MySQL/MySQLGridData.cs
+++ b/OpenSim/Data/MySQL/MySQLGridData.cs
@@ -197,29 +197,27 @@ namespace OpenSim.Data.MySQL
197 param["?xmax"] = xmax.ToString(); 197 param["?xmax"] = xmax.ToString();
198 param["?ymax"] = ymax.ToString(); 198 param["?ymax"] = ymax.ToString();
199 199
200 IDbCommand result = 200 using (IDbCommand result = dbm.Manager.Query(
201 dbm.Manager.Query(
202 "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", 201 "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax",
203 param); 202 param))
204 IDataReader reader = result.ExecuteReader(); 203 {
204 using (IDataReader reader = result.ExecuteReader())
205 {
206 RegionProfileData row;
205 207
206 RegionProfileData row; 208 List<RegionProfileData> rows = new List<RegionProfileData>();
207 209
208 List<RegionProfileData> rows = new List<RegionProfileData>(); 210 while ((row = dbm.Manager.readSimRow(reader)) != null)
211 rows.Add(row);
209 212
210 while ((row = dbm.Manager.readSimRow(reader)) != null) 213 return rows.ToArray();
211 { 214 }
212 rows.Add(row);
213 } 215 }
214 reader.Close();
215 result.Dispose();
216
217 return rows.ToArray();
218 } 216 }
219 catch (Exception e) 217 catch (Exception e)
220 { 218 {
221 dbm.Manager.Reconnect(); 219 dbm.Manager.Reconnect();
222 m_log.Error(e.ToString()); 220 m_log.Error(e.Message, e);
223 return null; 221 return null;
224 } 222 }
225 finally 223 finally
@@ -243,29 +241,27 @@ namespace OpenSim.Data.MySQL
243 Dictionary<string, object> param = new Dictionary<string, object>(); 241 Dictionary<string, object> param = new Dictionary<string, object>();
244 param["?name"] = namePrefix + "%"; 242 param["?name"] = namePrefix + "%";
245 243
246 IDbCommand result = 244 using (IDbCommand result = dbm.Manager.Query(
247 dbm.Manager.Query( 245 "SELECT * FROM regions WHERE regionName LIKE ?name",
248 "SELECT * FROM regions WHERE regionName LIKE ?name", 246 param))
249 param); 247 {
250 IDataReader reader = result.ExecuteReader(); 248 using (IDataReader reader = result.ExecuteReader())
249 {
250 RegionProfileData row;
251 251
252 RegionProfileData row; 252 List<RegionProfileData> rows = new List<RegionProfileData>();
253 253
254 List<RegionProfileData> rows = new List<RegionProfileData>(); 254 while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
255 rows.Add(row);
255 256
256 while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null) 257 return rows;
257 { 258 }
258 rows.Add(row);
259 } 259 }
260 reader.Close();
261 result.Dispose();
262
263 return rows;
264 } 260 }
265 catch (Exception e) 261 catch (Exception e)
266 { 262 {
267 dbm.Manager.Reconnect(); 263 dbm.Manager.Reconnect();
268 m_log.Error(e.ToString()); 264 m_log.Error(e.Message, e);
269 return null; 265 return null;
270 } 266 }
271 finally 267 finally
@@ -286,21 +282,21 @@ namespace OpenSim.Data.MySQL
286 try 282 try
287 { 283 {
288 Dictionary<string, object> param = new Dictionary<string, object>(); 284 Dictionary<string, object> param = new Dictionary<string, object>();
289 param["?handle"] = handle.ToString(); 285 param["?handle"] = handle.ToString();
290
291 IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param);
292 IDataReader reader = result.ExecuteReader();
293 286
294 RegionProfileData row = dbm.Manager.readSimRow(reader); 287 using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param))
295 reader.Close(); 288 {
296 result.Dispose(); 289 using (IDataReader reader = result.ExecuteReader())
297 290 {
298 return row; 291 RegionProfileData row = dbm.Manager.readSimRow(reader);
292 return row;
293 }
299 } 294 }
295 }
300 catch (Exception e) 296 catch (Exception e)
301 { 297 {
302 dbm.Manager.Reconnect(); 298 dbm.Manager.Reconnect();
303 m_log.Error(e.ToString()); 299 m_log.Error(e.Message, e);
304 return null; 300 return null;
305 } 301 }
306 finally 302 finally
@@ -321,23 +317,24 @@ namespace OpenSim.Data.MySQL
321 try 317 try
322 { 318 {
323 Dictionary<string, object> param = new Dictionary<string, object>(); 319 Dictionary<string, object> param = new Dictionary<string, object>();
324 param["?uuid"] = uuid.ToString(); 320 param["?uuid"] = uuid.ToString();
325 321
326 IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param); 322 using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param))
327 IDataReader reader = result.ExecuteReader(); 323 {
328 324 using (IDataReader reader = result.ExecuteReader())
329 RegionProfileData row = dbm.Manager.readSimRow(reader); 325 {
330 reader.Close(); 326 RegionProfileData row = dbm.Manager.readSimRow(reader);
331 result.Dispose(); 327 return row;
332 328 }
333 return row;
334 } 329 }
330 }
335 catch (Exception e) 331 catch (Exception e)
336 { 332 {
337 dbm.Manager.Reconnect(); 333 dbm.Manager.Reconnect();
338 m_log.Error(e.ToString()); 334 m_log.Error(e.Message, e);
339 return null; 335 return null;
340 } finally 336 }
337 finally
341 { 338 {
342 dbm.Release(); 339 dbm.Release();
343 } 340 }
@@ -359,22 +356,21 @@ namespace OpenSim.Data.MySQL
359 // Add % because this is a like query. 356 // Add % because this is a like query.
360 param["?regionName"] = regionName + "%"; 357 param["?regionName"] = regionName + "%";
361 // Order by statement will return shorter matches first. Only returns one record or no record. 358 // Order by statement will return shorter matches first. Only returns one record or no record.
362 IDbCommand result = 359 using (IDbCommand result = dbm.Manager.Query(
363 dbm.Manager.Query( 360 "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1",
364 "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", 361 param))
365 param); 362 {
366 IDataReader reader = result.ExecuteReader(); 363 using (IDataReader reader = result.ExecuteReader())
367 364 {
368 RegionProfileData row = dbm.Manager.readSimRow(reader); 365 RegionProfileData row = dbm.Manager.readSimRow(reader);
369 reader.Close(); 366 return row;
370 result.Dispose(); 367 }
371 368 }
372 return row;
373 } 369 }
374 catch (Exception e) 370 catch (Exception e)
375 { 371 {
376 dbm.Manager.Reconnect(); 372 dbm.Manager.Reconnect();
377 m_log.Error(e.ToString()); 373 m_log.Error(e.Message, e);
378 return null; 374 return null;
379 } 375 }
380 finally 376 finally
@@ -382,6 +378,7 @@ namespace OpenSim.Data.MySQL
382 dbm.Release(); 378 dbm.Release();
383 } 379 }
384 } 380 }
381
385 m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); 382 m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters");
386 return null; 383 return null;
387 } 384 }
@@ -394,12 +391,12 @@ namespace OpenSim.Data.MySQL
394 override public DataResponse StoreProfile(RegionProfileData profile) 391 override public DataResponse StoreProfile(RegionProfileData profile)
395 { 392 {
396 MySQLSuperManager dbm = GetLockedConnection(); 393 MySQLSuperManager dbm = GetLockedConnection();
397 try { 394 try
395 {
398 if (dbm.Manager.insertRegion(profile)) 396 if (dbm.Manager.insertRegion(profile))
399 {
400 return DataResponse.RESPONSE_OK; 397 return DataResponse.RESPONSE_OK;
401 } 398 else
402 return DataResponse.RESPONSE_ERROR; 399 return DataResponse.RESPONSE_ERROR;
403 } 400 }
404 finally 401 finally
405 { 402 {
@@ -417,14 +414,14 @@ namespace OpenSim.Data.MySQL
417 { 414 {
418 MySQLSuperManager dbm = GetLockedConnection(); 415 MySQLSuperManager dbm = GetLockedConnection();
419 416
420 417 try
421 try { 418 {
422 if (dbm.Manager.deleteRegion(uuid)) 419 if (dbm.Manager.deleteRegion(uuid))
423 {
424 return DataResponse.RESPONSE_OK; 420 return DataResponse.RESPONSE_OK;
425 } 421 else
426 return DataResponse.RESPONSE_ERROR; 422 return DataResponse.RESPONSE_ERROR;
427 } finally 423 }
424 finally
428 { 425 {
429 dbm.Release(); 426 dbm.Release();
430 } 427 }
@@ -482,26 +479,26 @@ namespace OpenSim.Data.MySQL
482 try 479 try
483 { 480 {
484 Dictionary<string, object> param = new Dictionary<string, object>(); 481 Dictionary<string, object> param = new Dictionary<string, object>();
485 param["?x"] = x.ToString(); 482 param["?x"] = x.ToString();
486 param["?y"] = y.ToString(); 483 param["?y"] = y.ToString();
487 IDbCommand result = 484 using (IDbCommand result = dbm.Manager.Query(
488 dbm.Manager.Query( 485 "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
489 "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", 486 param))
490 param); 487 {
491 IDataReader reader = result.ExecuteReader(); 488 using (IDataReader reader = result.ExecuteReader())
492 489 {
493 ReservationData row = dbm.Manager.readReservationRow(reader); 490 ReservationData row = dbm.Manager.readReservationRow(reader);
494 reader.Close(); 491 return row;
495 result.Dispose(); 492 }
496 493 }
497 return row;
498 } 494 }
499 catch (Exception e) 495 catch (Exception e)
500 { 496 {
501 dbm.Manager.Reconnect(); 497 dbm.Manager.Reconnect();
502 m_log.Error(e.ToString()); 498 m_log.Error(e.Message, e);
503 return null; 499 return null;
504 } finally 500 }
501 finally
505 { 502 {
506 dbm.Release(); 503 dbm.Release();
507 } 504 }
diff --git a/OpenSim/Data/MySQL/MySQLInventoryData.cs b/OpenSim/Data/MySQL/MySQLInventoryData.cs
index 0eecf06..598971d 100644
--- a/OpenSim/Data/MySQL/MySQLInventoryData.cs
+++ b/OpenSim/Data/MySQL/MySQLInventoryData.cs
@@ -135,30 +135,30 @@ namespace OpenSim.Data.MySQL
135 135
136 database.CheckConnection(); 136 database.CheckConnection();
137 137
138 MySqlCommand result = 138 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
139 new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid", 139 database.Connection))
140 database.Connection);
141 result.Parameters.AddWithValue("?uuid", folderID.ToString());
142 MySqlDataReader reader = result.ExecuteReader();
143
144 while (reader.Read())
145 { 140 {
146 // A null item (because something went wrong) breaks everything in the folder 141 result.Parameters.AddWithValue("?uuid", folderID.ToString());
147 InventoryItemBase item = readInventoryItem(reader);
148 if (item != null)
149 items.Add(item);
150 }
151 142
152 reader.Close(); 143 using (MySqlDataReader reader = result.ExecuteReader())
153 result.Dispose(); 144 {
145 while (reader.Read())
146 {
147 // A null item (because something went wrong) breaks everything in the folder
148 InventoryItemBase item = readInventoryItem(reader);
149 if (item != null)
150 items.Add(item);
151 }
154 152
155 return items; 153 return items;
154 }
155 }
156 } 156 }
157 } 157 }
158 catch (Exception e) 158 catch (Exception e)
159 { 159 {
160 database.Reconnect(); 160 database.Reconnect();
161 m_log.Error(e.ToString()); 161 m_log.Error(e.Message, e);
162 return null; 162 return null;
163 } 163 }
164 } 164 }
@@ -176,29 +176,28 @@ namespace OpenSim.Data.MySQL
176 { 176 {
177 database.CheckConnection(); 177 database.CheckConnection();
178 178
179 MySqlCommand result = 179 using (MySqlCommand result = new MySqlCommand(
180 new MySqlCommand( 180 "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
181 "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", 181 database.Connection))
182 database.Connection); 182 {
183 result.Parameters.AddWithValue("?uuid", user.ToString()); 183 result.Parameters.AddWithValue("?uuid", user.ToString());
184 result.Parameters.AddWithValue("?zero", UUID.Zero.ToString()); 184 result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
185 MySqlDataReader reader = result.ExecuteReader();
186
187 List<InventoryFolderBase> items = new List<InventoryFolderBase>();
188 while (reader.Read())
189 items.Add(readInventoryFolder(reader));
190
191 185
192 reader.Close(); 186 using (MySqlDataReader reader = result.ExecuteReader())
193 result.Dispose(); 187 {
188 List<InventoryFolderBase> items = new List<InventoryFolderBase>();
189 while (reader.Read())
190 items.Add(readInventoryFolder(reader));
194 191
195 return items; 192 return items;
193 }
194 }
196 } 195 }
197 } 196 }
198 catch (Exception e) 197 catch (Exception e)
199 { 198 {
200 database.Reconnect(); 199 database.Reconnect();
201 m_log.Error(e.ToString()); 200 m_log.Error(e.Message, e);
202 return null; 201 return null;
203 } 202 }
204 } 203 }
@@ -217,41 +216,38 @@ namespace OpenSim.Data.MySQL
217 { 216 {
218 database.CheckConnection(); 217 database.CheckConnection();
219 218
220 MySqlCommand result = 219 using (MySqlCommand result = new MySqlCommand(
221 new MySqlCommand( 220 "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
222 "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", 221 database.Connection))
223 database.Connection); 222 {
224 result.Parameters.AddWithValue("?uuid", user.ToString()); 223 result.Parameters.AddWithValue("?uuid", user.ToString());
225 result.Parameters.AddWithValue("?zero", UUID.Zero.ToString()); 224 result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
226 225
227 MySqlDataReader reader = result.ExecuteReader(); 226 using (MySqlDataReader reader = result.ExecuteReader())
227 {
228 List<InventoryFolderBase> items = new List<InventoryFolderBase>();
229 while (reader.Read())
230 items.Add(readInventoryFolder(reader));
228 231
229 List<InventoryFolderBase> items = new List<InventoryFolderBase>(); 232 InventoryFolderBase rootFolder = null;
230 while (reader.Read())
231 items.Add(readInventoryFolder(reader));
232 233
233 InventoryFolderBase rootFolder = null; 234 // There should only ever be one root folder for a user. However, if there's more
235 // than one we'll simply use the first one rather than failing. It would be even
236 // nicer to print some message to this effect, but this feels like it's too low a
237 // to put such a message out, and it's too minor right now to spare the time to
238 // suitably refactor.
239 if (items.Count > 0)
240 rootFolder = items[0];
234 241
235 // There should only ever be one root folder for a user. However, if there's more 242 return rootFolder;
236 // than one we'll simply use the first one rather than failing. It would be even 243 }
237 // nicer to print some message to this effect, but this feels like it's too low a
238 // to put such a message out, and it's too minor right now to spare the time to
239 // suitably refactor.
240 if (items.Count > 0)
241 {
242 rootFolder = items[0];
243 } 244 }
244
245 reader.Close();
246 result.Dispose();
247
248 return rootFolder;
249 } 245 }
250 } 246 }
251 catch (Exception e) 247 catch (Exception e)
252 { 248 {
253 database.Reconnect(); 249 database.Reconnect();
254 m_log.Error(e.ToString()); 250 m_log.Error(e.Message, e);
255 return null; 251 return null;
256 } 252 }
257 } 253 }
@@ -271,27 +267,26 @@ namespace OpenSim.Data.MySQL
271 { 267 {
272 database.CheckConnection(); 268 database.CheckConnection();
273 269
274 MySqlCommand result = 270 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
275 new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid", 271 database.Connection))
276 database.Connection); 272 {
277 result.Parameters.AddWithValue("?uuid", parentID.ToString()); 273 result.Parameters.AddWithValue("?uuid", parentID.ToString());
278 MySqlDataReader reader = result.ExecuteReader(); 274 using (MySqlDataReader reader = result.ExecuteReader())
279 275 {
280 List<InventoryFolderBase> items = new List<InventoryFolderBase>(); 276 List<InventoryFolderBase> items = new List<InventoryFolderBase>();
281
282 while (reader.Read())
283 items.Add(readInventoryFolder(reader));
284 277
285 reader.Close(); 278 while (reader.Read())
286 result.Dispose(); 279 items.Add(readInventoryFolder(reader));
287 280
288 return items; 281 return items;
282 }
283 }
289 } 284 }
290 } 285 }
291 catch (Exception e) 286 catch (Exception e)
292 { 287 {
293 database.Reconnect(); 288 database.Reconnect();
294 m_log.Error(e.ToString()); 289 m_log.Error(e.Message, e);
295 return null; 290 return null;
296 } 291 }
297 } 292 }
@@ -370,25 +365,25 @@ namespace OpenSim.Data.MySQL
370 { 365 {
371 database.CheckConnection(); 366 database.CheckConnection();
372 367
373 MySqlCommand result = 368 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection))
374 new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection); 369 {
375 result.Parameters.AddWithValue("?uuid", itemID.ToString()); 370 result.Parameters.AddWithValue("?uuid", itemID.ToString());
376 MySqlDataReader reader = result.ExecuteReader();
377
378 InventoryItemBase item = null;
379 if (reader.Read())
380 item = readInventoryItem(reader);
381 371
382 reader.Close(); 372 using (MySqlDataReader reader = result.ExecuteReader())
383 result.Dispose(); 373 {
374 InventoryItemBase item = null;
375 if (reader.Read())
376 item = readInventoryItem(reader);
384 377
385 return item; 378 return item;
379 }
380 }
386 } 381 }
387 } 382 }
388 catch (Exception e) 383 catch (Exception e)
389 { 384 {
390 database.Reconnect(); 385 database.Reconnect();
391 m_log.Error(e.ToString()); 386 m_log.Error(e.Message, e);
392 } 387 }
393 return null; 388 return null;
394 } 389 }
@@ -413,7 +408,7 @@ namespace OpenSim.Data.MySQL
413 } 408 }
414 catch (Exception e) 409 catch (Exception e)
415 { 410 {
416 m_log.Error(e.ToString()); 411 m_log.Error(e.Message, e);
417 } 412 }
418 413
419 return null; 414 return null;
@@ -433,24 +428,25 @@ namespace OpenSim.Data.MySQL
433 { 428 {
434 database.CheckConnection(); 429 database.CheckConnection();
435 430
436 MySqlCommand result = 431 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
437 new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection); 432 {
438 result.Parameters.AddWithValue("?uuid", folderID.ToString()); 433 result.Parameters.AddWithValue("?uuid", folderID.ToString());
439 MySqlDataReader reader = result.ExecuteReader();
440 434
441 InventoryFolderBase folder = null; 435 using (MySqlDataReader reader = result.ExecuteReader())
442 if (reader.Read()) 436 {
443 folder = readInventoryFolder(reader); 437 InventoryFolderBase folder = null;
444 reader.Close(); 438 if (reader.Read())
445 result.Dispose(); 439 folder = readInventoryFolder(reader);
446 440
447 return folder; 441 return folder;
442 }
443 }
448 } 444 }
449 } 445 }
450 catch (Exception e) 446 catch (Exception e)
451 { 447 {
452 database.Reconnect(); 448 database.Reconnect();
453 m_log.Error(e.ToString()); 449 m_log.Error(e.Message, e);
454 return null; 450 return null;
455 } 451 }
456 } 452 }
@@ -698,69 +694,73 @@ namespace OpenSim.Data.MySQL
698 try 694 try
699 { 695 {
700 List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); 696 List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
701 Dictionary<UUID, List<InventoryFolderBase>> hashtable 697 Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(); ;
702 = new Dictionary<UUID, List<InventoryFolderBase>>(); ;
703 List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>(); 698 List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>();
699 bool buildResultsFromHashTable = false;
700
704 lock (database) 701 lock (database)
705 { 702 {
706 MySqlCommand result;
707 MySqlDataReader reader;
708 bool buildResultsFromHashTable = false;
709
710 database.CheckConnection(); 703 database.CheckConnection();
711 704
712 /* Fetch the parent folder from the database to determine the agent ID, and if 705 /* Fetch the parent folder from the database to determine the agent ID, and if
713 * we're querying the root of the inventory folder tree */ 706 * we're querying the root of the inventory folder tree */
714 result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", 707 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
715 database.Connection); 708 {
716 result.Parameters.AddWithValue("?uuid", parentID.ToString()); 709 result.Parameters.AddWithValue("?uuid", parentID.ToString());
717 reader = result.ExecuteReader(); 710
718 while (reader.Read()) // Should be at most 1 result 711 using (MySqlDataReader reader = result.ExecuteReader())
719 parentFolder.Add(readInventoryFolder(reader)); 712 {
720 reader.Close(); 713 // Should be at most 1 result
721 result.Dispose(); 714 while (reader.Read())
715 parentFolder.Add(readInventoryFolder(reader));
716 }
717 }
722 718
723 if (parentFolder.Count >= 1) // No result means parent folder does not exist 719 if (parentFolder.Count >= 1) // No result means parent folder does not exist
724 { 720 {
725 if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder 721 if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder
726 { 722 {
727 /* Get all of the agent's folders from the database, put them in a list and return it */ 723 /* Get all of the agent's folders from the database, put them in a list and return it */
728 result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", 724 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
729 database.Connection);
730 result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
731 reader = result.ExecuteReader();
732 while (reader.Read())
733 { 725 {
734 InventoryFolderBase curFolder = readInventoryFolder(reader); 726 result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
735 if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list 727
736 folders.Add(curFolder); 728 using (MySqlDataReader reader = result.ExecuteReader())
729 {
730 while (reader.Read())
731 {
732 InventoryFolderBase curFolder = readInventoryFolder(reader);
733 if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
734 folders.Add(curFolder);
735 }
736 }
737 } 737 }
738 reader.Close();
739 result.Dispose();
740 } // if we are querying the root folder 738 } // if we are querying the root folder
741 else // else we are querying a subtree of the inventory folder tree 739 else // else we are querying a subtree of the inventory folder tree
742 { 740 {
743 /* Get all of the agent's folders from the database, put them all in a hash table 741 /* Get all of the agent's folders from the database, put them all in a hash table
744 * indexed by their parent ID */ 742 * indexed by their parent ID */
745 result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", 743 using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
746 database.Connection);
747 result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
748 reader = result.ExecuteReader();
749 while (reader.Read())
750 { 744 {
751 InventoryFolderBase curFolder = readInventoryFolder(reader); 745 result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
752 if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling 746
753 hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list 747 using (MySqlDataReader reader = result.ExecuteReader())
754 else // else current folder has no known (yet) siblings
755 { 748 {
756 List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>(); 749 while (reader.Read())
757 siblingList.Add(curFolder); 750 {
758 // Current folder has no known (yet) siblings 751 InventoryFolderBase curFolder = readInventoryFolder(reader);
759 hashtable.Add(curFolder.ParentID, siblingList); 752 if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling
753 hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list
754 else // else current folder has no known (yet) siblings
755 {
756 List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
757 siblingList.Add(curFolder);
758 // Current folder has no known (yet) siblings
759 hashtable.Add(curFolder.ParentID, siblingList);
760 }
761 } // while more items to read from the database
760 } 762 }
761 } // while more items to read from the database 763 }
762 reader.Close();
763 result.Dispose();
764 764
765 // Set flag so we know we need to build the results from the hash table after 765 // Set flag so we know we need to build the results from the hash table after
766 // we unlock the database 766 // we unlock the database
@@ -781,12 +781,13 @@ namespace OpenSim.Data.MySQL
781 folders.AddRange(hashtable[folders[i].ID]); 781 folders.AddRange(hashtable[folders[i].ID]);
782 } 782 }
783 } // lock (database) 783 } // lock (database)
784
784 return folders; 785 return folders;
785 } 786 }
786 catch (Exception e) 787 catch (Exception e)
787 { 788 {
788 database.Reconnect(); 789 database.Reconnect();
789 m_log.Error(e.ToString()); 790 m_log.Error(e.Message, e);
790 return null; 791 return null;
791 } 792 }
792 } 793 }
@@ -801,19 +802,18 @@ namespace OpenSim.Data.MySQL
801 { 802 {
802 database.CheckConnection(); 803 database.CheckConnection();
803 804
804 MySqlCommand cmd = 805 using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection))
805 new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection);
806 cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
807
808 lock (database)
809 { 806 {
810 cmd.ExecuteNonQuery(); 807 cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
808
809 lock (database)
810 cmd.ExecuteNonQuery();
811 } 811 }
812 } 812 }
813 catch (MySqlException e) 813 catch (MySqlException e)
814 { 814 {
815 database.Reconnect(); 815 database.Reconnect();
816 m_log.Error(e.ToString()); 816 m_log.Error(e.Message, e);
817 } 817 }
818 } 818 }
819 819
@@ -827,13 +827,12 @@ namespace OpenSim.Data.MySQL
827 { 827 {
828 database.CheckConnection(); 828 database.CheckConnection();
829 829
830 MySqlCommand cmd = 830 using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection))
831 new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection);
832 cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
833
834 lock (database)
835 { 831 {
836 cmd.ExecuteNonQuery(); 832 cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
833
834 lock (database)
835 cmd.ExecuteNonQuery();
837 } 836 }
838 } 837 }
839 catch (MySqlException e) 838 catch (MySqlException e)
@@ -865,40 +864,38 @@ namespace OpenSim.Data.MySQL
865 864
866 public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) 865 public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
867 { 866 {
868 MySqlDataReader result = null;
869 MySqlCommand sqlCmd = null;
870 lock (database) 867 lock (database)
871 { 868 {
872 try 869 try
873 { 870 {
874 database.CheckConnection(); 871 database.CheckConnection();
875 sqlCmd = new MySqlCommand(
876 "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
877 database.Connection);
878 sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
879 sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
880 result = sqlCmd.ExecuteReader();
881 872
882 List<InventoryItemBase> list = new List<InventoryItemBase>(); 873 using (MySqlCommand sqlCmd = new MySqlCommand(
883 while (result.Read()) 874 "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
875 database.Connection))
884 { 876 {
885 InventoryItemBase item = readInventoryItem(result); 877 sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
886 if (item != null) 878 sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
887 list.Add(item); 879
880 using (MySqlDataReader result = sqlCmd.ExecuteReader())
881 {
882 List<InventoryItemBase> list = new List<InventoryItemBase>();
883 while (result.Read())
884 {
885 InventoryItemBase item = readInventoryItem(result);
886 if (item != null)
887 list.Add(item);
888 }
889 return list;
890 }
888 } 891 }
889 return list;
890 } 892 }
891 catch (Exception e) 893 catch (Exception e)
892 { 894 {
893 database.Reconnect(); 895 database.Reconnect();
894 m_log.Error(e.ToString()); 896 m_log.Error(e.Message, e);
895 return null; 897 return null;
896 } 898 }
897 finally
898 {
899 if (result != null) result.Close();
900 if (sqlCmd != null) sqlCmd.Dispose();
901 }
902 } 899 }
903 } 900 }
904 } 901 }
diff --git a/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs b/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs
index f25bfd7..fe0914b 100644
--- a/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs
+++ b/OpenSim/Data/MySQL/MySQLLegacyRegionData.cs
@@ -268,6 +268,8 @@ namespace OpenSim.Data.MySQL
268 268
269 public void RemoveObject(UUID obj, UUID regionUUID) 269 public void RemoveObject(UUID obj, UUID regionUUID)
270 { 270 {
271 List<UUID> uuids = new List<UUID>();
272
271 // Formerly, this used to check the region UUID. 273 // Formerly, this used to check the region UUID.
272 // That makes no sense, as we remove the contents of a prim 274 // That makes no sense, as we remove the contents of a prim
273 // unconditionally, but the prim dependent on the region ID. 275 // unconditionally, but the prim dependent on the region ID.
@@ -278,43 +280,31 @@ namespace OpenSim.Data.MySQL
278 // 280 //
279 lock (m_Connection) 281 lock (m_Connection)
280 { 282 {
281 MySqlCommand cmd = m_Connection.CreateCommand(); 283 using (MySqlCommand cmd = m_Connection.CreateCommand())
282
283 cmd.CommandText = "select UUID from prims where "+
284 "SceneGroupID= ?UUID";
285
286 cmd.Parameters.AddWithValue("UUID", obj.ToString());
287
288 List<UUID> uuids = new List<UUID>();
289
290 IDataReader reader = ExecuteReader(cmd);
291
292 try
293 { 284 {
294 while (reader.Read()) 285 cmd.CommandText = "select UUID from prims where SceneGroupID= ?UUID";
286 cmd.Parameters.AddWithValue("UUID", obj.ToString());
287
288 using (IDataReader reader = ExecuteReader(cmd))
295 { 289 {
296 uuids.Add(new UUID(reader["UUID"].ToString())); 290 while (reader.Read())
291 uuids.Add(new UUID(reader["UUID"].ToString()));
297 } 292 }
298 }
299 finally
300 {
301 reader.Close();
302 }
303
304 // delete the main prims
305 cmd.CommandText = "delete from prims where SceneGroupID= ?UUID";
306 ExecuteNonQuery(cmd);
307 cmd.Dispose();
308 293
309 // there is no way this should be < 1 unless there is 294 // delete the main prims
310 // a very corrupt database, but in that case be extra 295 cmd.CommandText = "delete from prims where SceneGroupID= ?UUID";
311 // safe anyway. 296 ExecuteNonQuery(cmd);
312 if (uuids.Count > 0)
313 {
314 RemoveShapes(uuids);
315 RemoveItems(uuids);
316 } 297 }
317 } 298 }
299
300 // there is no way this should be < 1 unless there is
301 // a very corrupt database, but in that case be extra
302 // safe anyway.
303 if (uuids.Count > 0)
304 {
305 RemoveShapes(uuids);
306 RemoveItems(uuids);
307 }
318 } 308 }
319 309
320 /// <summary> 310 /// <summary>
@@ -326,19 +316,16 @@ namespace OpenSim.Data.MySQL
326 { 316 {
327 lock (m_Connection) 317 lock (m_Connection)
328 { 318 {
329 MySqlCommand cmd = m_Connection.CreateCommand(); 319 using (MySqlCommand cmd = m_Connection.CreateCommand())
330 320 {
331 cmd.CommandText = "delete from primitems where " + 321 cmd.CommandText = "delete from primitems where PrimID = ?PrimID";
332 "PrimID = ?PrimID"; 322 cmd.Parameters.AddWithValue("PrimID", uuid.ToString());
333
334 cmd.Parameters.AddWithValue("PrimID", uuid.ToString());
335 323
336 ExecuteNonQuery(cmd); 324 ExecuteNonQuery(cmd);
337 cmd.Dispose(); 325 }
338 } 326 }
339 } 327 }
340 328
341
342 /// <summary> 329 /// <summary>
343 /// Remove all persisted shapes for a list of prims 330 /// Remove all persisted shapes for a list of prims
344 /// The caller must acquire the necessrary synchronization locks 331 /// The caller must acquire the necessrary synchronization locks
@@ -349,28 +336,27 @@ namespace OpenSim.Data.MySQL
349 lock (m_Connection) 336 lock (m_Connection)
350 { 337 {
351 string sql = "delete from primshapes where "; 338 string sql = "delete from primshapes where ";
352 MySqlCommand cmd = m_Connection.CreateCommand(); 339
353 340 using (MySqlCommand cmd = m_Connection.CreateCommand())
354 for (int i = 0; i < uuids.Count; i++)
355 { 341 {
356 if ((i + 1) == uuids.Count) 342 for (int i = 0; i < uuids.Count; i++)
357 {// end of the list
358 sql += "(UUID = ?UUID" + i + ")";
359 }
360 else
361 { 343 {
362 sql += "(UUID = ?UUID" + i + ") or "; 344 if ((i + 1) == uuids.Count)
345 {// end of the list
346 sql += "(UUID = ?UUID" + i + ")";
347 }
348 else
349 {
350 sql += "(UUID = ?UUID" + i + ") or ";
351 }
363 } 352 }
364 } 353 cmd.CommandText = sql;
365 cmd.CommandText = sql;
366 354
367 for (int i = 0; i < uuids.Count; i++) 355 for (int i = 0; i < uuids.Count; i++)
368 { 356 cmd.Parameters.AddWithValue("UUID" + i, uuids[i].ToString());
369 cmd.Parameters.AddWithValue("UUID" + i, uuids[i].ToString());
370 }
371 357
372 ExecuteNonQuery(cmd); 358 ExecuteNonQuery(cmd);
373 cmd.Dispose(); 359 }
374 } 360 }
375 } 361 }
376 362
@@ -384,28 +370,28 @@ namespace OpenSim.Data.MySQL
384 lock (m_Connection) 370 lock (m_Connection)
385 { 371 {
386 string sql = "delete from primitems where "; 372 string sql = "delete from primitems where ";
387 MySqlCommand cmd = m_Connection.CreateCommand(); 373
388 374 using (MySqlCommand cmd = m_Connection.CreateCommand())
389 for (int i = 0; i < uuids.Count; i++)
390 { 375 {
391 if ((i + 1) == uuids.Count) 376 for (int i = 0; i < uuids.Count; i++)
392 {// end of the list
393 sql += "(PrimID = ?PrimID" + i + ")";
394 }
395 else
396 { 377 {
397 sql += "(PrimID = ?PrimID" + i + ") or "; 378 if ((i + 1) == uuids.Count)
379 {
380 // end of the list
381 sql += "(PrimID = ?PrimID" + i + ")";
382 }
383 else
384 {
385 sql += "(PrimID = ?PrimID" + i + ") or ";
386 }
398 } 387 }
399 } 388 cmd.CommandText = sql;
400 cmd.CommandText = sql;
401 389
402 for (int i = 0; i < uuids.Count; i++) 390 for (int i = 0; i < uuids.Count; i++)
403 { 391 cmd.Parameters.AddWithValue("PrimID" + i, uuids[i].ToString());
404 cmd.Parameters.AddWithValue("PrimID" + i, uuids[i].ToString());
405 }
406 392
407 ExecuteNonQuery(cmd); 393 ExecuteNonQuery(cmd);
408 cmd.Dispose(); 394 }
409 } 395 }
410 } 396 }
411 397
@@ -418,77 +404,71 @@ namespace OpenSim.Data.MySQL
418 404
419 lock (m_Connection) 405 lock (m_Connection)
420 { 406 {
421 MySqlCommand cmd = m_Connection.CreateCommand(); 407 using (MySqlCommand cmd = m_Connection.CreateCommand())
422 408 {
423 cmd.CommandText = "select *, " + 409 cmd.CommandText = "select *, " +
424 "case when prims.UUID = SceneGroupID " + 410 "case when prims.UUID = SceneGroupID " +
425 "then 0 else 1 end as sort from prims " + 411 "then 0 else 1 end as sort from prims " +
426 "left join primshapes on prims.UUID = primshapes.UUID "+ 412 "left join primshapes on prims.UUID = primshapes.UUID " +
427 "where RegionUUID = ?RegionUUID " + 413 "where RegionUUID = ?RegionUUID " +
428 "order by SceneGroupID asc, sort asc, LinkNumber asc"; 414 "order by SceneGroupID asc, sort asc, LinkNumber asc";
429
430 cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
431 415
432 IDataReader reader = ExecuteReader(cmd); 416 cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
433 417
434 try 418 using (IDataReader reader = ExecuteReader(cmd))
435 {
436 while (reader.Read())
437 { 419 {
438 SceneObjectPart prim = BuildPrim(reader); 420 while (reader.Read())
439 if (reader["Shape"] is DBNull) 421 {
440 prim.Shape = PrimitiveBaseShape.Default; 422 SceneObjectPart prim = BuildPrim(reader);
441 else 423 if (reader["Shape"] is DBNull)
442 prim.Shape = BuildShape(reader); 424 prim.Shape = PrimitiveBaseShape.Default;
425 else
426 prim.Shape = BuildShape(reader);
443 427
444 prims[prim.UUID] = prim; 428 prims[prim.UUID] = prim;
445 429
446 UUID groupID = new UUID(reader["SceneGroupID"].ToString()); 430 UUID groupID = new UUID(reader["SceneGroupID"].ToString());
447 431
448 if (groupID != lastGroupID) // New SOG 432 if (groupID != lastGroupID) // New SOG
449 {
450 if (grp != null)
451 objects[grp.UUID] = grp;
452
453 lastGroupID = groupID;
454
455 // There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are
456 // recorded as the root prim (for which the UUID must equal the persisted group UUID). In
457 // this case, force the UUID to be the same as the group UUID so that at least these can be
458 // deleted (we need to change the UUID so that any other prims in the linkset can also be
459 // deleted).
460 if (prim.UUID != groupID && groupID != UUID.Zero)
461 { 433 {
462 m_log.WarnFormat( 434 if (grp != null)
463 "[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID", 435 objects[grp.UUID] = grp;
464 prim.Name, prim.UUID, prim.GroupPosition, groupID); 436
465 437 lastGroupID = groupID;
466 prim.UUID = groupID; 438
439 // There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are
440 // recorded as the root prim (for which the UUID must equal the persisted group UUID). In
441 // this case, force the UUID to be the same as the group UUID so that at least these can be
442 // deleted (we need to change the UUID so that any other prims in the linkset can also be
443 // deleted).
444 if (prim.UUID != groupID && groupID != UUID.Zero)
445 {
446 m_log.WarnFormat(
447 "[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID",
448 prim.Name, prim.UUID, prim.GroupPosition, groupID);
449
450 prim.UUID = groupID;
451 }
452
453 grp = new SceneObjectGroup(prim);
467 } 454 }
455 else
456 {
457 // Black magic to preserve link numbers
458 //
459 int link = prim.LinkNum;
468 460
469 grp = new SceneObjectGroup(prim); 461 grp.AddPart(prim);
470 }
471 else
472 {
473 // Black magic to preserve link numbers
474 //
475 int link = prim.LinkNum;
476
477 grp.AddPart(prim);
478 462
479 if (link != 0) 463 if (link != 0)
480 prim.LinkNum = link; 464 prim.LinkNum = link;
465 }
481 } 466 }
482 } 467 }
483 }
484 finally
485 {
486 reader.Close();
487 }
488 468
489 if (grp != null) 469 if (grp != null)
490 objects[grp.UUID] = grp; 470 objects[grp.UUID] = grp;
491 cmd.Dispose(); 471 }
492 } 472 }
493 473
494 // Instead of attempting to LoadItems on every prim, 474 // Instead of attempting to LoadItems on every prim,
@@ -498,34 +478,29 @@ namespace OpenSim.Data.MySQL
498 List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>(); 478 List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>();
499 lock (m_Connection) 479 lock (m_Connection)
500 { 480 {
501 MySqlCommand itemCmd = m_Connection.CreateCommand(); 481 using (MySqlCommand itemCmd = m_Connection.CreateCommand())
502 itemCmd.CommandText = "select distinct primID from primitems";
503 IDataReader itemReader = ExecuteReader(itemCmd);
504 try
505 { 482 {
506 while (itemReader.Read()) 483 itemCmd.CommandText = "select distinct primID from primitems";
484 using (IDataReader itemReader = ExecuteReader(itemCmd))
507 { 485 {
508 if (!(itemReader["primID"] is DBNull)) 486 while (itemReader.Read())
509 { 487 {
510 UUID primID = new UUID(itemReader["primID"].ToString()); 488 if (!(itemReader["primID"] is DBNull))
511 if (prims.ContainsKey(primID))
512 { 489 {
513 primsWithInventory.Add(prims[primID]); 490 UUID primID = new UUID(itemReader["primID"].ToString());
491 if (prims.ContainsKey(primID))
492 {
493 primsWithInventory.Add(prims[primID]);
494 }
514 } 495 }
515 } 496 }
516 } 497 }
517 } 498 }
518 finally
519 {
520 itemReader.Close();
521 }
522 itemCmd.Dispose();
523 } 499 }
524 500
525 foreach (SceneObjectPart prim in primsWithInventory) 501 foreach (SceneObjectPart prim in primsWithInventory)
526 {
527 LoadItems(prim); 502 LoadItems(prim);
528 } 503
529 m_log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count); 504 m_log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count);
530 return new List<SceneObjectGroup>(objects.Values); 505 return new List<SceneObjectGroup>(objects.Values);
531 } 506 }
@@ -538,34 +513,25 @@ namespace OpenSim.Data.MySQL
538 { 513 {
539 lock (m_Connection) 514 lock (m_Connection)
540 { 515 {
541 MySqlCommand cmd = m_Connection.CreateCommand(); 516 List<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
542
543 cmd.CommandText = "select * from primitems where "+
544 "PrimID = ?PrimID";
545 517
546 cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString()); 518 using (MySqlCommand cmd = m_Connection.CreateCommand())
547
548 IDataReader reader = ExecuteReader(cmd);
549 List<TaskInventoryItem> inventory =
550 new List<TaskInventoryItem>();
551
552 try
553 { 519 {
554 while (reader.Read()) 520 cmd.CommandText = "select * from primitems where PrimID = ?PrimID";
521 cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString());
522
523 using (IDataReader reader = ExecuteReader(cmd))
555 { 524 {
556 TaskInventoryItem item = BuildItem(reader); 525 while (reader.Read())
526 {
527 TaskInventoryItem item = BuildItem(reader);
557 528
558 item.ParentID = prim.UUID; // Values in database are 529 item.ParentID = prim.UUID; // Values in database are often wrong
559 // often wrong 530 inventory.Add(item);
560 inventory.Add(item); 531 }
561 } 532 }
562 } 533 }
563 finally
564 {
565 reader.Close();
566 }
567 534
568 cmd.Dispose();
569 prim.Inventory.RestoreInventoryItems(inventory); 535 prim.Inventory.RestoreInventoryItems(inventory);
570 } 536 }
571 } 537 }
@@ -576,23 +542,21 @@ namespace OpenSim.Data.MySQL
576 542
577 lock (m_Connection) 543 lock (m_Connection)
578 { 544 {
579 MySqlCommand cmd = m_Connection.CreateCommand(); 545 using (MySqlCommand cmd = m_Connection.CreateCommand())
546 {
547 cmd.CommandText = "delete from terrain where RegionUUID = ?RegionUUID";
548 cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
580 549
581 cmd.CommandText = "delete from terrain where " + 550 ExecuteNonQuery(cmd);
582 "RegionUUID = ?RegionUUID";
583 cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
584 551
585 ExecuteNonQuery(cmd); 552 cmd.CommandText = "insert into terrain (RegionUUID, " +
586
587 cmd.CommandText = "insert into terrain (RegionUUID, " +
588 "Revision, Heightfield) values (?RegionUUID, " + 553 "Revision, Heightfield) values (?RegionUUID, " +
589 "1, ?Heightfield)"; 554 "1, ?Heightfield)";
590 555
591 cmd.Parameters.AddWithValue("Heightfield", 556 cmd.Parameters.AddWithValue("Heightfield", SerializeTerrain(ter));
592 SerializeTerrain(ter)); 557
593 558 ExecuteNonQuery(cmd);
594 ExecuteNonQuery(cmd); 559 }
595 cmd.Dispose();
596 } 560 }
597 } 561 }
598 562
@@ -602,42 +566,40 @@ namespace OpenSim.Data.MySQL
602 566
603 lock (m_Connection) 567 lock (m_Connection)
604 { 568 {
605 MySqlCommand cmd = m_Connection.CreateCommand(); 569 using (MySqlCommand cmd = m_Connection.CreateCommand())
606 cmd.CommandText = "select RegionUUID, Revision, Heightfield " + 570 {
607 "from terrain where RegionUUID = ?RegionUUID "+ 571 cmd.CommandText = "select RegionUUID, Revision, Heightfield " +
572 "from terrain where RegionUUID = ?RegionUUID " +
608 "order by Revision desc limit 1"; 573 "order by Revision desc limit 1";
609 cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString()); 574 cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
610
611 IDataReader reader = ExecuteReader(cmd);
612 575
613 try 576 using (IDataReader reader = ExecuteReader(cmd))
614 {
615 while (reader.Read())
616 { 577 {
617 terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; 578 while (reader.Read())
618 terrain.Initialize(); 579 {
580 int rev = Convert.ToInt32(reader["Revision"]);
619 581
620 MemoryStream mstr = new MemoryStream((byte[]) reader["Heightfield"]); 582 terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize];
621 int rev = 0; 583 terrain.Initialize();
622 584
623 BinaryReader br = new BinaryReader(mstr); 585 using (MemoryStream mstr = new MemoryStream((byte[])reader["Heightfield"]))
624 for (int x = 0; x < (int)Constants.RegionSize; x++)
625 {
626 for (int y = 0; y < (int)Constants.RegionSize; y++)
627 { 586 {
628 terrain[x, y] = br.ReadDouble(); 587 using (BinaryReader br = new BinaryReader(mstr))
588 {
589 for (int x = 0; x < (int)Constants.RegionSize; x++)
590 {
591 for (int y = 0; y < (int)Constants.RegionSize; y++)
592 {
593 terrain[x, y] = br.ReadDouble();
594 }
595 }
596 }
597
598 m_log.InfoFormat("[REGION DB]: Loaded terrain revision r{0}", rev);
629 } 599 }
630 rev = Convert.ToInt32(reader["Revision"]);
631 } 600 }
632 m_log.InfoFormat("[REGION DB]: Loaded terrain " +
633 "revision r{0}", rev);
634 } 601 }
635 } 602 }
636 finally
637 {
638 reader.Close();
639 }
640 cmd.Dispose();
641 } 603 }
642 604
643 return terrain; 605 return terrain;
@@ -647,14 +609,13 @@ namespace OpenSim.Data.MySQL
647 { 609 {
648 lock (m_Connection) 610 lock (m_Connection)
649 { 611 {
650 MySqlCommand cmd = m_Connection.CreateCommand(); 612 using (MySqlCommand cmd = m_Connection.CreateCommand())
651 613 {
652 cmd.CommandText = "delete from land where UUID = ?UUID"; 614 cmd.CommandText = "delete from land where UUID = ?UUID";
653 615 cmd.Parameters.AddWithValue("UUID", globalID.ToString());
654 cmd.Parameters.AddWithValue("UUID", globalID.ToString());
655 616
656 ExecuteNonQuery(cmd); 617 ExecuteNonQuery(cmd);
657 cmd.Dispose(); 618 }
658 } 619 }
659 } 620 }
660 621
@@ -662,9 +623,9 @@ namespace OpenSim.Data.MySQL
662 { 623 {
663 lock (m_Connection) 624 lock (m_Connection)
664 { 625 {
665 MySqlCommand cmd = m_Connection.CreateCommand(); 626 using (MySqlCommand cmd = m_Connection.CreateCommand())
666 627 {
667 cmd.CommandText = "replace into land (UUID, RegionUUID, " + 628 cmd.CommandText = "replace into land (UUID, RegionUUID, " +
668 "LocalLandID, Bitmap, Name, Description, " + 629 "LocalLandID, Bitmap, Name, Description, " +
669 "OwnerUUID, IsGroupOwned, Area, AuctionID, " + 630 "OwnerUUID, IsGroupOwned, Area, AuctionID, " +
670 "Category, ClaimDate, ClaimPrice, GroupUUID, " + 631 "Category, ClaimDate, ClaimPrice, GroupUUID, " +
@@ -685,28 +646,26 @@ namespace OpenSim.Data.MySQL
685 "?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " + 646 "?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " +
686 "?AuthbuyerID, ?OtherCleanTime, ?Dwell)"; 647 "?AuthbuyerID, ?OtherCleanTime, ?Dwell)";
687 648
688 FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID); 649 FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID);
689 650
690 ExecuteNonQuery(cmd); 651 ExecuteNonQuery(cmd);
691
692 cmd.CommandText = "delete from landaccesslist where " +
693 "LandUUID = ?UUID";
694
695 ExecuteNonQuery(cmd);
696 652
697 cmd.Parameters.Clear(); 653 cmd.CommandText = "delete from landaccesslist where LandUUID = ?UUID";
698 cmd.CommandText = "insert into landaccesslist (LandUUID, " +
699 "AccessUUID, Flags) values (?LandUUID, ?AccessUUID, " +
700 "?Flags)";
701 654
702 foreach (ParcelManager.ParcelAccessEntry entry in
703 parcel.LandData.ParcelAccessList)
704 {
705 FillLandAccessCommand(cmd, entry, parcel.LandData.GlobalID);
706 ExecuteNonQuery(cmd); 655 ExecuteNonQuery(cmd);
656
707 cmd.Parameters.Clear(); 657 cmd.Parameters.Clear();
658 cmd.CommandText = "insert into landaccesslist (LandUUID, " +
659 "AccessUUID, Flags) values (?LandUUID, ?AccessUUID, " +
660 "?Flags)";
661
662 foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList)
663 {
664 FillLandAccessCommand(cmd, entry, parcel.LandData.GlobalID);
665 ExecuteNonQuery(cmd);
666 cmd.Parameters.Clear();
667 }
708 } 668 }
709 cmd.Dispose();
710 } 669 }
711 } 670 }
712 671
@@ -716,35 +675,28 @@ namespace OpenSim.Data.MySQL
716 675
717 lock (m_Connection) 676 lock (m_Connection)
718 { 677 {
719 MySqlCommand cmd = m_Connection.CreateCommand(); 678 using (MySqlCommand cmd = m_Connection.CreateCommand())
720
721 cmd.CommandText = "select * from regionsettings where " +
722 "regionUUID = ?RegionUUID";
723 cmd.Parameters.AddWithValue("regionUUID", regionUUID);
724
725 IDataReader reader = ExecuteReader(cmd);
726
727 try
728 { 679 {
729 if (reader.Read()) 680 cmd.CommandText = "select * from regionsettings where regionUUID = ?RegionUUID";
730 { 681 cmd.Parameters.AddWithValue("regionUUID", regionUUID);
731 rs = BuildRegionSettings(reader); 682
732 rs.OnSave += StoreRegionSettings; 683 using (IDataReader reader = ExecuteReader(cmd))
733 }
734 else
735 { 684 {
736 rs = new RegionSettings(); 685 if (reader.Read())
737 rs.RegionUUID = regionUUID; 686 {
738 rs.OnSave += StoreRegionSettings; 687 rs = BuildRegionSettings(reader);
688 rs.OnSave += StoreRegionSettings;
689 }
690 else
691 {
692 rs = new RegionSettings();
693 rs.RegionUUID = regionUUID;
694 rs.OnSave += StoreRegionSettings;
739 695
740 StoreRegionSettings(rs); 696 StoreRegionSettings(rs);
697 }
741 } 698 }
742 } 699 }
743 finally
744 {
745 reader.Close();
746 }
747 cmd.Dispose();
748 } 700 }
749 701
750 return rs; 702 return rs;
@@ -754,9 +706,9 @@ namespace OpenSim.Data.MySQL
754 { 706 {
755 lock (m_Connection) 707 lock (m_Connection)
756 { 708 {
757 MySqlCommand cmd = m_Connection.CreateCommand(); 709 using (MySqlCommand cmd = m_Connection.CreateCommand())
758 710 {
759 cmd.CommandText = "replace into regionsettings (regionUUID, " + 711 cmd.CommandText = "replace into regionsettings (regionUUID, " +
760 "block_terraform, block_fly, allow_damage, " + 712 "block_terraform, block_fly, allow_damage, " +
761 "restrict_pushing, allow_land_resell, " + 713 "restrict_pushing, allow_land_resell, " +
762 "allow_land_join_divide, block_show_in_search, " + 714 "allow_land_join_divide, block_show_in_search, " +
@@ -766,8 +718,8 @@ namespace OpenSim.Data.MySQL
766 "terrain_texture_2, terrain_texture_3, " + 718 "terrain_texture_2, terrain_texture_3, " +
767 "terrain_texture_4, elevation_1_nw, " + 719 "terrain_texture_4, elevation_1_nw, " +
768 "elevation_2_nw, elevation_1_ne, " + 720 "elevation_2_nw, elevation_1_ne, " +
769 "elevation_2_ne, elevation_1_se, "+ 721 "elevation_2_ne, elevation_1_se, " +
770 "elevation_2_se, elevation_1_sw, "+ 722 "elevation_2_se, elevation_1_sw, " +
771 "elevation_2_sw, water_height, " + 723 "elevation_2_sw, water_height, " +
772 "terrain_raise_limit, terrain_lower_limit, " + 724 "terrain_raise_limit, terrain_lower_limit, " +
773 "use_estate_sun, fixed_sun, sun_position, " + 725 "use_estate_sun, fixed_sun, sun_position, " +
@@ -789,11 +741,10 @@ namespace OpenSim.Data.MySQL
789 "?SunVectorX, ?SunVectorY, ?SunVectorZ, " + 741 "?SunVectorX, ?SunVectorY, ?SunVectorZ, " +
790 "?LoadedCreationDateTime, ?LoadedCreationID)"; 742 "?LoadedCreationDateTime, ?LoadedCreationID)";
791 743
792 FillRegionSettingsCommand(cmd, rs); 744 FillRegionSettingsCommand(cmd, rs);
793
794 ExecuteNonQuery(cmd);
795 cmd.Dispose();
796 745
746 ExecuteNonQuery(cmd);
747 }
797 } 748 }
798 } 749 }
799 750
@@ -803,52 +754,38 @@ namespace OpenSim.Data.MySQL
803 754
804 lock (m_Connection) 755 lock (m_Connection)
805 { 756 {
806 MySqlCommand cmd = m_Connection.CreateCommand(); 757 using (MySqlCommand cmd = m_Connection.CreateCommand())
807
808 cmd.CommandText = "select * from land where " +
809 "RegionUUID = ?RegionUUID";
810
811 cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
812
813 IDataReader reader = ExecuteReader(cmd);
814
815 try
816 { 758 {
817 while (reader.Read()) 759 cmd.CommandText = "select * from land where RegionUUID = ?RegionUUID";
760 cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
761
762 using (IDataReader reader = ExecuteReader(cmd))
818 { 763 {
819 LandData newLand = BuildLandData(reader); 764 while (reader.Read())
820 landData.Add(newLand); 765 {
766 LandData newLand = BuildLandData(reader);
767 landData.Add(newLand);
768 }
821 } 769 }
822 } 770 }
823 finally
824 {
825 reader.Close();
826 }
827 771
828 foreach (LandData land in landData) 772 using (MySqlCommand cmd = m_Connection.CreateCommand())
829 { 773 {
830 cmd.Parameters.Clear(); 774 foreach (LandData land in landData)
831
832 cmd.CommandText = "select * from landaccesslist " +
833 "where LandUUID = ?LandUUID";
834
835 cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString());
836
837 reader = ExecuteReader(cmd);
838
839 try
840 { 775 {
841 while (reader.Read()) 776 cmd.Parameters.Clear();
777 cmd.CommandText = "select * from landaccesslist where LandUUID = ?LandUUID";
778 cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString());
779
780 using (IDataReader reader = ExecuteReader(cmd))
842 { 781 {
843 land.ParcelAccessList.Add(BuildLandAccessData(reader)); 782 while (reader.Read())
783 {
784 land.ParcelAccessList.Add(BuildLandAccessData(reader));
785 }
844 } 786 }
845 } 787 }
846 finally
847 {
848 reader.Close();
849 }
850 } 788 }
851 cmd.Dispose();
852 } 789 }
853 790
854 return landData; 791 return landData;
diff --git a/OpenSim/Data/MySQL/MySQLManager.cs b/OpenSim/Data/MySQL/MySQLManager.cs
index a6cce57..a724a50 100644
--- a/OpenSim/Data/MySQL/MySQLManager.cs
+++ b/OpenSim/Data/MySQL/MySQLManager.cs
@@ -134,18 +134,16 @@ namespace OpenSim.Data.MySQL
134 /// </summary> 134 /// </summary>
135 protected void GetWaitTimeout() 135 protected void GetWaitTimeout()
136 { 136 {
137 MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon); 137 using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon))
138
139 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
140 { 138 {
141 if (dbReader.Read()) 139 using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
142 { 140 {
143 m_waitTimeout 141 if (dbReader.Read())
144 = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; 142 {
143 m_waitTimeout
144 = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
145 }
145 } 146 }
146
147 dbReader.Close();
148 cmd.Dispose();
149 } 147 }
150 148
151 m_lastConnectionUse = DateTime.Now.Ticks; 149 m_lastConnectionUse = DateTime.Now.Ticks;
@@ -303,31 +301,31 @@ namespace OpenSim.Data.MySQL
303 { 301 {
304 CheckConnection(); 302 CheckConnection();
305 303
306 MySqlCommand tablesCmd = 304 using (MySqlCommand tablesCmd = new MySqlCommand(
307 new MySqlCommand( 305 "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
308 "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname", 306 dbcon))
309 dbcon);
310 tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
311
312 using (MySqlDataReader tables = tablesCmd.ExecuteReader())
313 { 307 {
314 while (tables.Read()) 308 tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
309
310 using (MySqlDataReader tables = tablesCmd.ExecuteReader())
315 { 311 {
316 try 312 while (tables.Read())
317 { 313 {
318 string tableName = (string) tables["TABLE_NAME"]; 314 try
319 string comment = (string) tables["TABLE_COMMENT"];
320 if (tableList.ContainsKey(tableName))
321 { 315 {
322 tableList[tableName] = comment; 316 string tableName = (string)tables["TABLE_NAME"];
317 string comment = (string)tables["TABLE_COMMENT"];
318 if (tableList.ContainsKey(tableName))
319 {
320 tableList[tableName] = comment;
321 }
322 }
323 catch (Exception e)
324 {
325 m_log.Error(e.Message, e);
323 } 326 }
324 }
325 catch (Exception e)
326 {
327 m_log.Error(e.ToString());
328 } 327 }
329 } 328 }
330 tables.Close();
331 } 329 }
332 } 330 }
333 } 331 }
@@ -346,19 +344,19 @@ namespace OpenSim.Data.MySQL
346 { 344 {
347 CheckConnection(); // Not sure if this one is necessary 345 CheckConnection(); // Not sure if this one is necessary
348 346
349 MySqlCommand dbcommand = (MySqlCommand) dbcon.CreateCommand(); 347 MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
350 dbcommand.CommandText = sql; 348 dbcommand.CommandText = sql;
351 foreach (KeyValuePair<string, object> param in parameters) 349 foreach (KeyValuePair<string, object> param in parameters)
352 { 350 {
353 dbcommand.Parameters.AddWithValue(param.Key, param.Value); 351 dbcommand.Parameters.AddWithValue(param.Key, param.Value);
354 } 352 }
355 353
356 return (IDbCommand) dbcommand; 354 return (IDbCommand)dbcommand;
357 } 355 }
358 catch (Exception e) 356 catch (Exception e)
359 { 357 {
360 // Return null if it fails. 358 // Return null if it fails.
361 m_log.Error("Failed during Query generation: " + e.ToString()); 359 m_log.Error("Failed during Query generation: " + e.Message, e);
362 return null; 360 return null;
363 } 361 }
364 } 362 }
@@ -694,8 +692,6 @@ namespace OpenSim.Data.MySQL
694 ret.Add(attachpoint, item); 692 ret.Add(attachpoint, item);
695 } 693 }
696 694
697 r.Close();
698
699 return ret; 695 return ret;
700 } 696 }
701 697
diff --git a/OpenSim/Data/MySQL/MySQLRegionData.cs b/OpenSim/Data/MySQL/MySQLRegionData.cs
index 06ef624..04b24b6 100644
--- a/OpenSim/Data/MySQL/MySQLRegionData.cs
+++ b/OpenSim/Data/MySQL/MySQLRegionData.cs
@@ -56,12 +56,13 @@ namespace OpenSim.Data.MySQL
56 if (scopeID != UUID.Zero) 56 if (scopeID != UUID.Zero)
57 command += " and ScopeID = ?scopeID"; 57 command += " and ScopeID = ?scopeID";
58 58
59 MySqlCommand cmd = new MySqlCommand(command); 59 using (MySqlCommand cmd = new MySqlCommand(command))
60 60 {
61 cmd.Parameters.AddWithValue("?regionName", regionName); 61 cmd.Parameters.AddWithValue("?regionName", regionName);
62 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); 62 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
63 63
64 return RunCommand(cmd); 64 return RunCommand(cmd);
65 }
65 } 66 }
66 67
67 public RegionData Get(int posX, int posY, UUID scopeID) 68 public RegionData Get(int posX, int posY, UUID scopeID)
@@ -70,17 +71,18 @@ namespace OpenSim.Data.MySQL
70 if (scopeID != UUID.Zero) 71 if (scopeID != UUID.Zero)
71 command += " and ScopeID = ?scopeID"; 72 command += " and ScopeID = ?scopeID";
72 73
73 MySqlCommand cmd = new MySqlCommand(command); 74 using (MySqlCommand cmd = new MySqlCommand(command))
74 75 {
75 cmd.Parameters.AddWithValue("?posX", posX.ToString()); 76 cmd.Parameters.AddWithValue("?posX", posX.ToString());
76 cmd.Parameters.AddWithValue("?posY", posY.ToString()); 77 cmd.Parameters.AddWithValue("?posY", posY.ToString());
77 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); 78 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
78 79
79 List<RegionData> ret = RunCommand(cmd); 80 List<RegionData> ret = RunCommand(cmd);
80 if (ret.Count == 0) 81 if (ret.Count == 0)
81 return null; 82 return null;
82 83
83 return ret[0]; 84 return ret[0];
85 }
84 } 86 }
85 87
86 public RegionData Get(UUID regionID, UUID scopeID) 88 public RegionData Get(UUID regionID, UUID scopeID)
@@ -89,16 +91,17 @@ namespace OpenSim.Data.MySQL
89 if (scopeID != UUID.Zero) 91 if (scopeID != UUID.Zero)
90 command += " and ScopeID = ?scopeID"; 92 command += " and ScopeID = ?scopeID";
91 93
92 MySqlCommand cmd = new MySqlCommand(command); 94 using (MySqlCommand cmd = new MySqlCommand(command))
93 95 {
94 cmd.Parameters.AddWithValue("?regionID", regionID.ToString()); 96 cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
95 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); 97 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
96 98
97 List<RegionData> ret = RunCommand(cmd); 99 List<RegionData> ret = RunCommand(cmd);
98 if (ret.Count == 0) 100 if (ret.Count == 0)
99 return null; 101 return null;
100 102
101 return ret[0]; 103 return ret[0];
104 }
102 } 105 }
103 106
104 public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) 107 public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
@@ -107,71 +110,70 @@ namespace OpenSim.Data.MySQL
107 if (scopeID != UUID.Zero) 110 if (scopeID != UUID.Zero)
108 command += " and ScopeID = ?scopeID"; 111 command += " and ScopeID = ?scopeID";
109 112
110 MySqlCommand cmd = new MySqlCommand(command); 113 using (MySqlCommand cmd = new MySqlCommand(command))
111 114 {
112 cmd.Parameters.AddWithValue("?startX", startX.ToString()); 115 cmd.Parameters.AddWithValue("?startX", startX.ToString());
113 cmd.Parameters.AddWithValue("?startY", startY.ToString()); 116 cmd.Parameters.AddWithValue("?startY", startY.ToString());
114 cmd.Parameters.AddWithValue("?endX", endX.ToString()); 117 cmd.Parameters.AddWithValue("?endX", endX.ToString());
115 cmd.Parameters.AddWithValue("?endY", endY.ToString()); 118 cmd.Parameters.AddWithValue("?endY", endY.ToString());
116 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); 119 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
117 120
118 return RunCommand(cmd); 121 return RunCommand(cmd);
122 }
119 } 123 }
120 124
121 public List<RegionData> RunCommand(MySqlCommand cmd) 125 public List<RegionData> RunCommand(MySqlCommand cmd)
122 { 126 {
123 List<RegionData> retList = new List<RegionData>(); 127 List<RegionData> retList = new List<RegionData>();
124 128
125 IDataReader result = ExecuteReader(cmd); 129 using (IDataReader result = ExecuteReader(cmd))
126
127 while (result.Read())
128 { 130 {
129 RegionData ret = new RegionData(); 131 while (result.Read())
130 ret.Data = new Dictionary<string, object>();
131
132 UUID regionID;
133 UUID.TryParse(result["uuid"].ToString(), out regionID);
134 ret.RegionID = regionID;
135 UUID scope;
136 UUID.TryParse(result["ScopeID"].ToString(), out scope);
137 ret.ScopeID = scope;
138 ret.RegionName = result["regionName"].ToString();
139 ret.posX = Convert.ToInt32(result["locX"]);
140 ret.posY = Convert.ToInt32(result["locY"]);
141 ret.sizeX = Convert.ToInt32(result["sizeX"]);
142 ret.sizeY = Convert.ToInt32(result["sizeY"]);
143
144 if (m_ColumnNames == null)
145 { 132 {
146 m_ColumnNames = new List<string>(); 133 RegionData ret = new RegionData();
147 134 ret.Data = new Dictionary<string, object>();
148 DataTable schemaTable = result.GetSchemaTable(); 135
149 foreach (DataRow row in schemaTable.Rows) 136 UUID regionID;
150 m_ColumnNames.Add(row["ColumnName"].ToString()); 137 UUID.TryParse(result["uuid"].ToString(), out regionID);
138 ret.RegionID = regionID;
139 UUID scope;
140 UUID.TryParse(result["ScopeID"].ToString(), out scope);
141 ret.ScopeID = scope;
142 ret.RegionName = result["regionName"].ToString();
143 ret.posX = Convert.ToInt32(result["locX"]);
144 ret.posY = Convert.ToInt32(result["locY"]);
145 ret.sizeX = Convert.ToInt32(result["sizeX"]);
146 ret.sizeY = Convert.ToInt32(result["sizeY"]);
147
148 if (m_ColumnNames == null)
149 {
150 m_ColumnNames = new List<string>();
151
152 DataTable schemaTable = result.GetSchemaTable();
153 foreach (DataRow row in schemaTable.Rows)
154 m_ColumnNames.Add(row["ColumnName"].ToString());
155 }
156
157 foreach (string s in m_ColumnNames)
158 {
159 if (s == "uuid")
160 continue;
161 if (s == "ScopeID")
162 continue;
163 if (s == "regionName")
164 continue;
165 if (s == "locX")
166 continue;
167 if (s == "locY")
168 continue;
169
170 ret.Data[s] = result[s].ToString();
171 }
172
173 retList.Add(ret);
151 } 174 }
152
153 foreach (string s in m_ColumnNames)
154 {
155 if (s == "uuid")
156 continue;
157 if (s == "ScopeID")
158 continue;
159 if (s == "regionName")
160 continue;
161 if (s == "locX")
162 continue;
163 if (s == "locY")
164 continue;
165
166 ret.Data[s] = result[s].ToString();
167 }
168
169 retList.Add(ret);
170 } 175 }
171 176
172 result.Close();
173 CloseReaderCommand(cmd);
174
175 return retList; 177 return retList;
176 } 178 }
177 179
@@ -198,76 +200,72 @@ namespace OpenSim.Data.MySQL
198 200
199 string[] fields = new List<string>(data.Data.Keys).ToArray(); 201 string[] fields = new List<string>(data.Data.Keys).ToArray();
200 202
201 MySqlCommand cmd = new MySqlCommand(); 203 using (MySqlCommand cmd = new MySqlCommand())
202
203 string update = "update `"+m_Realm+"` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
204 foreach (string field in fields)
205 { 204 {
206 update += ", "; 205 string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
207 update += "`" + field + "` = ?"+field; 206 foreach (string field in fields)
208 207 {
209 cmd.Parameters.AddWithValue("?"+field, data.Data[field]); 208 update += ", ";
210 } 209 update += "`" + field + "` = ?" + field;
211
212 update += " where uuid = ?regionID";
213 210
214 if (data.ScopeID != UUID.Zero) 211 cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
215 update += " and ScopeID = ?scopeID"; 212 }
216 213
217 cmd.CommandText = update; 214 update += " where uuid = ?regionID";
218 cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
219 cmd.Parameters.AddWithValue("?regionName", data.RegionName);
220 cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
221 cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
222 cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
223 cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString());
224 cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString());
225 215
226 if (ExecuteNonQuery(cmd) < 1) 216 if (data.ScopeID != UUID.Zero)
227 { 217 update += " and ScopeID = ?scopeID";
228 string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" +
229 String.Join("`, `", fields) +
230 "`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")";
231 218
232 cmd.CommandText = insert; 219 cmd.CommandText = update;
220 cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
221 cmd.Parameters.AddWithValue("?regionName", data.RegionName);
222 cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
223 cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
224 cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
225 cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString());
226 cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString());
233 227
234 if (ExecuteNonQuery(cmd) < 1) 228 if (ExecuteNonQuery(cmd) < 1)
235 { 229 {
236 cmd.Dispose(); 230 string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" +
237 return false; 231 String.Join("`, `", fields) +
232 "`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")";
233
234 cmd.CommandText = insert;
235
236 if (ExecuteNonQuery(cmd) < 1)
237 {
238 return false;
239 }
238 } 240 }
239 } 241 }
240 242
241 cmd.Dispose();
242
243 return true; 243 return true;
244 } 244 }
245 245
246 public bool SetDataItem(UUID regionID, string item, string value) 246 public bool SetDataItem(UUID regionID, string item, string value)
247 { 247 {
248 MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + 248 using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID"))
249 "` set `" + item + "` = ?" + item + " where uuid = ?UUID"); 249 {
250 250 cmd.Parameters.AddWithValue("?" + item, value);
251 251 cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
252 cmd.Parameters.AddWithValue("?"+item, value);
253 cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
254 252
255 if (ExecuteNonQuery(cmd) > 0) 253 if (ExecuteNonQuery(cmd) > 0)
256 return true; 254 return true;
255 }
257 256
258 return false; 257 return false;
259 } 258 }
260 259
261 public bool Delete(UUID regionID) 260 public bool Delete(UUID regionID)
262 { 261 {
263 MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + 262 using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID"))
264 "` where uuid = ?UUID"); 263 {
265 264 cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
266
267 cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
268 265
269 if (ExecuteNonQuery(cmd) > 0) 266 if (ExecuteNonQuery(cmd) > 0)
270 return true; 267 return true;
268 }
271 269
272 return false; 270 return false;
273 } 271 }
diff --git a/OpenSim/Data/MySQL/MySQLUserAccountData.cs b/OpenSim/Data/MySQL/MySQLUserAccountData.cs
index d48144d..c713a11 100644
--- a/OpenSim/Data/MySQL/MySQLUserAccountData.cs
+++ b/OpenSim/Data/MySQL/MySQLUserAccountData.cs
@@ -64,48 +64,44 @@ namespace OpenSim.Data.MySQL
64 if (scopeID != UUID.Zero) 64 if (scopeID != UUID.Zero)
65 command += " and ScopeID = ?scopeID"; 65 command += " and ScopeID = ?scopeID";
66 66
67 MySqlCommand cmd = new MySqlCommand(command); 67 using (MySqlCommand cmd = new MySqlCommand(command))
68
69 cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
70 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
71
72 IDataReader result = ExecuteReader(cmd);
73
74 if (result.Read())
75 { 68 {
76 ret.PrincipalID = principalID; 69 cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
77 UUID scope; 70 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
78 UUID.TryParse(result["ScopeID"].ToString(), out scope);
79 ret.ScopeID = scope;
80 71
81 if (m_ColumnNames == null) 72 using (IDataReader result = ExecuteReader(cmd))
82 { 73 {
83 m_ColumnNames = new List<string>(); 74 if (result.Read())
84 75 {
85 DataTable schemaTable = result.GetSchemaTable(); 76 ret.PrincipalID = principalID;
86 foreach (DataRow row in schemaTable.Rows) 77 UUID scope;
87 m_ColumnNames.Add(row["ColumnName"].ToString()); 78 UUID.TryParse(result["ScopeID"].ToString(), out scope);
79 ret.ScopeID = scope;
80
81 if (m_ColumnNames == null)
82 {
83 m_ColumnNames = new List<string>();
84
85 DataTable schemaTable = result.GetSchemaTable();
86 foreach (DataRow row in schemaTable.Rows)
87 m_ColumnNames.Add(row["ColumnName"].ToString());
88 }
89
90 foreach (string s in m_ColumnNames)
91 {
92 if (s == "UUID")
93 continue;
94 if (s == "ScopeID")
95 continue;
96
97 ret.Data[s] = result[s].ToString();
98 }
99
100 return ret;
101 }
88 } 102 }
89
90 foreach (string s in m_ColumnNames)
91 {
92 if (s == "UUID")
93 continue;
94 if (s == "ScopeID")
95 continue;
96
97 ret.Data[s] = result[s].ToString();
98 }
99
100 result.Close();
101 CloseReaderCommand(cmd);
102
103 return ret;
104 } 103 }
105 104
106 result.Close();
107 CloseReaderCommand(cmd);
108
109 return null; 105 return null;
110 } 106 }
111 107
@@ -118,61 +114,60 @@ namespace OpenSim.Data.MySQL
118 114
119 string[] fields = new List<string>(data.Data.Keys).ToArray(); 115 string[] fields = new List<string>(data.Data.Keys).ToArray();
120 116
121 MySqlCommand cmd = new MySqlCommand(); 117 using (MySqlCommand cmd = new MySqlCommand())
122
123 string update = "update `"+m_Realm+"` set ";
124 bool first = true;
125 foreach (string field in fields)
126 { 118 {
127 if (!first) 119 string update = "update `" + m_Realm + "` set ";
128 update += ", "; 120 bool first = true;
129 update += "`" + field + "` = ?"+field; 121 foreach (string field in fields)
130 122 {
131 first = false; 123 if (!first)
132 124 update += ", ";
133 cmd.Parameters.AddWithValue("?"+field, data.Data[field]); 125 update += "`" + field + "` = ?" + field;
134 }
135 126
136 update += " where UUID = ?principalID"; 127 first = false;
137 128
138 if (data.ScopeID != UUID.Zero) 129 cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
139 update += " and ScopeID = ?scopeID"; 130 }
140 131
141 cmd.CommandText = update; 132 update += " where UUID = ?principalID";
142 cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
143 cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
144 133
145 if (ExecuteNonQuery(cmd) < 1) 134 if (data.ScopeID != UUID.Zero)
146 { 135 update += " and ScopeID = ?scopeID";
147 string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
148 String.Join("`, `", fields) +
149 "`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";
150 136
151 cmd.CommandText = insert; 137 cmd.CommandText = update;
138 cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
139 cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
152 140
153 if (ExecuteNonQuery(cmd) < 1) 141 if (ExecuteNonQuery(cmd) < 1)
154 { 142 {
155 cmd.Dispose(); 143 string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
156 return false; 144 String.Join("`, `", fields) +
145 "`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";
146
147 cmd.CommandText = insert;
148
149 if (ExecuteNonQuery(cmd) < 1)
150 {
151 cmd.Dispose();
152 return false;
153 }
157 } 154 }
158 } 155 }
159 156
160 cmd.Dispose();
161
162 return true; 157 return true;
163 } 158 }
164 159
165 public bool SetDataItem(UUID principalID, string item, string value) 160 public bool SetDataItem(UUID principalID, string item, string value)
166 { 161 {
167 MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + 162 using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" +
168 "` set `" + item + "` = ?" + item + " where UUID = ?UUID"); 163 item + "` = ?" + item + " where UUID = ?UUID"))
169 164 {
170 165 cmd.Parameters.AddWithValue("?" + item, value);
171 cmd.Parameters.AddWithValue("?"+item, value); 166 cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
172 cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
173 167
174 if (ExecuteNonQuery(cmd) > 0) 168 if (ExecuteNonQuery(cmd) > 0)
175 return true; 169 return true;
170 }
176 171
177 return false; 172 return false;
178 } 173 }
diff --git a/OpenSim/Data/MySQL/MySQLUserData.cs b/OpenSim/Data/MySQL/MySQLUserData.cs
index 04f872f..bd46dfc 100644
--- a/OpenSim/Data/MySQL/MySQLUserData.cs
+++ b/OpenSim/Data/MySQL/MySQLUserData.cs
@@ -181,21 +181,20 @@ namespace OpenSim.Data.MySQL
181 param["?first"] = user; 181 param["?first"] = user;
182 param["?second"] = last; 182 param["?second"] = last;
183 183
184 IDbCommand result = 184 using (IDbCommand result = dbm.Manager.Query(
185 dbm.Manager.Query( 185 "SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param))
186 "SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param); 186 {
187 IDataReader reader = result.ExecuteReader(); 187 using (IDataReader reader = result.ExecuteReader())
188 188 {
189 UserProfileData row = dbm.Manager.readUserRow(reader); 189 UserProfileData row = dbm.Manager.readUserRow(reader);
190 190 return row;
191 reader.Dispose(); 191 }
192 result.Dispose(); 192 }
193 return row;
194 } 193 }
195 catch (Exception e) 194 catch (Exception e)
196 { 195 {
197 dbm.Manager.Reconnect(); 196 dbm.Manager.Reconnect();
198 m_log.Error(e.ToString()); 197 m_log.Error(e.Message, e);
199 return null; 198 return null;
200 } 199 }
201 finally 200 finally
@@ -220,28 +219,30 @@ namespace OpenSim.Data.MySQL
220 219
221 try 220 try
222 { 221 {
223 IDbCommand adder = 222 using (IDbCommand adder = dbm.Manager.Query(
224 dbm.Manager.Query( 223 "INSERT INTO `" + m_userFriendsTableName + "` " +
225 "INSERT INTO `" + m_userFriendsTableName + "` " + 224 "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
226 "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + 225 "VALUES " +
227 "VALUES " + 226 "(?ownerID,?friendID,?friendPerms,?datetimestamp)",
228 "(?ownerID,?friendID,?friendPerms,?datetimestamp)", 227 param))
229 param); 228 {
230 adder.ExecuteNonQuery(); 229 adder.ExecuteNonQuery();
231 230 }
232 adder = 231
233 dbm.Manager.Query( 232 using (IDbCommand adder = dbm.Manager.Query(
234 "INSERT INTO `" + m_userFriendsTableName + "` " + 233 "INSERT INTO `" + m_userFriendsTableName + "` " +
235 "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + 234 "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
236 "VALUES " + 235 "VALUES " +
237 "(?friendID,?ownerID,?friendPerms,?datetimestamp)", 236 "(?friendID,?ownerID,?friendPerms,?datetimestamp)",
238 param); 237 param))
239 adder.ExecuteNonQuery(); 238 {
239 adder.ExecuteNonQuery();
240 }
240 } 241 }
241 catch (Exception e) 242 catch (Exception e)
242 { 243 {
243 dbm.Manager.Reconnect(); 244 dbm.Manager.Reconnect();
244 m_log.Error(e.ToString()); 245 m_log.Error(e.Message, e);
245 return; 246 return;
246 } 247 }
247 finally 248 finally
@@ -260,22 +261,24 @@ namespace OpenSim.Data.MySQL
260 261
261 try 262 try
262 { 263 {
263 IDbCommand updater = 264 using (IDbCommand updater = dbm.Manager.Query(
264 dbm.Manager.Query(
265 "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID", 265 "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
266 param); 266 param))
267 updater.ExecuteNonQuery(); 267 {
268 updater.ExecuteNonQuery();
269 }
268 270
269 updater = 271 using (IDbCommand updater = dbm.Manager.Query(
270 dbm.Manager.Query(
271 "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID", 272 "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
272 param); 273 param))
273 updater.ExecuteNonQuery(); 274 {
275 updater.ExecuteNonQuery();
276 }
274 } 277 }
275 catch (Exception e) 278 catch (Exception e)
276 { 279 {
277 dbm.Manager.Reconnect(); 280 dbm.Manager.Reconnect();
278 m_log.Error(e.ToString()); 281 m_log.Error(e.Message, e);
279 return; 282 return;
280 } 283 }
281 finally 284 finally
@@ -295,18 +298,19 @@ namespace OpenSim.Data.MySQL
295 298
296 try 299 try
297 { 300 {
298 IDbCommand updater = 301 using (IDbCommand updater = dbm.Manager.Query(
299 dbm.Manager.Query(
300 "update " + m_userFriendsTableName + 302 "update " + m_userFriendsTableName +
301 " SET friendPerms = ?friendPerms " + 303 " SET friendPerms = ?friendPerms " +
302 "where ownerID = ?ownerID and friendID = ?friendID", 304 "where ownerID = ?ownerID and friendID = ?friendID",
303 param); 305 param))
304 updater.ExecuteNonQuery(); 306 {
307 updater.ExecuteNonQuery();
308 }
305 } 309 }
306 catch (Exception e) 310 catch (Exception e)
307 { 311 {
308 dbm.Manager.Reconnect(); 312 dbm.Manager.Reconnect();
309 m_log.Error(e.ToString()); 313 m_log.Error(e.Message, e);
310 return; 314 return;
311 } 315 }
312 finally 316 finally
@@ -327,34 +331,33 @@ namespace OpenSim.Data.MySQL
327 try 331 try
328 { 332 {
329 //Left Join userfriends to itself 333 //Left Join userfriends to itself
330 IDbCommand result = 334 using (IDbCommand result = dbm.Manager.Query(
331 dbm.Manager.Query( 335 "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " +
332 "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + 336 m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
333 m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" + 337 " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
334 " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID", 338 param))
335 param);
336 IDataReader reader = result.ExecuteReader();
337
338 while (reader.Read())
339 { 339 {
340 FriendListItem fli = new FriendListItem(); 340 using (IDataReader reader = result.ExecuteReader())
341 fli.FriendListOwner = new UUID((string) reader["ownerID"]); 341 {
342 fli.Friend = new UUID((string) reader["friendID"]); 342 while (reader.Read())
343 fli.FriendPerms = (uint) Convert.ToInt32(reader["friendPerms"]); 343 {
344 344 FriendListItem fli = new FriendListItem();
345 // This is not a real column in the database table, it's a joined column from the opposite record 345 fli.FriendListOwner = new UUID((string)reader["ownerID"]);
346 fli.FriendListOwnerPerms = (uint) Convert.ToInt32(reader["ownerperms"]); 346 fli.Friend = new UUID((string)reader["friendID"]);
347 347 fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]);
348 Lfli.Add(fli); 348
349 // This is not a real column in the database table, it's a joined column from the opposite record
350 fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]);
351
352 Lfli.Add(fli);
353 }
354 }
349 } 355 }
350
351 reader.Dispose();
352 result.Dispose();
353 } 356 }
354 catch (Exception e) 357 catch (Exception e)
355 { 358 {
356 dbm.Manager.Reconnect(); 359 dbm.Manager.Reconnect();
357 m_log.Error(e.ToString()); 360 m_log.Error(e.Message, e);
358 return Lfli; 361 return Lfli;
359 } 362 }
360 finally 363 finally
@@ -376,29 +379,29 @@ namespace OpenSim.Data.MySQL
376 { 379 {
377 Dictionary<string, object> param = new Dictionary<string, object>(); 380 Dictionary<string, object> param = new Dictionary<string, object>();
378 param["?uuid"] = uuid.ToString(); 381 param["?uuid"] = uuid.ToString();
379 IDbCommand result =
380 dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
381 " where UUID = ?uuid", param);
382 382
383 IDataReader reader = result.ExecuteReader(); 383 using (IDbCommand result = dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
384 while (reader.Read()) 384 " where UUID = ?uuid", param))
385 { 385 {
386 FriendRegionInfo fri = new FriendRegionInfo(); 386 using (IDataReader reader = result.ExecuteReader())
387 fri.isOnline = (sbyte)reader["agentOnline"] != 0; 387 {
388 fri.regionHandle = (ulong)reader["currentHandle"]; 388 while (reader.Read())
389 389 {
390 infos[uuid] = fri; 390 FriendRegionInfo fri = new FriendRegionInfo();
391 fri.isOnline = (sbyte)reader["agentOnline"] != 0;
392 fri.regionHandle = (ulong)reader["currentHandle"];
393
394 infos[uuid] = fri;
395 }
396 }
391 } 397 }
392
393 reader.Dispose();
394 result.Dispose();
395 } 398 }
396 } 399 }
397 catch (Exception e) 400 catch (Exception e)
398 { 401 {
399 m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e); 402 m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e);
400 dbm.Manager.Reconnect(); 403 dbm.Manager.Reconnect();
401 m_log.Error(e.ToString()); 404 m_log.Error(e.Message, e);
402 } 405 }
403 finally 406 finally
404 { 407 {
@@ -427,28 +430,28 @@ namespace OpenSim.Data.MySQL
427 430
428 try 431 try
429 { 432 {
430 IDbCommand result = 433 using (IDbCommand result = dbm.Manager.Query(
431 dbm.Manager.Query( 434 "SELECT UUID,username,lastname FROM " + m_usersTableName +
432 "SELECT UUID,username,lastname FROM " + m_usersTableName + 435 " WHERE username like ?first AND lastname like ?second LIMIT 100",
433 " WHERE username like ?first AND lastname like ?second LIMIT 100", 436 param))
434 param);
435 IDataReader reader = result.ExecuteReader();
436
437 while (reader.Read())
438 { 437 {
439 AvatarPickerAvatar user = new AvatarPickerAvatar(); 438 using (IDataReader reader = result.ExecuteReader())
440 user.AvatarID = new UUID((string) reader["UUID"]); 439 {
441 user.firstName = (string) reader["username"]; 440 while (reader.Read())
442 user.lastName = (string) reader["lastname"]; 441 {
443 returnlist.Add(user); 442 AvatarPickerAvatar user = new AvatarPickerAvatar();
443 user.AvatarID = new UUID((string)reader["UUID"]);
444 user.firstName = (string)reader["username"];
445 user.lastName = (string)reader["lastname"];
446 returnlist.Add(user);
447 }
448 }
444 } 449 }
445 reader.Dispose();
446 result.Dispose();
447 } 450 }
448 catch (Exception e) 451 catch (Exception e)
449 { 452 {
450 dbm.Manager.Reconnect(); 453 dbm.Manager.Reconnect();
451 m_log.Error(e.ToString()); 454 m_log.Error(e.Message, e);
452 return returnlist; 455 return returnlist;
453 } 456 }
454 finally 457 finally
@@ -465,28 +468,28 @@ namespace OpenSim.Data.MySQL
465 Dictionary<string, object> param = new Dictionary<string, object>(); 468 Dictionary<string, object> param = new Dictionary<string, object>();
466 param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%"; 469 param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
467 470
468 IDbCommand result = 471 using (IDbCommand result = dbm.Manager.Query(
469 dbm.Manager.Query( 472 "SELECT UUID,username,lastname FROM " + m_usersTableName +
470 "SELECT UUID,username,lastname FROM " + m_usersTableName + 473 " WHERE username like ?first OR lastname like ?first LIMIT 100",
471 " WHERE username like ?first OR lastname like ?first LIMIT 100", 474 param))
472 param);
473 IDataReader reader = result.ExecuteReader();
474
475 while (reader.Read())
476 { 475 {
477 AvatarPickerAvatar user = new AvatarPickerAvatar(); 476 using (IDataReader reader = result.ExecuteReader())
478 user.AvatarID = new UUID((string) reader["UUID"]); 477 {
479 user.firstName = (string) reader["username"]; 478 while (reader.Read())
480 user.lastName = (string) reader["lastname"]; 479 {
481 returnlist.Add(user); 480 AvatarPickerAvatar user = new AvatarPickerAvatar();
481 user.AvatarID = new UUID((string)reader["UUID"]);
482 user.firstName = (string)reader["username"];
483 user.lastName = (string)reader["lastname"];
484 returnlist.Add(user);
485 }
486 }
482 } 487 }
483 reader.Dispose();
484 result.Dispose();
485 } 488 }
486 catch (Exception e) 489 catch (Exception e)
487 { 490 {
488 dbm.Manager.Reconnect(); 491 dbm.Manager.Reconnect();
489 m_log.Error(e.ToString()); 492 m_log.Error(e.Message, e);
490 return returnlist; 493 return returnlist;
491 } 494 }
492 finally 495 finally
@@ -510,20 +513,19 @@ namespace OpenSim.Data.MySQL
510 Dictionary<string, object> param = new Dictionary<string, object>(); 513 Dictionary<string, object> param = new Dictionary<string, object>();
511 param["?uuid"] = uuid.ToString(); 514 param["?uuid"] = uuid.ToString();
512 515
513 IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param); 516 using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param))
514 IDataReader reader = result.ExecuteReader(); 517 {
515 518 using (IDataReader reader = result.ExecuteReader())
516 UserProfileData row = dbm.Manager.readUserRow(reader); 519 {
517 520 UserProfileData row = dbm.Manager.readUserRow(reader);
518 reader.Dispose(); 521 return row;
519 result.Dispose(); 522 }
520 523 }
521 return row;
522 } 524 }
523 catch (Exception e) 525 catch (Exception e)
524 { 526 {
525 dbm.Manager.Reconnect(); 527 dbm.Manager.Reconnect();
526 m_log.Error(e.ToString()); 528 m_log.Error(e.Message, e);
527 return null; 529 return null;
528 } 530 }
529 finally 531 finally
@@ -569,15 +571,15 @@ namespace OpenSim.Data.MySQL
569 571
570 try 572 try
571 { 573 {
572 dbm.Manager.ExecuteParameterizedSql( 574 dbm.Manager.ExecuteParameterizedSql(
573 "update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " + 575 "update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " +
574 "where UUID = ?UUID", 576 "where UUID = ?UUID",
575 param); 577 param);
576 } 578 }
577 catch (Exception e) 579 catch (Exception e)
578 { 580 {
579 dbm.Manager.Reconnect(); 581 dbm.Manager.Reconnect();
580 m_log.Error(e.ToString()); 582 m_log.Error(e.Message, e);
581 return; 583 return;
582 } 584 }
583 finally 585 finally
@@ -600,21 +602,19 @@ namespace OpenSim.Data.MySQL
600 Dictionary<string, object> param = new Dictionary<string, object>(); 602 Dictionary<string, object> param = new Dictionary<string, object>();
601 param["?uuid"] = uuid.ToString(); 603 param["?uuid"] = uuid.ToString();
602 604
603 IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", 605 using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param))
604 param); 606 {
605 IDataReader reader = result.ExecuteReader(); 607 using (IDataReader reader = result.ExecuteReader())
606 608 {
607 UserAgentData row = dbm.Manager.readAgentRow(reader); 609 UserAgentData row = dbm.Manager.readAgentRow(reader);
608 610 return row;
609 reader.Dispose(); 611 }
610 result.Dispose(); 612 }
611
612 return row;
613 } 613 }
614 catch (Exception e) 614 catch (Exception e)
615 { 615 {
616 dbm.Manager.Reconnect(); 616 dbm.Manager.Reconnect();
617 m_log.Error(e.ToString()); 617 m_log.Error(e.Message, e);
618 return null; 618 return null;
619 } 619 }
620 finally 620 finally
@@ -638,19 +638,20 @@ namespace OpenSim.Data.MySQL
638 638
639 try 639 try
640 { 640 {
641 dbm.Manager.insertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, 641 dbm.Manager.insertUserRow(
642 user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, 642 user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
643 user.HomeLocation.Z, 643 user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
644 user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, 644 user.HomeLocation.Z,
645 user.LastLogin, user.UserInventoryURI, user.UserAssetURI, 645 user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
646 user.CanDoMask, user.WantDoMask, 646 user.LastLogin, user.UserInventoryURI, user.UserAssetURI,
647 user.AboutText, user.FirstLifeAboutText, user.Image, 647 user.CanDoMask, user.WantDoMask,
648 user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner); 648 user.AboutText, user.FirstLifeAboutText, user.Image,
649 user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
649 } 650 }
650 catch (Exception e) 651 catch (Exception e)
651 { 652 {
652 dbm.Manager.Reconnect(); 653 dbm.Manager.Reconnect();
653 m_log.Error(e.ToString()); 654 m_log.Error(e.Message, e);
654 } 655 }
655 finally 656 finally
656 { 657 {
@@ -676,7 +677,7 @@ namespace OpenSim.Data.MySQL
676 catch (Exception e) 677 catch (Exception e)
677 { 678 {
678 dbm.Manager.Reconnect(); 679 dbm.Manager.Reconnect();
679 m_log.Error(e.ToString()); 680 m_log.Error(e.Message, e);
680 } 681 }
681 finally 682 finally
682 { 683 {
@@ -693,14 +694,15 @@ namespace OpenSim.Data.MySQL
693 MySQLSuperManager dbm = GetLockedConnection("UpdateUserProfile"); 694 MySQLSuperManager dbm = GetLockedConnection("UpdateUserProfile");
694 try 695 try
695 { 696 {
696 dbm.Manager.updateUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, 697 dbm.Manager.updateUserRow(
697 user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, 698 user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
698 user.HomeLocation.Z, user.HomeLookAt.X, 699 user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
699 user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, 700 user.HomeLocation.Z, user.HomeLookAt.X,
700 user.UserInventoryURI, 701 user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin,
701 user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText, 702 user.UserInventoryURI,
702 user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey, 703 user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText,
703 user.UserFlags, user.GodLevel, user.CustomType, user.Partner); 704 user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey,
705 user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
704 } 706 }
705 finally 707 finally
706 { 708 {
@@ -748,29 +750,29 @@ namespace OpenSim.Data.MySQL
748 Dictionary<string, object> param = new Dictionary<string, object>(); 750 Dictionary<string, object> param = new Dictionary<string, object>();
749 param["?owner"] = user.ToString(); 751 param["?owner"] = user.ToString();
750 752
751 IDbCommand result = dbm.Manager.Query( 753 using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param))
752 "SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param);
753 IDataReader reader = result.ExecuteReader();
754
755 AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader);
756
757 reader.Dispose();
758 result.Dispose();
759
760 if (null == appearance)
761 { 754 {
762 m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); 755 using (IDataReader reader = result.ExecuteReader())
763 return null; 756 {
757 AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader);
758
759 if (appearance == null)
760 {
761 m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString());
762 return null;
763 }
764 else
765 {
766 appearance.SetAttachments(GetUserAttachments(user));
767 return appearance;
768 }
769 }
764 } 770 }
765
766 appearance.SetAttachments(GetUserAttachments(user));
767
768 return appearance;
769 } 771 }
770 catch (Exception e) 772 catch (Exception e)
771 { 773 {
772 dbm.Manager.Reconnect(); 774 dbm.Manager.Reconnect();
773 m_log.Error(e.ToString()); 775 m_log.Error(e.Message, e);
774 return null; 776 return null;
775 } 777 }
776 finally 778 finally
@@ -798,7 +800,7 @@ namespace OpenSim.Data.MySQL
798 catch (Exception e) 800 catch (Exception e)
799 { 801 {
800 dbm.Manager.Reconnect(); 802 dbm.Manager.Reconnect();
801 m_log.Error(e.ToString()); 803 m_log.Error(e.Message, e);
802 } 804 }
803 finally 805 finally
804 { 806 {
@@ -833,20 +835,20 @@ namespace OpenSim.Data.MySQL
833 835
834 try 836 try
835 { 837 {
836 IDbCommand result = dbm.Manager.Query( 838 using (IDbCommand result = dbm.Manager.Query(
837 "SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param); 839 "SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param))
838 IDataReader reader = result.ExecuteReader(); 840 {
839 841 using (IDataReader reader = result.ExecuteReader())
840 Hashtable ret = dbm.Manager.readAttachments(reader); 842 {
841 843 Hashtable ret = dbm.Manager.readAttachments(reader);
842 reader.Dispose(); 844 return ret;
843 result.Dispose(); 845 }
844 return ret; 846 }
845 } 847 }
846 catch (Exception e) 848 catch (Exception e)
847 { 849 {
848 dbm.Manager.Reconnect(); 850 dbm.Manager.Reconnect();
849 m_log.Error(e.ToString()); 851 m_log.Error(e.Message, e);
850 return null; 852 return null;
851 } 853 }
852 finally 854 finally
@@ -905,7 +907,7 @@ namespace OpenSim.Data.MySQL
905 catch (Exception e) 907 catch (Exception e)
906 { 908 {
907 dbm.Manager.Reconnect(); 909 dbm.Manager.Reconnect();
908 m_log.Error(e.ToString()); 910 m_log.Error(e.Message, e);
909 return; 911 return;
910 } 912 }
911 finally 913 finally
diff --git a/OpenSim/Data/SQLite/SQLiteRegionData.cs b/OpenSim/Data/SQLite/SQLiteRegionData.cs
index 1d17bb9..08af7c3 100644
--- a/OpenSim/Data/SQLite/SQLiteRegionData.cs
+++ b/OpenSim/Data/SQLite/SQLiteRegionData.cs
@@ -581,13 +581,17 @@ namespace OpenSim.Data.SQLite
581 if (row.Read()) 581 if (row.Read())
582 { 582 {
583 // TODO: put this into a function 583 // TODO: put this into a function
584 MemoryStream str = new MemoryStream((byte[]) row["Heightfield"]); 584 using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"]))
585 BinaryReader br = new BinaryReader(str);
586 for (int x = 0; x < (int)Constants.RegionSize; x++)
587 { 585 {
588 for (int y = 0; y < (int)Constants.RegionSize; y++) 586 using (BinaryReader br = new BinaryReader(str))
589 { 587 {
590 terret[x, y] = br.ReadDouble(); 588 for (int x = 0; x < (int)Constants.RegionSize; x++)
589 {
590 for (int y = 0; y < (int)Constants.RegionSize; y++)
591 {
592 terret[x, y] = br.ReadDouble();
593 }
594 }
591 } 595 }
592 } 596 }
593 rev = (int) row["Revision"]; 597 rev = (int) row["Revision"];
diff --git a/OpenSim/Framework/AssetLandmark.cs b/OpenSim/Framework/AssetLandmark.cs
index 7c87c34..fd7a2cd 100644
--- a/OpenSim/Framework/AssetLandmark.cs
+++ b/OpenSim/Framework/AssetLandmark.cs
@@ -49,7 +49,7 @@ namespace OpenSim.Framework
49 49
50 private void InternData() 50 private void InternData()
51 { 51 {
52 string temp = Encoding.UTF8.GetString(Data).Trim(); 52 string temp = Util.UTF8.GetString(Data).Trim();
53 string[] parts = temp.Split('\n'); 53 string[] parts = temp.Split('\n');
54 int.TryParse(parts[0].Substring(17, 1), out Version); 54 int.TryParse(parts[0].Substring(17, 1), out Version);
55 UUID.TryParse(parts[1].Substring(10, 36), out RegionID); 55 UUID.TryParse(parts[1].Substring(10, 36), out RegionID);
diff --git a/OpenSim/Framework/Capabilities/LLSD.cs b/OpenSim/Framework/Capabilities/LLSD.cs
index 84f43c1..eec9e61 100644
--- a/OpenSim/Framework/Capabilities/LLSD.cs
+++ b/OpenSim/Framework/Capabilities/LLSD.cs
@@ -112,7 +112,7 @@ namespace OpenSim.Framework.Capabilities
112 112
113 writer.Close(); 113 writer.Close();
114 114
115 return Encoding.UTF8.GetBytes(sw.ToString()); 115 return Util.UTF8.GetBytes(sw.ToString());
116 } 116 }
117 117
118 /// <summary> 118 /// <summary>
@@ -329,7 +329,7 @@ namespace OpenSim.Framework.Capabilities
329 329
330 reader.Read(); 330 reader.Read();
331 FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); 331 FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces);
332 byte[] inp = Encoding.UTF8.GetBytes(reader.ReadString()); 332 byte[] inp = Util.UTF8.GetBytes(reader.ReadString());
333 ret = b64.TransformFinalBlock(inp, 0, inp.Length); 333 ret = b64.TransformFinalBlock(inp, 0, inp.Length);
334 break; 334 break;
335 } 335 }
diff --git a/OpenSim/Framework/Capabilities/LLSDStreamHandler.cs b/OpenSim/Framework/Capabilities/LLSDStreamHandler.cs
index df48b35..7aaa994 100644
--- a/OpenSim/Framework/Capabilities/LLSDStreamHandler.cs
+++ b/OpenSim/Framework/Capabilities/LLSDStreamHandler.cs
@@ -47,7 +47,7 @@ namespace OpenSim.Framework.Capabilities
47 public override byte[] Handle(string path, Stream request, 47 public override byte[] Handle(string path, Stream request,
48 OSHttpRequest httpRequest, OSHttpResponse httpResponse) 48 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
49 { 49 {
50 //Encoding encoding = Encoding.UTF8; 50 //Encoding encoding = Util.UTF8;
51 //StreamReader streamReader = new StreamReader(request, false); 51 //StreamReader streamReader = new StreamReader(request, false);
52 52
53 //string requestBody = streamReader.ReadToEnd(); 53 //string requestBody = streamReader.ReadToEnd();
diff --git a/OpenSim/Framework/Communications/Clients/RegionClient.cs b/OpenSim/Framework/Communications/Clients/RegionClient.cs
index 3419ce2..10be069 100644
--- a/OpenSim/Framework/Communications/Clients/RegionClient.cs
+++ b/OpenSim/Framework/Communications/Clients/RegionClient.cs
@@ -106,7 +106,6 @@ namespace OpenSim.Framework.Communications.Clients
106 AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send 106 AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
107 os = AgentCreateRequest.GetRequestStream(); 107 os = AgentCreateRequest.GetRequestStream();
108 os.Write(buffer, 0, strBuffer.Length); //Send it 108 os.Write(buffer, 0, strBuffer.Length); //Send it
109 os.Close();
110 //m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri); 109 //m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
111 } 110 }
112 //catch (WebException ex) 111 //catch (WebException ex)
@@ -116,6 +115,11 @@ namespace OpenSim.Framework.Communications.Clients
116 reason = "cannot contact remote region"; 115 reason = "cannot contact remote region";
117 return false; 116 return false;
118 } 117 }
118 finally
119 {
120 if (os != null)
121 os.Close();
122 }
119 123
120 // Let's wait for the response 124 // Let's wait for the response
121 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); 125 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
@@ -224,7 +228,6 @@ namespace OpenSim.Framework.Communications.Clients
224 ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send 228 ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
225 os = ChildUpdateRequest.GetRequestStream(); 229 os = ChildUpdateRequest.GetRequestStream();
226 os.Write(buffer, 0, strBuffer.Length); //Send it 230 os.Write(buffer, 0, strBuffer.Length); //Send it
227 os.Close();
228 //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri); 231 //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
229 } 232 }
230 //catch (WebException ex) 233 //catch (WebException ex)
@@ -234,6 +237,11 @@ namespace OpenSim.Framework.Communications.Clients
234 237
235 return false; 238 return false;
236 } 239 }
240 finally
241 {
242 if (os != null)
243 os.Close();
244 }
237 245
238 // Let's wait for the response 246 // Let's wait for the response
239 //m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate"); 247 //m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
@@ -437,7 +445,6 @@ namespace OpenSim.Framework.Communications.Clients
437 ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send 445 ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
438 os = ObjectCreateRequest.GetRequestStream(); 446 os = ObjectCreateRequest.GetRequestStream();
439 os.Write(buffer, 0, strBuffer.Length); //Send it 447 os.Write(buffer, 0, strBuffer.Length); //Send it
440 os.Close();
441 m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri); 448 m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
442 } 449 }
443 //catch (WebException ex) 450 //catch (WebException ex)
@@ -447,6 +454,11 @@ namespace OpenSim.Framework.Communications.Clients
447 454
448 return false; 455 return false;
449 } 456 }
457 finally
458 {
459 if (os != null)
460 os.Close();
461 }
450 462
451 // Let's wait for the response 463 // Let's wait for the response
452 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); 464 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
@@ -512,7 +524,6 @@ namespace OpenSim.Framework.Communications.Clients
512 ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send 524 ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
513 os = ObjectCreateRequest.GetRequestStream(); 525 os = ObjectCreateRequest.GetRequestStream();
514 os.Write(buffer, 0, strBuffer.Length); //Send it 526 os.Write(buffer, 0, strBuffer.Length); //Send it
515 os.Close();
516 //m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri); 527 //m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri);
517 } 528 }
518 //catch (WebException ex) 529 //catch (WebException ex)
@@ -522,6 +533,11 @@ namespace OpenSim.Framework.Communications.Clients
522 533
523 return false; 534 return false;
524 } 535 }
536 finally
537 {
538 if (os != null)
539 os.Close();
540 }
525 541
526 // Let's wait for the response 542 // Let's wait for the response
527 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); 543 //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
@@ -597,7 +613,6 @@ namespace OpenSim.Framework.Communications.Clients
597 HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send 613 HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
598 os = HelloNeighbourRequest.GetRequestStream(); 614 os = HelloNeighbourRequest.GetRequestStream();
599 os.Write(buffer, 0, strBuffer.Length); //Send it 615 os.Write(buffer, 0, strBuffer.Length); //Send it
600 os.Close();
601 //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri); 616 //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
602 } 617 }
603 //catch (WebException ex) 618 //catch (WebException ex)
@@ -607,7 +622,11 @@ namespace OpenSim.Framework.Communications.Clients
607 622
608 return false; 623 return false;
609 } 624 }
610 625 finally
626 {
627 if (os != null)
628 os.Close();
629 }
611 // Let's wait for the response 630 // Let's wait for the response
612 //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall"); 631 //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");
613 632
diff --git a/OpenSim/Framework/Communications/XMPP/XmppWriter.cs b/OpenSim/Framework/Communications/XMPP/XmppWriter.cs
index b52eda7..415d808 100644
--- a/OpenSim/Framework/Communications/XMPP/XmppWriter.cs
+++ b/OpenSim/Framework/Communications/XMPP/XmppWriter.cs
@@ -38,7 +38,7 @@ namespace OpenSim.Framework.Communications.XMPP
38 { 38 {
39 } 39 }
40 40
41 public XMPPWriter(IOStream stream) : this(stream, Encoding.UTF8) 41 public XMPPWriter(IOStream stream) : this(stream, Util.UTF8)
42 { 42 {
43 } 43 }
44 44
diff --git a/OpenSim/Framework/Configuration/HTTP/HTTPConfiguration.cs b/OpenSim/Framework/Configuration/HTTP/HTTPConfiguration.cs
index 318d2c3..3dce578 100644
--- a/OpenSim/Framework/Configuration/HTTP/HTTPConfiguration.cs
+++ b/OpenSim/Framework/Configuration/HTTP/HTTPConfiguration.cs
@@ -77,7 +77,7 @@ namespace OpenSim.Framework.Configuration.HTTP
77 count = resStream.Read(buf, 0, buf.Length); 77 count = resStream.Read(buf, 0, buf.Length);
78 if (count != 0) 78 if (count != 0)
79 { 79 {
80 tempString = Encoding.UTF8.GetString(buf, 0, count); 80 tempString = Util.UTF8.GetString(buf, 0, count);
81 sb.Append(tempString); 81 sb.Append(tempString);
82 } 82 }
83 } while (count > 0); 83 } while (count > 0);
diff --git a/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs b/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs
index 5afa110..03c12dd 100644
--- a/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs
+++ b/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs
@@ -91,24 +91,35 @@ namespace OpenSim.Framework.Servers.HttpServer
91 Stream requestStream = request.EndGetRequestStream(res); 91 Stream requestStream = request.EndGetRequestStream(res);
92 92
93 requestStream.Write(buffer.ToArray(), 0, length); 93 requestStream.Write(buffer.ToArray(), 0, length);
94 requestStream.Close();
94 95
95 request.BeginGetResponse(delegate(IAsyncResult ar) 96 request.BeginGetResponse(delegate(IAsyncResult ar)
96 { 97 {
97 response = request.EndGetResponse(ar); 98 response = request.EndGetResponse(ar);
98 99 Stream respStream = null;
99 try 100 try
100 { 101 {
101 deserial = (TResponse) deserializer.Deserialize( 102 respStream = response.GetResponseStream();
102 response.GetResponseStream()); 103 deserial = (TResponse)deserializer.Deserialize(
104 respStream);
103 } 105 }
104 catch (System.InvalidOperationException) 106 catch (System.InvalidOperationException)
105 { 107 {
106 } 108 }
109 finally
110 {
111 // Let's not close this
112 //buffer.Close();
113 respStream.Close();
114 response.Close();
115 }
107 116
108 action(deserial); 117 action(deserial);
118
109 }, null); 119 }, null);
110 }, null); 120 }, null);
111 121
122
112 return; 123 return;
113 } 124 }
114 125
@@ -119,14 +130,21 @@ namespace OpenSim.Framework.Servers.HttpServer
119 // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't 130 // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
120 // documented in MSDN 131 // documented in MSDN
121 response = request.EndGetResponse(res2); 132 response = request.EndGetResponse(res2);
122 133
134 Stream respStream = null;
123 try 135 try
124 { 136 {
125 deserial = (TResponse)deserializer.Deserialize(response.GetResponseStream()); 137 respStream = response.GetResponseStream();
138 deserial = (TResponse)deserializer.Deserialize(respStream);
126 } 139 }
127 catch (System.InvalidOperationException) 140 catch (System.InvalidOperationException)
128 { 141 {
129 } 142 }
143 finally
144 {
145 respStream.Close();
146 response.Close();
147 }
130 } 148 }
131 catch (WebException e) 149 catch (WebException e)
132 { 150 {
@@ -148,7 +166,7 @@ namespace OpenSim.Framework.Servers.HttpServer
148 } 166 }
149 else 167 else
150 { 168 {
151 m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e); 169 m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
152 } 170 }
153 } 171 }
154 catch (Exception e) 172 catch (Exception e)
diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
index 6c63c6c..942fed9 100644
--- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
+++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
@@ -979,7 +979,7 @@ namespace OpenSim.Framework.Servers.HttpServer
979 } 979 }
980 980
981 // response.ContentType = "application/llsd+json"; 981 // response.ContentType = "application/llsd+json";
982 // return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse)); 982 // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
983 response.ContentType = "application/llsd+xml"; 983 response.ContentType = "application/llsd+xml";
984 return OSDParser.SerializeLLSDXmlBytes(llsdResponse); 984 return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
985 } 985 }
diff --git a/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs b/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs
index 3f72c31..7ebb462 100644
--- a/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs
+++ b/OpenSim/Framework/Servers/HttpServer/RestSessionService.cs
@@ -94,13 +94,26 @@ namespace OpenSim.Framework.Servers.HttpServer
94 94
95 Stream requestStream = request.GetRequestStream(); 95 Stream requestStream = request.GetRequestStream();
96 requestStream.Write(buffer.ToArray(), 0, length); 96 requestStream.Write(buffer.ToArray(), 0, length);
97 buffer.Close();
97 requestStream.Close(); 98 requestStream.Close();
99
98 TResponse deserial = default(TResponse); 100 TResponse deserial = default(TResponse);
99 using (WebResponse resp = request.GetResponse()) 101 using (WebResponse resp = request.GetResponse())
100 { 102 {
101 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); 103 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
102 deserial = (TResponse)deserializer.Deserialize(resp.GetResponseStream()); 104 Stream respStream = null;
103 resp.Close(); 105 try
106 {
107 respStream = resp.GetResponseStream();
108 deserial = (TResponse)deserializer.Deserialize(respStream);
109 }
110 catch { }
111 finally
112 {
113 if (respStream != null)
114 respStream.Close();
115 resp.Close();
116 }
104 } 117 }
105 return deserial; 118 return deserial;
106 } 119 }
@@ -140,6 +153,7 @@ namespace OpenSim.Framework.Servers.HttpServer
140 serializer.Serialize(writer, sobj); 153 serializer.Serialize(writer, sobj);
141 writer.Flush(); 154 writer.Flush();
142 } 155 }
156 buffer.Close();
143 157
144 int length = (int)buffer.Length; 158 int length = (int)buffer.Length;
145 request.ContentLength = length; 159 request.ContentLength = length;
@@ -165,6 +179,8 @@ namespace OpenSim.Framework.Servers.HttpServer
165 // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd()); 179 // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd());
166 180
167 deserial = (TResponse)deserializer.Deserialize(stream); 181 deserial = (TResponse)deserializer.Deserialize(stream);
182 if (stream != null)
183 stream.Close();
168 184
169 if (deserial != null && ResponseCallback != null) 185 if (deserial != null && ResponseCallback != null)
170 { 186 {
diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs
index a0d4008..8a490f7 100644
--- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs
+++ b/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs
@@ -66,8 +66,23 @@ namespace OpenSim.Framework.Servers.HttpServer
66 length = (int)obj.Length; 66 length = (int)obj.Length;
67 request.ContentLength = length; 67 request.ContentLength = length;
68 68
69 Stream requestStream = request.GetRequestStream(); 69 Stream requestStream = null;
70 requestStream.Write(buffer.ToArray(), 0, length); 70 try
71 {
72 requestStream = request.GetRequestStream();
73 requestStream.Write(buffer.ToArray(), 0, length);
74 }
75 catch
76 {
77 }
78 finally
79 {
80 if (requestStream != null)
81 requestStream.Close();
82 // Let's not close this
83 //buffer.Close();
84
85 }
71 } 86 }
72 87
73 string respstring = String.Empty; 88 string respstring = String.Empty;
@@ -78,9 +93,20 @@ namespace OpenSim.Framework.Servers.HttpServer
78 { 93 {
79 if (resp.ContentLength > 0) 94 if (resp.ContentLength > 0)
80 { 95 {
81 using (StreamReader reader = new StreamReader(resp.GetResponseStream())) 96 Stream respStream = null;
97 try
98 {
99 respStream = resp.GetResponseStream();
100 using (StreamReader reader = new StreamReader(respStream))
101 {
102 respstring = reader.ReadToEnd();
103 }
104 }
105 catch { }
106 finally
82 { 107 {
83 respstring = reader.ReadToEnd(); 108 if (respStream != null)
109 respStream.Close();
84 } 110 }
85 } 111 }
86 } 112 }
diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs
index ec9bd4f..eab463c 100644
--- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs
+++ b/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs
@@ -58,6 +58,7 @@ namespace OpenSim.Framework.Servers.HttpServer
58 public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj) 58 public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
59 { 59 {
60 Type type = typeof (TRequest); 60 Type type = typeof (TRequest);
61 TResponse deserial = default(TResponse);
61 62
62 WebRequest request = WebRequest.Create(requestUrl); 63 WebRequest request = WebRequest.Create(requestUrl);
63 request.Method = verb; 64 request.Method = verb;
@@ -81,19 +82,33 @@ namespace OpenSim.Framework.Servers.HttpServer
81 int length = (int) buffer.Length; 82 int length = (int) buffer.Length;
82 request.ContentLength = length; 83 request.ContentLength = length;
83 84
84 Stream requestStream = request.GetRequestStream(); 85 Stream requestStream = null;
85 requestStream.Write(buffer.ToArray(), 0, length); 86 try
87 {
88 requestStream = request.GetRequestStream();
89 requestStream.Write(buffer.ToArray(), 0, length);
90 }
91 catch (Exception)
92 {
93 return deserial;
94 }
95 finally
96 {
97 if (requestStream != null)
98 requestStream.Close();
99 }
86 } 100 }
87 101
88 TResponse deserial = default(TResponse);
89 try 102 try
90 { 103 {
91 using (WebResponse resp = request.GetResponse()) 104 using (WebResponse resp = request.GetResponse())
92 { 105 {
93 if (resp.ContentLength > 0) 106 if (resp.ContentLength > 0)
94 { 107 {
108 Stream respStream = resp.GetResponseStream();
95 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); 109 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
96 deserial = (TResponse)deserializer.Deserialize(resp.GetResponseStream()); 110 deserial = (TResponse)deserializer.Deserialize(respStream);
111 respStream.Close();
97 } 112 }
98 } 113 }
99 } 114 }
diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs
index 17fc58c..0851d26 100644
--- a/OpenSim/Framework/Util.cs
+++ b/OpenSim/Framework/Util.cs
@@ -103,6 +103,8 @@ namespace OpenSim.Framework
103 } 103 }
104 104
105 105
106 public static Encoding UTF8 = Encoding.UTF8;
107
106 /// <value> 108 /// <value>
107 /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards) 109 /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
108 /// </value> 110 /// </value>
@@ -465,7 +467,7 @@ namespace OpenSim.Framework
465 output.Append(": "); 467 output.Append(": ");
466 } 468 }
467 469
468 output.Append(CleanString(Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1))); 470 output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
469 } 471 }
470 else 472 else
471 { 473 {
@@ -826,7 +828,7 @@ namespace OpenSim.Framework
826 828
827 public static string Compress(string text) 829 public static string Compress(string text)
828 { 830 {
829 byte[] buffer = Encoding.UTF8.GetBytes(text); 831 byte[] buffer = Util.UTF8.GetBytes(text);
830 MemoryStream memory = new MemoryStream(); 832 MemoryStream memory = new MemoryStream();
831 using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true)) 833 using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
832 { 834 {
@@ -860,7 +862,7 @@ namespace OpenSim.Framework
860 decompressor.Read(buffer, 0, buffer.Length); 862 decompressor.Read(buffer, 0, buffer.Length);
861 } 863 }
862 864
863 return Encoding.UTF8.GetString(buffer); 865 return Util.UTF8.GetString(buffer);
864 } 866 }
865 } 867 }
866 868
@@ -1132,7 +1134,7 @@ namespace OpenSim.Framework
1132 { 1134 {
1133 byte[] data = new byte[length]; 1135 byte[] data = new byte[length];
1134 stream.Read(data, 0, length); 1136 stream.Read(data, 0, length);
1135 string strdata = Encoding.UTF8.GetString(data); 1137 string strdata = Util.UTF8.GetString(data);
1136 OSDMap args = null; 1138 OSDMap args = null;
1137 OSD buffer; 1139 OSD buffer;
1138 buffer = OSDParser.DeserializeJson(strdata); 1140 buffer = OSDParser.DeserializeJson(strdata);
diff --git a/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs b/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs
index 5651a17..dedf876 100644
--- a/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs
+++ b/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs
@@ -39,6 +39,10 @@ using OpenSim.Data;
39using OpenSim.Framework; 39using OpenSim.Framework;
40using OpenSim.Grid.Framework; 40using OpenSim.Grid.Framework;
41using Timer = System.Timers.Timer; 41using Timer = System.Timers.Timer;
42using OpenSim.Services.Interfaces;
43using OpenSim.Services.Connectors;
44using GridRegion = OpenSim.Services.Interfaces.GridRegion;
45
42 46
43namespace OpenSim.Grid.MessagingServer.Modules 47namespace OpenSim.Grid.MessagingServer.Modules
44{ 48{
@@ -52,6 +56,8 @@ namespace OpenSim.Grid.MessagingServer.Modules
52 56
53 private IGridServiceCore m_messageCore; 57 private IGridServiceCore m_messageCore;
54 58
59 private IGridService m_GridService;
60
55 // a dictionary of all current regions this server knows about 61 // a dictionary of all current regions this server knows about
56 private Dictionary<ulong, RegionProfileData> m_regionInfoCache = new Dictionary<ulong, RegionProfileData>(); 62 private Dictionary<ulong, RegionProfileData> m_regionInfoCache = new Dictionary<ulong, RegionProfileData>();
57 63
@@ -59,6 +65,8 @@ namespace OpenSim.Grid.MessagingServer.Modules
59 { 65 {
60 m_cfg = config; 66 m_cfg = config;
61 m_messageCore = messageCore; 67 m_messageCore = messageCore;
68
69 m_GridService = new GridServicesConnector(m_cfg.GridServerURL);
62 } 70 }
63 71
64 public void Initialise() 72 public void Initialise()
@@ -134,51 +142,30 @@ namespace OpenSim.Grid.MessagingServer.Modules
134 /// <returns></returns> 142 /// <returns></returns>
135 public RegionProfileData RequestRegionInfo(ulong regionHandle) 143 public RegionProfileData RequestRegionInfo(ulong regionHandle)
136 { 144 {
137 RegionProfileData regionProfile = null; 145 uint x = 0, y = 0;
138 try 146 Utils.LongToUInts(regionHandle, out x, out y);
139 { 147 GridRegion region = m_GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
140 Hashtable requestData = new Hashtable();
141 requestData["region_handle"] = regionHandle.ToString();
142 requestData["authkey"] = m_cfg.GridSendKey;
143
144 ArrayList SendParams = new ArrayList();
145 SendParams.Add(requestData);
146 148
147 XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); 149 if (region != null)
150 return GridRegionToRegionProfile(region);
148 151
149 XmlRpcResponse GridResp = GridReq.Send(m_cfg.GridServerURL, 3000); 152 else
150 153 return null;
151 Hashtable responseData = (Hashtable)GridResp.Value; 154 }
152
153 if (responseData.ContainsKey("error"))
154 {
155 m_log.Error("[GRID]: error received from grid server" + responseData["error"]);
156 return null;
157 }
158
159 uint regX = Convert.ToUInt32((string)responseData["region_locx"]);
160 uint regY = Convert.ToUInt32((string)responseData["region_locy"]);
161 string internalIpStr = (string)responseData["sim_ip"];
162
163 regionProfile = new RegionProfileData();
164 regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]);
165 regionProfile.httpServerURI = "http://" + internalIpStr + ":" + regionProfile.httpPort + "/";
166 regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize));
167 regionProfile.regionLocX = regX;
168 regionProfile.regionLocY = regY;
169
170 regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
171 regionProfile.UUID = new UUID((string)responseData["region_UUID"]);
172 regionProfile.regionName = (string)responseData["region_name"];
173 }
174 catch (WebException)
175 {
176 m_log.Error("[GRID]: " +
177 "Region lookup failed for: " + regionHandle.ToString() +
178 " - Is the GridServer down?");
179 }
180 155
181 return regionProfile; 156 private RegionProfileData GridRegionToRegionProfile(GridRegion region)
157 {
158 RegionProfileData rprofile = new RegionProfileData();
159 rprofile.httpPort = region.HttpPort;
160 rprofile.httpServerURI = region.ServerURI;
161 rprofile.regionLocX = (uint)(region.RegionLocX / Constants.RegionSize);
162 rprofile.regionLocY = (uint)(region.RegionLocY / Constants.RegionSize);
163 rprofile.RegionName = region.RegionName;
164 rprofile.ServerHttpPort = region.HttpPort;
165 rprofile.ServerIP = region.ExternalHostName;
166 rprofile.ServerPort = (uint)region.ExternalEndPoint.Port;
167 rprofile.Uuid = region.RegionID;
168 return rprofile;
182 } 169 }
183 170
184 public XmlRpcResponse RegionStartup(XmlRpcRequest request, IPEndPoint remoteClient) 171 public XmlRpcResponse RegionStartup(XmlRpcRequest request, IPEndPoint remoteClient)
diff --git a/OpenSim/Grid/UserServer.Modules/UserLoginService.cs b/OpenSim/Grid/UserServer.Modules/UserLoginService.cs
index 7d0e0de..d46ff9b 100644
--- a/OpenSim/Grid/UserServer.Modules/UserLoginService.cs
+++ b/OpenSim/Grid/UserServer.Modules/UserLoginService.cs
@@ -317,6 +317,7 @@ namespace OpenSim.Grid.UserServer.Modules
317 { 317 {
318 m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); 318 m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName);
319 appearance = new AvatarAppearance(user.ID); 319 appearance = new AvatarAppearance(user.ID);
320 loginParams["appearance"] = appearance.ToHashTable();
320 } 321 }
321 322
322 ArrayList SendParams = new ArrayList(); 323 ArrayList SendParams = new ArrayList();
diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs
index 241af53..33b01e5 100644
--- a/OpenSim/Region/Application/Application.cs
+++ b/OpenSim/Region/Application/Application.cs
@@ -205,13 +205,10 @@ namespace OpenSim
205 Directory.CreateDirectory(m_crashDir); 205 Directory.CreateDirectory(m_crashDir);
206 } 206 }
207 string log = Util.GetUniqueFilename(ex.GetType() + ".txt"); 207 string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
208 StreamWriter m_crashLog = 208 using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
209 new StreamWriter( 209 {
210 Path.Combine(m_crashDir, log) 210 m_crashLog.WriteLine(msg);
211 ); 211 }
212
213 m_crashLog.WriteLine(msg);
214 m_crashLog.Close();
215 212
216 File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true); 213 File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true);
217 } 214 }
diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs
index 468c5d7..6e7a2a0 100644
--- a/OpenSim/Region/Application/OpenSimBase.cs
+++ b/OpenSim/Region/Application/OpenSimBase.cs
@@ -699,7 +699,7 @@ namespace OpenSim
699 public byte[] Handle(string path, Stream request, 699 public byte[] Handle(string path, Stream request,
700 OSHttpRequest httpRequest, OSHttpResponse httpResponse) 700 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
701 { 701 {
702 return Encoding.UTF8.GetBytes("OK"); 702 return Util.UTF8.GetBytes("OK");
703 } 703 }
704 704
705 public string ContentType 705 public string ContentType
@@ -736,7 +736,7 @@ namespace OpenSim
736 public byte[] Handle(string path, Stream request, 736 public byte[] Handle(string path, Stream request,
737 OSHttpRequest httpRequest, OSHttpResponse httpResponse) 737 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
738 { 738 {
739 return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); 739 return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
740 } 740 }
741 741
742 public string ContentType 742 public string ContentType
@@ -777,7 +777,7 @@ namespace OpenSim
777 public byte[] Handle(string path, Stream request, 777 public byte[] Handle(string path, Stream request,
778 OSHttpRequest httpRequest, OSHttpResponse httpResponse) 778 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
779 { 779 {
780 return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); 780 return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
781 } 781 }
782 782
783 public string ContentType 783 public string ContentType
diff --git a/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs b/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
index 5f549b5..19ad0b4 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
@@ -47,69 +47,26 @@ namespace OpenSim.Region.ClientStack.LindenUDP
47 47
48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
49 49
50 public uint m_lastSequence; 50 public uint LastSequence;
51 public float m_requestedPriority; 51 public float Priority;
52 public uint m_requestedPacketNumber; 52 public uint StartPacket;
53 public sbyte m_requestedDiscardLevel; 53 public sbyte DiscardLevel;
54 public UUID m_requestedUUID; 54 public UUID TextureID;
55 public IJ2KDecoder m_j2kDecodeModule; 55 public IJ2KDecoder J2KDecoder;
56 public IAssetService m_assetCache; 56 public IAssetService AssetService;
57 public OpenJPEG.J2KLayerInfo[] m_layers; 57 public OpenJPEG.J2KLayerInfo[] Layers;
58 public bool m_decoded; 58 public bool IsDecoded;
59 public bool m_hasasset; 59 public bool HasAsset;
60 public C5.IPriorityQueueHandle<J2KImage> m_priorityQueueHandle; 60 public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle;
61 61
62 private uint m_packetNumber; 62 private uint m_currentPacket;
63 private bool m_decoderequested; 63 private bool m_decodeRequested;
64 private bool m_asset_requested; 64 private bool m_assetRequested;
65 private bool m_sentinfo; 65 private bool m_sentInfo;
66 private uint m_stopPacket; 66 private uint m_stopPacket;
67 private AssetBase m_asset; 67 private byte[] m_asset;
68 private int m_assetDataLength;
69 private LLImageManager m_imageManager; 68 private LLImageManager m_imageManager;
70 69
71 #region Properties
72
73 public uint m_pPacketNumber
74 {
75 get { return m_packetNumber; }
76 }
77 public uint m_pStopPacketNumber
78 {
79 get { return m_stopPacket; }
80 }
81
82 public byte[] Data
83 {
84 get
85 {
86 if (m_asset != null)
87 return m_asset.Data;
88 else
89 return null;
90 }
91 }
92
93 public ushort TexturePacketCount()
94 {
95 if (!m_decoded)
96 return 0;
97
98 try
99 {
100 return (ushort)(((m_assetDataLength - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
101 }
102 catch (Exception)
103 {
104 // If the asset is missing/destroyed/truncated, we will land
105 // here
106 //
107 return 0;
108 }
109 }
110
111 #endregion Properties
112
113 public J2KImage(LLImageManager imageManager) 70 public J2KImage(LLImageManager imageManager)
114 { 71 {
115 m_imageManager = imageManager; 72 m_imageManager = imageManager;
@@ -117,33 +74,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
117 74
118 public bool SendPackets(LLClientView client, int maxpack) 75 public bool SendPackets(LLClientView client, int maxpack)
119 { 76 {
120 if (m_packetNumber <= m_stopPacket) 77 if (m_currentPacket <= m_stopPacket)
121 { 78 {
122 bool SendMore = true; 79 bool SendMore = true;
123 if (!m_sentinfo || (m_packetNumber == 0)) 80 if (!m_sentInfo || (m_currentPacket == 0))
124 { 81 {
125 if (SendFirstPacket(client)) 82 if (SendFirstPacket(client))
126 { 83 {
127 SendMore = false; 84 SendMore = false;
128 } 85 }
129 m_sentinfo = true; 86 m_sentInfo = true;
130 m_packetNumber++; 87 m_currentPacket++;
131 } 88 }
132 // bool ignoreStop = false; 89 if (m_currentPacket < 2)
133 if (m_packetNumber < 2)
134 { 90 {
135 m_packetNumber = 2; 91 m_currentPacket = 2;
136 } 92 }
137 93
138 int count = 0; 94 int count = 0;
139 while (SendMore && count < maxpack && m_packetNumber <= m_stopPacket) 95 while (SendMore && count < maxpack && m_currentPacket <= m_stopPacket)
140 { 96 {
141 count++; 97 count++;
142 SendMore = SendPacket(client); 98 SendMore = SendPacket(client);
143 m_packetNumber++; 99 m_currentPacket++;
144 } 100 }
145 101
146 if (m_packetNumber > m_stopPacket) 102 if (m_currentPacket > m_stopPacket)
147 return true; 103 return true;
148 } 104 }
149 105
@@ -156,68 +112,76 @@ namespace OpenSim.Region.ClientStack.LindenUDP
156 //and assign the real discardLevel and packetNumber 112 //and assign the real discardLevel and packetNumber
157 //assuming of course that the connected client might be bonkers 113 //assuming of course that the connected client might be bonkers
158 114
159 if (!m_hasasset) 115 if (!HasAsset)
160 { 116 {
161 if (!m_asset_requested) 117 if (!m_assetRequested)
162 { 118 {
163 m_asset_requested = true; 119 m_assetRequested = true;
164 m_assetCache.Get(m_requestedUUID.ToString(), this, AssetReceived); 120 AssetService.Get(TextureID.ToString(), this, AssetReceived);
165 } 121 }
166 } 122 }
167 else 123 else
168 { 124 {
169 if (!m_decoded) 125 if (!IsDecoded)
170 { 126 {
171 //We need to decode the requested image first 127 //We need to decode the requested image first
172 if (!m_decoderequested) 128 if (!m_decodeRequested)
173 { 129 {
174 //Request decode 130 //Request decode
175 m_decoderequested = true; 131 m_decodeRequested = true;
176 // Do we have a jpeg decoder? 132 // Do we have a jpeg decoder?
177 if (m_j2kDecodeModule != null) 133 if (J2KDecoder != null)
178 { 134 {
179 if (Data == null) 135 if (m_asset == null)
180 { 136 {
181 J2KDecodedCallback(m_requestedUUID, new OpenJPEG.J2KLayerInfo[0]); 137 J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
182 } 138 }
183 else 139 else
184 { 140 {
185 // Send it off to the jpeg decoder 141 // Send it off to the jpeg decoder
186 m_j2kDecodeModule.BeginDecode(m_requestedUUID, Data, J2KDecodedCallback); 142 J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback);
187 } 143 }
188 144
189 } 145 }
190 else 146 else
191 { 147 {
192 J2KDecodedCallback(m_requestedUUID, new OpenJPEG.J2KLayerInfo[0]); 148 J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
193 } 149 }
194 } 150 }
195 } 151 }
196 else 152 else
197 { 153 {
198 // Check for missing image asset data 154 // Check for missing image asset data
199 if (m_asset == null || m_asset.Data == null) 155 if (m_asset == null)
200 { 156 {
201 // FIXME: 157 m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer");
202 m_packetNumber = m_stopPacket; 158 m_currentPacket = m_stopPacket;
203 return; 159 return;
204 } 160 }
205 161
206 if (m_requestedDiscardLevel >= 0 || m_stopPacket == 0) 162 if (DiscardLevel >= 0 || m_stopPacket == 0)
207 { 163 {
208 int maxDiscardLevel = Math.Max(0, m_layers.Length - 1); 164 // This shouldn't happen, but if it does, we really can't proceed
165 if (Layers == null)
166 {
167 m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer");
168 m_currentPacket = m_stopPacket;
169 return;
170 }
171
172 int maxDiscardLevel = Math.Max(0, Layers.Length - 1);
209 173
210 // Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel 174 // Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel
211 if (m_requestedDiscardLevel < 0 && m_stopPacket == 0) 175 if (DiscardLevel < 0 && m_stopPacket == 0)
212 m_requestedDiscardLevel = (sbyte)maxDiscardLevel; 176 DiscardLevel = (sbyte)maxDiscardLevel;
213 177
214 // Clamp at the highest discard level 178 // Clamp at the highest discard level
215 m_requestedDiscardLevel = (sbyte)Math.Min(m_requestedDiscardLevel, maxDiscardLevel); 179 DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel);
216 180
217 //Calculate the m_stopPacket 181 //Calculate the m_stopPacket
218 if (m_layers.Length > 0) 182 if (Layers.Length > 0)
219 { 183 {
220 m_stopPacket = (uint)GetPacketForBytePosition(m_layers[(m_layers.Length - 1) - m_requestedDiscardLevel].End); 184 m_stopPacket = (uint)GetPacketForBytePosition(Layers[(Layers.Length - 1) - DiscardLevel].End);
221 //I don't know why, but the viewer seems to expect the final packet if the file 185 //I don't know why, but the viewer seems to expect the final packet if the file
222 //is just one packet bigger. 186 //is just one packet bigger.
223 if (TexturePacketCount() == m_stopPacket + 1) 187 if (TexturePacketCount() == m_stopPacket + 1)
@@ -230,32 +194,65 @@ namespace OpenSim.Region.ClientStack.LindenUDP
230 m_stopPacket = TexturePacketCount(); 194 m_stopPacket = TexturePacketCount();
231 } 195 }
232 196
233 m_packetNumber = m_requestedPacketNumber; 197 m_currentPacket = StartPacket;
234 } 198 }
235 199
236 if (m_imageManager.Client.PacketHandler.GetQueueCount(ThrottleOutPacketType.Texture) == 0) 200 if ((m_imageManager != null) && (m_imageManager.Client != null) && (m_imageManager.Client.PacketHandler != null))
237 { 201 if (m_imageManager.Client.PacketHandler.GetQueueCount(ThrottleOutPacketType.Texture) == 0)
238 //m_log.Debug("No textures queued, sending one packet to kickstart it"); 202 {
239 SendPacket(m_imageManager.Client); 203 //m_log.Debug("No textures queued, sending one packet to kickstart it");
240 } 204 SendPacket(m_imageManager.Client);
205 }
241 } 206 }
242 } 207 }
243 } 208 }
244 209
210 private bool SendFirstPacket(LLClientView client)
211 {
212 if (m_asset == null)
213 {
214 m_log.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID);
215 client.SendImageNotFound(TextureID);
216 return true;
217 }
218 else if (m_asset.Length <= FIRST_PACKET_SIZE)
219 {
220 // We have less then one packet's worth of data
221 client.SendImageFirstPart(1, TextureID, (uint)m_asset.Length, m_asset, 2);
222 m_stopPacket = 0;
223 return true;
224 }
225 else
226 {
227 // This is going to be a multi-packet texture download
228 byte[] firstImageData = new byte[FIRST_PACKET_SIZE];
229
230 try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); }
231 catch (Exception)
232 {
233 m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length);
234 return true;
235 }
236
237 client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint)m_asset.Length, firstImageData, (byte)ImageCodec.J2C);
238 }
239 return false;
240 }
241
245 private bool SendPacket(LLClientView client) 242 private bool SendPacket(LLClientView client)
246 { 243 {
247 bool complete = false; 244 bool complete = false;
248 int imagePacketSize = ((int)m_packetNumber == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE; 245 int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;
249 246
250 try 247 try
251 { 248 {
252 if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_assetDataLength) 249 if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length)
253 { 250 {
254 imagePacketSize = LastPacketSize(); 251 imagePacketSize = LastPacketSize();
255 complete = true; 252 complete = true;
256 if ((CurrentBytePosition() + imagePacketSize) > m_assetDataLength) 253 if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length)
257 { 254 {
258 imagePacketSize = m_assetDataLength - CurrentBytePosition(); 255 imagePacketSize = m_asset.Length - CurrentBytePosition();
259 complete = true; 256 complete = true;
260 } 257 }
261 } 258 }
@@ -266,27 +263,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP
266 if (imagePacketSize > 0) 263 if (imagePacketSize > 0)
267 { 264 {
268 byte[] imageData = new byte[imagePacketSize]; 265 byte[] imageData = new byte[imagePacketSize];
269 try 266 int currentPosition = CurrentBytePosition();
270 { 267
271 Buffer.BlockCopy(m_asset.Data, CurrentBytePosition(), imageData, 0, imagePacketSize); 268 try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); }
272 }
273 catch (Exception e) 269 catch (Exception e)
274 { 270 {
275 m_log.Error("Error copying texture block. Out of memory? imagePacketSize was " + imagePacketSize.ToString() + " on packet " + m_packetNumber.ToString() + " out of " + m_stopPacket.ToString() + ". Exception: " + e.ToString()); 271 m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}",
272 TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message);
276 return false; 273 return false;
277 } 274 }
278 275
279 //Send the packet 276 //Send the packet
280 client.SendImageNextPart((ushort)(m_packetNumber - 1), m_requestedUUID, imageData); 277 client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData);
281 }
282 if (complete)
283 {
284 return false;
285 }
286 else
287 {
288 return true;
289 } 278 }
279
280 return !complete;
290 } 281 }
291 catch (Exception) 282 catch (Exception)
292 { 283 {
@@ -294,6 +285,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
294 } 285 }
295 } 286 }
296 287
288 private ushort TexturePacketCount()
289 {
290 if (!IsDecoded)
291 return 0;
292
293 if (m_asset == null)
294 return 0;
295
296 if (m_asset.Length <= FIRST_PACKET_SIZE)
297 return 1;
298
299 return (ushort)(((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
300 }
301
297 private int GetPacketForBytePosition(int bytePosition) 302 private int GetPacketForBytePosition(int bytePosition)
298 { 303 {
299 return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1; 304 return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1;
@@ -301,9 +306,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
301 306
302 private int LastPacketSize() 307 private int LastPacketSize()
303 { 308 {
304 if (m_packetNumber == 1) 309 if (m_currentPacket == 1)
305 return m_assetDataLength; 310 return m_asset.Length;
306 int lastsize = (m_assetDataLength - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE; 311 int lastsize = (m_asset.Length - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE;
307 //If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary 312 //If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary
308 if (lastsize == 0) 313 if (lastsize == 0)
309 { 314 {
@@ -314,12 +319,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
314 319
315 private int CurrentBytePosition() 320 private int CurrentBytePosition()
316 { 321 {
317 if (m_packetNumber == 0) 322 if (m_currentPacket == 0)
318 return 0; 323 return 0;
319 if (m_packetNumber == 1) 324 if (m_currentPacket == 1)
320 return FIRST_PACKET_SIZE; 325 return FIRST_PACKET_SIZE;
321 326
322 int result = FIRST_PACKET_SIZE + ((int)m_packetNumber - 2) * IMAGE_PACKET_SIZE; 327 int result = FIRST_PACKET_SIZE + ((int)m_currentPacket - 2) * IMAGE_PACKET_SIZE;
323 if (result < 0) 328 if (result < 0)
324 { 329 {
325 result = FIRST_PACKET_SIZE; 330 result = FIRST_PACKET_SIZE;
@@ -327,68 +332,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
327 return result; 332 return result;
328 } 333 }
329 334
330 private bool SendFirstPacket(LLClientView client)
331 {
332 // this means we don't have
333 if (Data == null)
334 {
335 client.SendImageNotFound(m_requestedUUID);
336 m_log.WarnFormat("[TEXTURE]: Got null Data element on a asset {0}.. and the missing image Data property is also null", m_requestedUUID);
337 return true;
338 }
339 // Do we have less then 1 packet's worth of data?
340 else if (m_assetDataLength <= FIRST_PACKET_SIZE)
341 {
342 // Send only 1 packet
343 client.SendImageFirstPart(1, m_requestedUUID, (uint)m_assetDataLength, m_asset.Data, 2);
344 m_stopPacket = 0;
345 return true;
346 }
347 else
348 {
349 byte[] firstImageData = new byte[FIRST_PACKET_SIZE];
350 try
351 {
352 Buffer.BlockCopy(m_asset.Data, 0, firstImageData, 0, (int)FIRST_PACKET_SIZE);
353 client.SendImageFirstPart(TexturePacketCount(), m_requestedUUID, (uint)m_assetDataLength, firstImageData, 2);
354 }
355 catch (Exception)
356 {
357 m_log.Error("Texture block copy failed. Possibly out of memory?");
358 return true;
359 }
360 }
361 return false;
362 }
363
364 private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers) 335 private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers)
365 { 336 {
366 m_layers = layers; 337 Layers = layers;
367 m_decoded = true; 338 IsDecoded = true;
368 RunUpdate(); 339 RunUpdate();
369 } 340 }
370 341
371 private void AssetDataCallback(UUID AssetID, AssetBase asset) 342 private void AssetDataCallback(UUID AssetID, AssetBase asset)
372 { 343 {
373 m_hasasset = true; 344 HasAsset = true;
374 345
375 if (asset == null || asset.Data == null) 346 if (asset == null || asset.Data == null)
376 { 347 {
377 if (m_imageManager.MissingImage != null) 348 if (m_imageManager.MissingImage != null)
378 { 349 {
379 m_asset = m_imageManager.MissingImage; 350 m_asset = m_imageManager.MissingImage.Data;
380 m_assetDataLength = m_asset.Data.Length;
381 } 351 }
382 else 352 else
383 { 353 {
384 m_asset = null; 354 m_asset = null;
385 m_decoded = true; 355 IsDecoded = true;
386 } 356 }
387 } 357 }
388 else 358 else
389 { 359 {
390 m_asset = asset; 360 m_asset = asset.Data;
391 m_assetDataLength = m_asset.Data.Length;
392 } 361 }
393 362
394 RunUpdate(); 363 RunUpdate();
diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs
index 3b43771..0052729 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs
@@ -4751,7 +4751,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
4751 { 4751 {
4752 Hashtable mp = (Hashtable)simMapProfiles[iii]; 4752 Hashtable mp = (Hashtable)simMapProfiles[iii];
4753 mbReply.Data[iii] = new MapBlockReplyPacket.DataBlock(); 4753 mbReply.Data[iii] = new MapBlockReplyPacket.DataBlock();
4754 mbReply.Data[iii].Name = System.Text.Encoding.UTF8.GetBytes((string)mp["name"]); 4754 mbReply.Data[iii].Name = Util.UTF8.GetBytes((string)mp["name"]);
4755 mbReply.Data[iii].Access = System.Convert.ToByte(mp["access"]); 4755 mbReply.Data[iii].Access = System.Convert.ToByte(mp["access"]);
4756 mbReply.Data[iii].Agents = System.Convert.ToByte(mp["agents"]); 4756 mbReply.Data[iii].Agents = System.Convert.ToByte(mp["agents"]);
4757 mbReply.Data[iii].MapImageID = new UUID((string)mp["map-image-id"]); 4757 mbReply.Data[iii].MapImageID = new UUID((string)mp["map-image-id"]);
@@ -7341,7 +7341,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
7341 } 7341 }
7342 #endregion 7342 #endregion
7343 7343
7344 string mapName = Encoding.UTF8.GetString(map.NameData.Name, 0, 7344 string mapName = Util.UTF8.GetString(map.NameData.Name, 0,
7345 map.NameData.Name.Length - 1); 7345 map.NameData.Name.Length - 1);
7346 handlerMapNameRequest = OnMapNameRequest; 7346 handlerMapNameRequest = OnMapNameRequest;
7347 if (handlerMapNameRequest != null) 7347 if (handlerMapNameRequest != null)
diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLImageManager.cs b/OpenSim/Region/ClientStack/LindenUDP/LLImageManager.cs
index a484fdf..2120d33 100644
--- a/OpenSim/Region/ClientStack/LindenUDP/LLImageManager.cs
+++ b/OpenSim/Region/ClientStack/LindenUDP/LLImageManager.cs
@@ -45,48 +45,43 @@ namespace OpenSim.Region.ClientStack.LindenUDP
45 { 45 {
46 public int Compare(J2KImage x, J2KImage y) 46 public int Compare(J2KImage x, J2KImage y)
47 { 47 {
48 return x.m_requestedPriority.CompareTo(y.m_requestedPriority); 48 return x.Priority.CompareTo(y.Priority);
49 } 49 }
50 } 50 }
51 51
52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 52 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
53 private bool m_shuttingdown = false; 53 private bool m_shuttingdown;
54 private long m_lastloopprocessed = 0; 54 private long m_lastloopprocessed;
55 private AssetBase m_missingImage = null; 55 private AssetBase m_missingImage;
56
57 private LLClientView m_client; //Client we're assigned to 56 private LLClientView m_client; //Client we're assigned to
58 private IAssetService m_assetCache; //Asset Cache 57 private IAssetService m_assetCache; //Asset Cache
59 private IJ2KDecoder m_j2kDecodeModule; //Our J2K module 58 private IJ2KDecoder m_j2kDecodeModule; //Our J2K module
60 private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer()); 59 private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());
60 private object m_syncRoot = new object();
61
62 public LLClientView Client { get { return m_client; } }
63 public AssetBase MissingImage { get { return m_missingImage; } }
61 64
62 public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule) 65 public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
63 { 66 {
64 m_client = client; 67 m_client = client;
65 m_assetCache = pAssetCache; 68 m_assetCache = pAssetCache;
69
66 if (pAssetCache != null) 70 if (pAssetCache != null)
67 m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f"); 71 m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
68 else 72
69 m_log.Error("[ClientView] - couldn't set missing image asset, falling back to missing image packet. This is known to crash the client"); 73 if (m_missingImage == null)
74 m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
70 75
71 m_j2kDecodeModule = pJ2kDecodeModule; 76 m_j2kDecodeModule = pJ2kDecodeModule;
72 } 77 }
73 78
74 public LLClientView Client 79 /// <summary>
75 { 80 /// Handles an incoming texture request or update to an existing texture request
76 get { return m_client; } 81 /// </summary>
77 } 82 /// <param name="newRequest"></param>
78
79 public AssetBase MissingImage
80 {
81 get { return m_missingImage; }
82 }
83
84 public void EnqueueReq(TextureRequestArgs newRequest) 83 public void EnqueueReq(TextureRequestArgs newRequest)
85 { 84 {
86 //newRequest is the properties of our new texture fetch request.
87 //Basically, here is where we queue up "new" requests..
88 // .. or modify existing requests to suit.
89
90 //Make sure we're not shutting down.. 85 //Make sure we're not shutting down..
91 if (!m_shuttingdown) 86 if (!m_shuttingdown)
92 { 87 {
@@ -94,7 +89,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
94 89
95 // Do a linear search for this texture download 90 // Do a linear search for this texture download
96 lock (m_priorityQueue) 91 lock (m_priorityQueue)
97 m_priorityQueue.Find(delegate(J2KImage img) { return img.m_requestedUUID == newRequest.RequestedAssetID; }, out imgrequest); 92 m_priorityQueue.Find(delegate(J2KImage img) { return img.TextureID == newRequest.RequestedAssetID; }, out imgrequest);
98 93
99 if (imgrequest != null) 94 if (imgrequest != null)
100 { 95 {
@@ -105,7 +100,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
105 try 100 try
106 { 101 {
107 lock (m_priorityQueue) 102 lock (m_priorityQueue)
108 m_priorityQueue.Delete(imgrequest.m_priorityQueueHandle); 103 m_priorityQueue.Delete(imgrequest.PriorityQueueHandle);
109 } 104 }
110 catch (Exception) { } 105 catch (Exception) { }
111 } 106 }
@@ -116,30 +111,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
116 111
117 //Check the packet sequence to make sure this isn't older than 112 //Check the packet sequence to make sure this isn't older than
118 //one we've already received 113 //one we've already received
119 if (newRequest.requestSequence > imgrequest.m_lastSequence) 114 if (newRequest.requestSequence > imgrequest.LastSequence)
120 { 115 {
121 //Update the sequence number of the last RequestImage packet 116 //Update the sequence number of the last RequestImage packet
122 imgrequest.m_lastSequence = newRequest.requestSequence; 117 imgrequest.LastSequence = newRequest.requestSequence;
123 118
124 //Update the requested discard level 119 //Update the requested discard level
125 imgrequest.m_requestedDiscardLevel = newRequest.DiscardLevel; 120 imgrequest.DiscardLevel = newRequest.DiscardLevel;
126 121
127 //Update the requested packet number 122 //Update the requested packet number
128 imgrequest.m_requestedPacketNumber = newRequest.PacketNumber; 123 imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
129 124
130 //Update the requested priority 125 //Update the requested priority
131 imgrequest.m_requestedPriority = newRequest.Priority; 126 imgrequest.Priority = newRequest.Priority;
132 try 127 UpdateImageInQueue(imgrequest);
133 {
134 lock (m_priorityQueue)
135 m_priorityQueue.Replace(imgrequest.m_priorityQueueHandle, imgrequest);
136 }
137 catch (Exception)
138 {
139 imgrequest.m_priorityQueueHandle = null;
140 lock (m_priorityQueue)
141 m_priorityQueue.Add(ref imgrequest.m_priorityQueueHandle, imgrequest);
142 }
143 128
144 //Run an update 129 //Run an update
145 imgrequest.RunUpdate(); 130 imgrequest.RunUpdate();
@@ -159,31 +144,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP
159 // newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority); 144 // newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
160 145
161 imgrequest = new J2KImage(this); 146 imgrequest = new J2KImage(this);
162 147 imgrequest.J2KDecoder = m_j2kDecodeModule;
163 //Assign our decoder module 148 imgrequest.AssetService = m_assetCache;
164 imgrequest.m_j2kDecodeModule = m_j2kDecodeModule; 149 imgrequest.DiscardLevel = newRequest.DiscardLevel;
165 150 imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
166 //Assign our asset cache module 151 imgrequest.Priority = newRequest.Priority;
167 imgrequest.m_assetCache = m_assetCache; 152 imgrequest.TextureID = newRequest.RequestedAssetID;
168 153 imgrequest.Priority = newRequest.Priority;
169 //Assign the requested discard level
170 imgrequest.m_requestedDiscardLevel = newRequest.DiscardLevel;
171
172 //Assign the requested packet number
173 imgrequest.m_requestedPacketNumber = newRequest.PacketNumber;
174
175 //Assign the requested priority
176 imgrequest.m_requestedPriority = newRequest.Priority;
177
178 //Assign the asset uuid
179 imgrequest.m_requestedUUID = newRequest.RequestedAssetID;
180
181 //Assign the requested priority
182 imgrequest.m_requestedPriority = newRequest.Priority;
183 154
184 //Add this download to the priority queue 155 //Add this download to the priority queue
185 lock (m_priorityQueue) 156 AddImageToQueue(imgrequest);
186 m_priorityQueue.Add(ref imgrequest.m_priorityQueueHandle, imgrequest);
187 157
188 //Run an update 158 //Run an update
189 imgrequest.RunUpdate(); 159 imgrequest.RunUpdate();
@@ -194,105 +164,99 @@ namespace OpenSim.Region.ClientStack.LindenUDP
194 164
195 public bool ProcessImageQueue(int count, int maxpack) 165 public bool ProcessImageQueue(int count, int maxpack)
196 { 166 {
197 lock (this) 167 J2KImage imagereq;
198 { 168 int numCollected = 0;
199 //count is the number of textures we want to process in one go.
200 //As part of this class re-write, that number will probably rise
201 //since we're processing in a more efficient manner.
202
203 // this can happen during Close()
204 if (m_client == null)
205 return false;
206
207 int numCollected = 0;
208
209 //Calculate our threshold
210 int threshold;
211 if (m_lastloopprocessed == 0)
212 {
213 if (m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null || m_client.PacketHandler.PacketQueue.TextureThrottle == null)
214 return false;
215 //This is decent for a semi fast machine, but we'll calculate it more accurately based on time below
216 threshold = m_client.PacketHandler.PacketQueue.TextureThrottle.Current / 6300;
217 m_lastloopprocessed = DateTime.Now.Ticks;
218 }
219 else
220 {
221 double throttleseconds = ((double)DateTime.Now.Ticks - (double)m_lastloopprocessed) / (double)TimeSpan.TicksPerSecond;
222 throttleseconds = throttleseconds * m_client.PacketHandler.PacketQueue.TextureThrottle.Current;
223
224 //Average of 1000 bytes per packet
225 throttleseconds = throttleseconds / 1000;
226
227 //Safe-zone multiplier of 2.0
228 threshold = (int)(throttleseconds * 2.0);
229 m_lastloopprocessed = DateTime.Now.Ticks;
230
231 }
232 169
233 if (m_client.PacketHandler == null) 170 //lock (m_syncRoot)
234 return false; 171 //{
172 m_lastloopprocessed = DateTime.Now.Ticks;
235 173
236 if (m_client.PacketHandler.PacketQueue == null) 174 // This can happen during Close()
175 if (m_client == null || m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null)
237 return false; 176 return false;
238 177
239 if (threshold < 10) 178 while ((imagereq = GetHighestPriorityImage()) != null)
240 threshold = 10;
241
242 //Uncomment this to see what the texture stack is doing
243 //m_log.Debug("Queue: " + m_client.PacketHandler.PacketQueue.getQueueCount(ThrottleOutPacketType.Texture).ToString() + " Threshold: " + threshold.ToString() + " outstanding: " + m_outstandingtextures.ToString());
244 if (true) //m_client.PacketHandler.PacketQueue.GetQueueCount(ThrottleOutPacketType.Texture) < threshold)
245 { 179 {
246 while (m_priorityQueue.Count > 0) 180 if (imagereq.IsDecoded == true)
247 { 181 {
248 J2KImage imagereq = null; 182 ++numCollected;
249 lock (m_priorityQueue)
250 imagereq = m_priorityQueue.FindMax();
251 183
252 if (imagereq.m_decoded == true) 184 if (imagereq.SendPackets(m_client, maxpack))
253 { 185 {
254 // we need to test this here now that we are dropping assets 186 // Send complete. Destroy any knowledge of this transfer
255 if (!imagereq.m_hasasset) 187 RemoveImageFromQueue(imagereq);
256 {
257 m_log.WarnFormat("[LLIMAGE MANAGER]: Re-requesting the image asset {0}", imagereq.m_requestedUUID);
258 imagereq.RunUpdate();
259 continue;
260 }
261
262 ++numCollected;
263
264 //SendPackets will send up to ten packets per cycle
265 if (imagereq.SendPackets(m_client, maxpack))
266 {
267 // Send complete. Destroy any knowledge of this transfer
268 try
269 {
270 lock (m_priorityQueue)
271 m_priorityQueue.Delete(imagereq.m_priorityQueueHandle);
272 }
273 catch (Exception) { }
274 }
275 } 188 }
276
277 if (numCollected == count)
278 break;
279 } 189 }
190
191 if (numCollected == count)
192 break;
280 } 193 }
194 //}
281 195
282 return m_priorityQueue.Count > 0; 196 return m_priorityQueue.Count > 0;
283 }
284 } 197 }
285 198
286 //Faux destructor 199 //Faux destructor
287 public void Close() 200 public void Close()
288 { 201 {
289
290 m_shuttingdown = true; 202 m_shuttingdown = true;
291 m_j2kDecodeModule = null; 203 m_j2kDecodeModule = null;
292 m_assetCache = null; 204 m_assetCache = null;
293 m_client = null; 205 m_client = null;
294 } 206 }
295 207
208 #region Priority Queue Helpers
209
210 J2KImage GetHighestPriorityImage()
211 {
212 J2KImage image = null;
213
214 lock (m_priorityQueue)
215 {
216
217 if (m_priorityQueue.Count > 0)
218 {
219 try
220 {
221 image = m_priorityQueue.FindMax();
222 }
223 catch (Exception) { }
224 }
225 }
226 return image;
227 }
228
229 void AddImageToQueue(J2KImage image)
230 {
231 image.PriorityQueueHandle = null;
232
233 lock (m_priorityQueue)
234 m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
235 }
236
237 void RemoveImageFromQueue(J2KImage image)
238 {
239 try
240 {
241 lock (m_priorityQueue)
242 m_priorityQueue.Delete(image.PriorityQueueHandle);
243 }
244 catch (Exception) { }
245 }
246
247 void UpdateImageInQueue(J2KImage image)
248 {
249 lock (m_priorityQueue)
250 {
251 try { m_priorityQueue.Replace(image.PriorityQueueHandle, image); }
252 catch (Exception)
253 {
254 image.PriorityQueueHandle = null;
255 m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
256 }
257 }
258 }
296 259
260 #endregion Priority Queue Helpers
297 } 261 }
298} 262}
diff --git a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
index a0f359b..7456e8c 100644
--- a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
+++ b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
@@ -257,7 +257,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
257 stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); 257 stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd);
258 } 258 }
259 259
260 layerDecodeAsset.Data = Encoding.UTF8.GetBytes(stringResult.ToString()); 260 layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
261 261
262 #endregion Serialize Layer Data 262 #endregion Serialize Layer Data
263 263
@@ -280,7 +280,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
280 { 280 {
281 #region Deserialize Layer Data 281 #region Deserialize Layer Data
282 282
283 string readResult = Encoding.UTF8.GetString(layerDecodeAsset.Data); 283 string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
284 string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); 284 string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
285 285
286 if (lines.Length == 0) 286 if (lines.Length == 0)
diff --git a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
index 817e0d4..c0bb70c 100644
--- a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
+++ b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
@@ -323,13 +323,13 @@ namespace Flotsam.RegionModules.AssetCache
323 string filename = GetFileName(id); 323 string filename = GetFileName(id);
324 if (File.Exists(filename)) 324 if (File.Exists(filename))
325 { 325 {
326 FileStream stream = null;
326 try 327 try
327 { 328 {
328 FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read); 329 stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
329 BinaryFormatter bformatter = new BinaryFormatter(); 330 BinaryFormatter bformatter = new BinaryFormatter();
330 331
331 asset = (AssetBase)bformatter.Deserialize(stream); 332 asset = (AssetBase)bformatter.Deserialize(stream);
332 stream.Close();
333 333
334 UpdateMemoryCache(id, asset); 334 UpdateMemoryCache(id, asset);
335 335
@@ -349,6 +349,11 @@ namespace Flotsam.RegionModules.AssetCache
349 { 349 {
350 LogException(e); 350 LogException(e);
351 } 351 }
352 finally
353 {
354 if (stream != null)
355 stream.Close();
356 }
352 } 357 }
353 358
354 359
@@ -493,19 +498,20 @@ namespace Flotsam.RegionModules.AssetCache
493 498
494 private void WriteFileCache(string filename, AssetBase asset) 499 private void WriteFileCache(string filename, AssetBase asset)
495 { 500 {
501 Stream stream = null;
502 // Make sure the target cache directory exists
503 string directory = Path.GetDirectoryName(filename);
504 // Write file first to a temp name, so that it doesn't look
505 // like it's already cached while it's still writing.
506 string tempname = Path.Combine(directory, Path.GetRandomFileName());
496 try 507 try
497 { 508 {
498 // Make sure the target cache directory exists
499 string directory = Path.GetDirectoryName(filename);
500 if (!Directory.Exists(directory)) 509 if (!Directory.Exists(directory))
501 { 510 {
502 Directory.CreateDirectory(directory); 511 Directory.CreateDirectory(directory);
503 } 512 }
504 513
505 // Write file first to a temp name, so that it doesn't look 514 stream = File.Open(tempname, FileMode.Create);
506 // like it's already cached while it's still writing.
507 string tempname = Path.Combine(directory, Path.GetRandomFileName());
508 Stream stream = File.Open(tempname, FileMode.Create);
509 BinaryFormatter bformatter = new BinaryFormatter(); 515 BinaryFormatter bformatter = new BinaryFormatter();
510 bformatter.Serialize(stream, asset); 516 bformatter.Serialize(stream, asset);
511 stream.Close(); 517 stream.Close();
@@ -522,6 +528,9 @@ namespace Flotsam.RegionModules.AssetCache
522 } 528 }
523 finally 529 finally
524 { 530 {
531 if (stream != null)
532 stream.Close();
533
525 // Even if the write fails with an exception, we need to make sure 534 // Even if the write fails with an exception, we need to make sure
526 // that we release the lock on that file, otherwise it'll never get 535 // that we release the lock on that file, otherwise it'll never get
527 // cached 536 // cached
diff --git a/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs b/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs
index 50d7c97..45e724d 100644
--- a/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs
+++ b/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs
@@ -367,7 +367,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
367 // Encode outbound data 367 // Encode outbound data
368 if (OutboundBody.Length > 0) 368 if (OutboundBody.Length > 0)
369 { 369 {
370 byte[] data = Encoding.UTF8.GetBytes(OutboundBody); 370 byte[] data = Util.UTF8.GetBytes(OutboundBody);
371 371
372 Request.ContentLength = data.Length; 372 Request.ContentLength = data.Length;
373 Stream bstream = Request.GetRequestStream(); 373 Stream bstream = Request.GetRequestStream();
@@ -390,7 +390,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
390 if (count != 0) 390 if (count != 0)
391 { 391 {
392 // translate from bytes to ASCII text 392 // translate from bytes to ASCII text
393 tempString = Encoding.UTF8.GetString(buf, 0, count); 393 tempString = Util.UTF8.GetString(buf, 0, count);
394 394
395 // continue building the string 395 // continue building the string
396 sb.Append(tempString); 396 sb.Append(tempString);
diff --git a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
index 040d0a3..901144a 100644
--- a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
+++ b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
@@ -397,10 +397,15 @@ namespace OpenSim.Region.CoreModules.World.Permissions
397 // with the powers requested (powers = 0 for no powers check) 397 // with the powers requested (powers = 0 for no powers check)
398 protected bool IsGroupMember(UUID groupID, UUID userID, ulong powers) 398 protected bool IsGroupMember(UUID groupID, UUID userID, ulong powers)
399 { 399 {
400 IClientAPI client = m_scene.GetScenePresence(userID).ControllingClient; 400 ScenePresence sp = m_scene.GetScenePresence(userID);
401 401 if (sp != null)
402 return ((groupID == client.ActiveGroupId) && (client.ActiveGroupPowers != 0) && 402 {
403 ((powers == 0) || ((client.ActiveGroupPowers & powers) == powers))); 403 IClientAPI client = sp.ControllingClient;
404
405 return ((groupID == client.ActiveGroupId) && (client.ActiveGroupPowers != 0) &&
406 ((powers == 0) || ((client.ActiveGroupPowers & powers) == powers)));
407 }
408 return false;
404 } 409 }
405 410
406 /// <summary> 411 /// <summary>
@@ -576,9 +581,12 @@ namespace OpenSim.Region.CoreModules.World.Permissions
576 return objectOwnerMask; 581 return objectOwnerMask;
577 } 582 }
578 583
584 if ((objectOwnerMask & (uint)PermissionMask.Transfer) != 0 && task.ObjectSaleType != 0)
585 objectEveryoneMask |= (uint)PrimFlags.ObjectTransfer;
586
579 // Group permissions 587 // Group permissions
580 if ((task.GroupID != UUID.Zero) && IsGroupMember(task.GroupID, user, 0)) 588 if ((task.GroupID != UUID.Zero) && IsGroupMember(task.GroupID, user, 0))
581 return objectGroupMask; 589 return objectGroupMask | objectEveryoneMask;
582 590
583 return objectEveryoneMask; 591 return objectEveryoneMask;
584 } 592 }
diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs
index 3eb7cd2..a70ef13 100644
--- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs
+++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs
@@ -36,10 +36,10 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
36 { 36 {
37 public struct HeightmapLookupValue : IComparable<HeightmapLookupValue> 37 public struct HeightmapLookupValue : IComparable<HeightmapLookupValue>
38 { 38 {
39 public int Index; 39 public ushort Index;
40 public double Value; 40 public float Value;
41 41
42 public HeightmapLookupValue(int index, double value) 42 public HeightmapLookupValue(ushort index, float value)
43 { 43 {
44 Index = index; 44 Index = index;
45 Value = value; 45 Value = value;
@@ -62,7 +62,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
62 { 62 {
63 for (int j = 0; j < 256; j++) 63 for (int j = 0; j < 256; j++)
64 { 64 {
65 LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue(i + (j * 256), ((double)i * ((double)j / 128.0d))); 65 LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue((ushort)(i + (j * 256)), (float)((double)i * ((double)j / 128.0d)));
66 } 66 }
67 } 67 }
68 Array.Sort<HeightmapLookupValue>(LookupHeightTable); 68 Array.Sort<HeightmapLookupValue>(LookupHeightTable);
@@ -196,7 +196,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
196 196
197 // The lookup table is pre-sorted, so we either find an exact match or 197 // The lookup table is pre-sorted, so we either find an exact match or
198 // the next closest (smaller) match with a binary search 198 // the next closest (smaller) match with a binary search
199 index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, t)); 199 index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, (float)t));
200 if (index < 0) 200 if (index < 0)
201 index = ~index - 1; 201 index = ~index - 1;
202 202
diff --git a/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs b/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs
index 080bd5a..4df9094 100644
--- a/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs
+++ b/OpenSim/Region/DataSnapshot/DataSnapshotManager.cs
@@ -352,7 +352,7 @@ namespace OpenSim.Region.DataSnapshot
352 m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace); 352 m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace);
353 } 353 }
354 // This is not quite working, so... 354 // This is not quite working, so...
355 // string responseStr = Encoding.UTF8.GetString(response); 355 // string responseStr = Util.UTF8.GetString(response);
356 m_log.Info("[DATASNAPSHOT]: data service notified: " + url); 356 m_log.Info("[DATASNAPSHOT]: data service notified: " + url);
357 } 357 }
358 358
diff --git a/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs b/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs
index 73f918e..e9660b1 100644
--- a/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs
+++ b/OpenSim/Region/Framework/Scenes/RegionStatsHandler.cs
@@ -73,7 +73,7 @@ namespace OpenSim.Region.Framework.Scenes
73 73
74 public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) 74 public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
75 { 75 {
76 return Encoding.UTF8.GetBytes(Report()); 76 return Util.UTF8.GetBytes(Report());
77 } 77 }
78 78
79 public string ContentType 79 public string ContentType
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index b4cfc48..23a7021 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
@@ -1332,7 +1332,8 @@ if (m_shape != null) {
1332 bool RigidBody = isPhysical && !isPhantom; 1332 bool RigidBody = isPhysical && !isPhantom;
1333 1333
1334 // The only time the physics scene shouldn't know about the prim is if it's phantom or an attachment, which is phantom by definition 1334 // The only time the physics scene shouldn't know about the prim is if it's phantom or an attachment, which is phantom by definition
1335 if (!isPhantom && !IsAttachment) 1335 // or flexible
1336 if (!isPhantom && !IsAttachment && !(Shape.PathCurve == (byte) Extrusion.Flexible))
1336 { 1337 {
1337 PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( 1338 PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape(
1338 Name, 1339 Name,
@@ -3395,8 +3396,8 @@ if (m_shape != null) {
3395 } 3396 }
3396 } 3397 }
3397 3398
3398 3399
3399 if (IsPhantom || IsAttachment) // note: this may have been changed above in the case of joints 3400 if (IsPhantom || IsAttachment || (Shape.PathCurve == (byte)Extrusion.Flexible)) // note: this may have been changed above in the case of joints
3400 { 3401 {
3401 AddFlag(PrimFlags.Phantom); 3402 AddFlag(PrimFlags.Phantom);
3402 if (PhysActor != null) 3403 if (PhysActor != null)
diff --git a/OpenSim/Region/Framework/Scenes/TerrainChannel.cs b/OpenSim/Region/Framework/Scenes/TerrainChannel.cs
index 8209ff6..ca6210d 100644
--- a/OpenSim/Region/Framework/Scenes/TerrainChannel.cs
+++ b/OpenSim/Region/Framework/Scenes/TerrainChannel.cs
@@ -172,7 +172,7 @@ namespace OpenSim.Region.Framework.Scenes
172 public string SaveToXmlString() 172 public string SaveToXmlString()
173 { 173 {
174 XmlWriterSettings settings = new XmlWriterSettings(); 174 XmlWriterSettings settings = new XmlWriterSettings();
175 settings.Encoding = Encoding.UTF8; 175 settings.Encoding = Util.UTF8;
176 using (StringWriter sw = new StringWriter()) 176 using (StringWriter sw = new StringWriter())
177 { 177 {
178 using (XmlWriter writer = XmlWriter.Create(sw, settings)) 178 using (XmlWriter writer = XmlWriter.Create(sw, settings))
diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
index ee2d2db..4364627 100644
--- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
+++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
@@ -81,7 +81,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
81 { 81 {
82 m_log.Info("[IRCd] Sending >>> " + command); 82 m_log.Info("[IRCd] Sending >>> " + command);
83 83
84 byte[] buf = Encoding.UTF8.GetBytes(command + "\r\n"); 84 byte[] buf = Util.UTF8.GetBytes(command + "\r\n");
85 85
86 m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null); 86 m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null);
87 } 87 }
@@ -109,7 +109,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
109 byte[] buf = new byte[8]; // RFC1459 defines max message size as 512. 109 byte[] buf = new byte[8]; // RFC1459 defines max message size as 512.
110 110
111 int count = m_client.GetStream().Read(buf, 0, buf.Length); 111 int count = m_client.GetStream().Read(buf, 0, buf.Length);
112 string line = Encoding.UTF8.GetString(buf, 0, count); 112 string line = Util.UTF8.GetString(buf, 0, count);
113 113
114 strbuf += line; 114 strbuf += line;
115 115
diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs
index c7bb56a..b04b076 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs
@@ -559,7 +559,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
559 559
560 if (method == "POST") 560 if (method == "POST")
561 { 561 {
562 byte[] contentreq = Encoding.UTF8.GetBytes(body); 562 byte[] contentreq = Util.UTF8.GetBytes(body);
563 forwardreq.ContentLength = contentreq.Length; 563 forwardreq.ContentLength = contentreq.Length;
564 Stream reqStream = forwardreq.GetRequestStream(); 564 Stream reqStream = forwardreq.GetRequestStream();
565 reqStream.Write(contentreq, 0, contentreq.Length); 565 reqStream.Write(contentreq, 0, contentreq.Length);
@@ -567,7 +567,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
567 } 567 }
568 568
569 HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse(); 569 HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse();
570 Encoding encoding = Encoding.UTF8; 570 Encoding encoding = Util.UTF8;
571 StreamReader fwdresponsestream = new StreamReader(fwdrsp.GetResponseStream(), encoding); 571 StreamReader fwdresponsestream = new StreamReader(fwdrsp.GetResponseStream(), encoding);
572 fwdresponsestr = fwdresponsestream.ReadToEnd(); 572 fwdresponsestr = fwdresponsestream.ReadToEnd();
573 fwdresponsecontenttype = fwdrsp.ContentType; 573 fwdresponsecontenttype = fwdrsp.ContentType;
diff --git a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
index 3044b17..e3fbb6e 100644
--- a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
+++ b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
@@ -539,7 +539,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
539 { 539 {
540 XmlSerializer xs = new XmlSerializer(typeof(Copse)); 540 XmlSerializer xs = new XmlSerializer(typeof(Copse));
541 541
542 using (XmlTextWriter writer = new XmlTextWriter(fileName, System.Text.Encoding.UTF8)) 542 using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
543 { 543 {
544 writer.Formatting = Formatting.Indented; 544 writer.Formatting = Formatting.Indented;
545 xs.Serialize(writer, obj); 545 xs.Serialize(writer, obj);
diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs
index d56ddc8..0e29ccc 100644
--- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs
+++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs
@@ -224,6 +224,14 @@ namespace OpenSim.Region.Physics.Meshing
224 for (int i = 0; i < lodBytes.Length; i++) 224 for (int i = 0; i < lodBytes.Length; i++)
225 hash = djb2(hash, lodBytes[i]); 225 hash = djb2(hash, lodBytes[i]);
226 226
227 // include sculpt UUID
228 if (pbs.SculptEntry)
229 {
230 scaleBytes = pbs.SculptTexture.GetBytes();
231 for (int i = 0; i < scaleBytes.Length; i++)
232 hash = djb2(hash, scaleBytes[i]);
233 }
234
227 return hash; 235 return hash;
228 } 236 }
229 237
@@ -330,7 +338,7 @@ namespace OpenSim.Region.Physics.Meshing
330 bool invert = ((primShape.SculptType & 64) != 0); 338 bool invert = ((primShape.SculptType & 64) != 0);
331 339
332 sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert); 340 sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
333 341
334 idata.Dispose(); 342 idata.Dispose();
335 343
336 sculptMesh.DumpRaw(baseDir, primName, "primMesh"); 344 sculptMesh.DumpRaw(baseDir, primName, "primMesh");
@@ -389,7 +397,7 @@ namespace OpenSim.Region.Physics.Meshing
389 primMesh.pathCutBegin = pathBegin; 397 primMesh.pathCutBegin = pathBegin;
390 primMesh.pathCutEnd = pathEnd; 398 primMesh.pathCutEnd = pathEnd;
391 399
392 if (primShape.PathCurve == (byte)Extrusion.Straight) 400 if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
393 { 401 {
394 primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10; 402 primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
395 primMesh.twistEnd = primShape.PathTwist * 18 / 10; 403 primMesh.twistEnd = primShape.PathTwist * 18 / 10;
@@ -484,12 +492,18 @@ namespace OpenSim.Region.Physics.Meshing
484 492
485 public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical) 493 public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical)
486 { 494 {
495 Mesh mesh = null;
496 ulong key = 0;
497
487 // If this mesh has been created already, return it instead of creating another copy 498 // If this mesh has been created already, return it instead of creating another copy
488 // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory 499 // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
489 ulong key = GetMeshKey(primShape, size, lod); 500
490 Mesh mesh = null; 501 if (! primShape.SculptEntry)
491 if (m_uniqueMeshes.TryGetValue(key, out mesh)) 502 {
492 return mesh; 503 key = GetMeshKey(primShape, size, lod);
504 if (m_uniqueMeshes.TryGetValue(key, out mesh))
505 return mesh;
506 }
493 507
494 if (size.X < 0.01f) size.X = 0.01f; 508 if (size.X < 0.01f) size.X = 0.01f;
495 if (size.Y < 0.01f) size.Y = 0.01f; 509 if (size.Y < 0.01f) size.Y = 0.01f;
@@ -512,7 +526,10 @@ namespace OpenSim.Region.Physics.Meshing
512 // trim the vertex and triangle lists to free up memory 526 // trim the vertex and triangle lists to free up memory
513 mesh.TrimExcess(); 527 mesh.TrimExcess();
514 } 528 }
515 m_uniqueMeshes.Add(key, mesh); 529
530 if (!primShape.SculptEntry)
531 m_uniqueMeshes.Add(key, mesh);
532
516 return mesh; 533 return mesh;
517 } 534 }
518 } 535 }
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs
index ca67a64..b79c356 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs
@@ -7080,7 +7080,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
7080 try 7080 try
7081 { 7081 {
7082 byte[] encData_byte = new byte[str.Length]; 7082 byte[] encData_byte = new byte[str.Length];
7083 encData_byte = Encoding.UTF8.GetBytes(str); 7083 encData_byte = Util.UTF8.GetBytes(str);
7084 string encodedData = Convert.ToBase64String(encData_byte); 7084 string encodedData = Convert.ToBase64String(encData_byte);
7085 return encodedData; 7085 return encodedData;
7086 } 7086 }
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
index 59525b6..4cb4b61 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
@@ -1491,7 +1491,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
1491 notecardData = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " 1491 notecardData = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length "
1492 + textLength.ToString() + "\n" + notecardData + "}\n"; 1492 + textLength.ToString() + "\n" + notecardData + "}\n";
1493 1493
1494 asset.Data = Encoding.UTF8.GetBytes(notecardData); 1494 asset.Data = Util.UTF8.GetBytes(notecardData);
1495 World.AssetService.Store(asset); 1495 World.AssetService.Store(asset);
1496 1496
1497 // Create Task Entry 1497 // Create Task Entry
diff --git a/OpenSim/Server/Base/ServerUtils.cs b/OpenSim/Server/Base/ServerUtils.cs
index 9beadd8..0964caa 100644
--- a/OpenSim/Server/Base/ServerUtils.cs
+++ b/OpenSim/Server/Base/ServerUtils.cs
@@ -87,7 +87,7 @@ namespace OpenSim.Server.Base
87 public static byte[] SerializeResult(XmlSerializer xs, object data) 87 public static byte[] SerializeResult(XmlSerializer xs, object data)
88 { 88 {
89 MemoryStream ms = new MemoryStream(); 89 MemoryStream ms = new MemoryStream();
90 XmlTextWriter xw = new XmlTextWriter(ms, Encoding.UTF8); 90 XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
91 xw.Formatting = Formatting.Indented; 91 xw.Formatting = Formatting.Indented;
92 xs.Serialize(xw, data); 92 xs.Serialize(xw, data);
93 xw.Flush(); 93 xw.Flush();
diff --git a/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs b/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs
index d6ef22e..68bb01e 100644
--- a/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs
+++ b/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs
@@ -160,7 +160,7 @@ namespace OpenSim.Server.Handlers.Neighbour
160 160
161 httpResponse.StatusCode = (int)HttpStatusCode.OK; 161 httpResponse.StatusCode = (int)HttpStatusCode.OK;
162 162
163 return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)); 163 return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
164 } 164 }
165 } 165 }
166 166
diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs
index 822edcb..3da72c7 100644
--- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs
+++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs
@@ -161,7 +161,7 @@ namespace OpenSim.Server.Handlers.Simulation
161 161
162 httpResponse.StatusCode = (int)HttpStatusCode.OK; 162 httpResponse.StatusCode = (int)HttpStatusCode.OK;
163 163
164 return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)); 164 return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
165 } 165 }
166 } 166 }
167 167
diff --git a/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs b/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs
index d16112d..6f7c90f 100644
--- a/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs
+++ b/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs
@@ -171,6 +171,8 @@ namespace OpenSim.Services.Connectors
171 171
172 if (asset == null) 172 if (asset == null)
173 { 173 {
174 bool result = false;
175
174 AsynchronousRestObjectRequester. 176 AsynchronousRestObjectRequester.
175 MakeRequest<int, AssetBase>("GET", uri, 0, 177 MakeRequest<int, AssetBase>("GET", uri, 0,
176 delegate(AssetBase a) 178 delegate(AssetBase a)
@@ -178,12 +180,15 @@ namespace OpenSim.Services.Connectors
178 if (m_Cache != null) 180 if (m_Cache != null)
179 m_Cache.Cache(a); 181 m_Cache.Cache(a);
180 handler(id, sender, a); 182 handler(id, sender, a);
183 result = true;
181 }); 184 });
182 185
186 return result;
183 } 187 }
184 else 188 else
185 { 189 {
186 Util.FireAndForget(delegate { handler(id, sender, asset); }); 190 //Util.FireAndForget(delegate { handler(id, sender, asset); });
191 handler(id, sender, asset);
187 } 192 }
188 193
189 return true; 194 return true;