Merge branch 'master' into vehicles

0.6.8-post-fixes
Melanie 2009-10-05 10:17:23 +01:00
commit 0744292b47
63 changed files with 1874 additions and 1906 deletions

View File

@ -163,7 +163,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
get { return Plugin.RequestId; } get { return Plugin.RequestId; }
} }
internal static Encoding Encoding = Encoding.UTF8; internal static Encoding Encoding = Util.UTF8;
/// <summary> /// <summary>
/// Version control for REST implementation. This /// Version control for REST implementation. This
@ -435,7 +435,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
try try
{ {
byte[] encData_byte = new byte[str.Length]; byte[] encData_byte = new byte[str.Length];
encData_byte = Encoding.UTF8.GetBytes(str); encData_byte = Util.UTF8.GetBytes(str);
return Convert.ToBase64String(encData_byte); return Convert.ToBase64String(encData_byte);
} }
catch catch

View File

@ -45,7 +45,8 @@ namespace OpenSim.ApplicationPlugins.Rest
{ {
} }
public RestXmlWriter(Stream stream) : this(stream, Encoding.UTF8) public RestXmlWriter(Stream stream)
: this(stream, Encoding.UTF8)
{ {
} }

View File

@ -148,8 +148,8 @@ namespace OpenSim.Client.Linden
protected void AddHttpHandlers() protected void AddHttpHandlers()
{ {
//we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change? //we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change?
MainServer.Instance.AddXmlRPCHandler("expect_user", ExpectUser); MainServer.Instance.AddXmlRPCHandler("expect_user", ExpectUser, false);
MainServer.Instance.AddXmlRPCHandler("logoff_user", LogOffUser); MainServer.Instance.AddXmlRPCHandler("logoff_user", LogOffUser, false);
} }
protected void AddScene(Scene scene) protected void AddScene(Scene scene)
@ -182,19 +182,34 @@ namespace OpenSim.Client.Linden
/// <returns></returns> /// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient) public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient)
{ {
XmlRpcResponse resp = new XmlRpcResponse();
try
{
ulong regionHandle = 0;
Hashtable requestData = (Hashtable)request.Params[0]; Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData(); AgentCircuitData agentData = new AgentCircuitData();
if (requestData.ContainsKey("session_id"))
agentData.SessionID = new UUID((string)requestData["session_id"]); agentData.SessionID = new UUID((string)requestData["session_id"]);
if (requestData.ContainsKey("secure_session_id"))
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]); agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
if (requestData.ContainsKey("firstname"))
agentData.firstname = (string)requestData["firstname"]; agentData.firstname = (string)requestData["firstname"];
if (requestData.ContainsKey("lastname"))
agentData.lastname = (string)requestData["lastname"]; agentData.lastname = (string)requestData["lastname"];
if (requestData.ContainsKey("agent_id"))
agentData.AgentID = new UUID((string)requestData["agent_id"]); agentData.AgentID = new UUID((string)requestData["agent_id"]);
if (requestData.ContainsKey("circuit_code"))
agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]); agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
if (requestData.ContainsKey("caps_path"))
agentData.CapsPath = (string)requestData["caps_path"]; agentData.CapsPath = (string)requestData["caps_path"];
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]); if (requestData.ContainsKey("regionhandle"))
regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
else
m_log.Warn("[CLIENT]: request from login server did not contain regionhandle");
// Appearance // Appearance
if (requestData["appearance"] != null) if (requestData.ContainsKey("appearance"))
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]); agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat( m_log.DebugFormat(
@ -216,8 +231,6 @@ namespace OpenSim.Client.Linden
agentData.child = false; agentData.child = false;
} }
XmlRpcResponse resp = new XmlRpcResponse();
if (!RegionLoginsEnabled) if (!RegionLoginsEnabled)
{ {
m_log.InfoFormat( m_log.InfoFormat(
@ -280,6 +293,15 @@ namespace OpenSim.Client.Linden
resp.Value = respdata; resp.Value = respdata;
} }
} }
}
catch (Exception e)
{
m_log.WarnFormat("[CLIENT]: Unable to receive user. Reason: {0}", e);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "Exception occurred";
resp.Value = respdata;
}
return resp; return resp;
} }

View File

@ -886,7 +886,7 @@ namespace OpenSim.Client.MXP.ClientStack
chatActionEvent.ActionFragment.SourceObjectId = fromAgentID.Guid; chatActionEvent.ActionFragment.SourceObjectId = fromAgentID.Guid;
chatActionEvent.ActionFragment.ObservationRadius = 180.0f; chatActionEvent.ActionFragment.ObservationRadius = 180.0f;
chatActionEvent.ActionFragment.ExtensionDialect = "TEXT"; chatActionEvent.ActionFragment.ExtensionDialect = "TEXT";
chatActionEvent.SetPayloadData(Encoding.UTF8.GetBytes(message)); chatActionEvent.SetPayloadData(Util.UTF8.GetBytes(message));
Session.Send(chatActionEvent); Session.Send(chatActionEvent);
} }

View File

@ -95,16 +95,15 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
ManagedImage tmp; ManagedImage tmp;
Image imgData; Image imgData;
byte[] jpegdata;
OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData); OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData);
MemoryStream ms = new MemoryStream(); using (MemoryStream ms = new MemoryStream())
{
imgData.Save(ms, ImageFormat.Jpeg); imgData.Save(ms, ImageFormat.Jpeg);
jpegdata = ms.GetBuffer();
byte[] jpegdata = ms.GetBuffer(); }
ms.Close();
resp.ContentType = "image/jpeg"; resp.ContentType = "image/jpeg";
resp.ContentLength = jpegdata.Length; resp.ContentLength = jpegdata.Length;

View File

@ -197,20 +197,11 @@ namespace OpenSim.Data.MSSQL
public void Dispose() public void Dispose()
{ {
SqlConnection conn = realCommand.Connection; SqlConnection conn = realCommand.Connection;
try try { realCommand.Dispose(); }
{
realCommand.Dispose();
}
finally finally
{ {
try try { conn.Dispose(); }
{ finally { }
conn.Close();
}
finally
{
conn.Dispose();
}
} }
} }

View File

@ -348,8 +348,6 @@ namespace OpenSim.Data.MSSQL
//Delete the actual row //Delete the actual row
DeleteOneFolder(folderID, connection); DeleteOneFolder(folderID, connection);
DeleteItemsInFolder(folderID, connection); DeleteItemsInFolder(folderID, connection);
connection.Close();
} }
} }

View File

@ -340,8 +340,6 @@ namespace OpenSim.Data.MSSQL
MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore); MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
migration.Update(); migration.Update();
connection.Close();
} }
} }
@ -385,9 +383,7 @@ namespace OpenSim.Data.MSSQL
m_log.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
tables.Close();
} }
} }
/// <summary> /// <summary>

View File

@ -56,7 +56,6 @@ namespace OpenSim.Data.MSSQL
{ {
version = Convert.ToInt32(reader["version"]); version = Convert.ToInt32(reader["version"]);
} }
reader.Close();
} }
} }
catch catch

View File

@ -131,7 +131,8 @@ namespace OpenSim.Data
m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type); m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type);
m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!"); m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
DbCommand cmd = _conn.CreateCommand(); using (DbCommand cmd = _conn.CreateCommand())
{
foreach (KeyValuePair<int, string> kvp in migrations) foreach (KeyValuePair<int, string> kvp in migrations)
{ {
int newversion = kvp.Key; int newversion = kvp.Key;
@ -149,7 +150,7 @@ namespace OpenSim.Data
UpdateVersion(_type, newversion); UpdateVersion(_type, newversion);
} }
version = newversion; version = newversion;
cmd.Dispose(); }
} }
} }
@ -189,43 +190,45 @@ namespace OpenSim.Data
protected virtual int FindVersion(DbConnection conn, string type) protected virtual int FindVersion(DbConnection conn, string type)
{ {
int version = 0; int version = 0;
DbCommand cmd = conn.CreateCommand();
using (DbCommand cmd = conn.CreateCommand())
{
try try
{ {
cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc"; cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
using (IDataReader reader = cmd.ExecuteReader()) using (IDataReader reader = cmd.ExecuteReader())
{ {
if (reader.Read()) if (reader.Read())
{
version = Convert.ToInt32(reader["version"]); version = Convert.ToInt32(reader["version"]);
} }
reader.Close();
}
} }
catch catch
{ {
// Something went wrong, so we're version 0 // Something went wrong, so we're version 0
} }
cmd.Dispose(); }
return version; return version;
} }
private void InsertVersion(string type, int version) private void InsertVersion(string type, int version)
{ {
DbCommand cmd = _conn.CreateCommand(); using (DbCommand cmd = _conn.CreateCommand())
{
cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")"; cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version); m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose(); }
} }
private void UpdateVersion(string type, int version) private void UpdateVersion(string type, int version)
{ {
DbCommand cmd = _conn.CreateCommand(); using (DbCommand cmd = _conn.CreateCommand())
{
cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'"; cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version); m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Dispose(); }
} }
// private SortedList<int, string> GetAllMigrations() // private SortedList<int, string> GetAllMigrations()

View File

@ -142,10 +142,10 @@ namespace OpenSim.Data.MySQL
{ {
_dbConnection.CheckConnection(); _dbConnection.CheckConnection();
MySqlCommand cmd = using (MySqlCommand cmd = new MySqlCommand(
new MySqlCommand(
"SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id", "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id",
_dbConnection.Connection); _dbConnection.Connection))
{
cmd.Parameters.AddWithValue("?id", assetID.ToString()); cmd.Parameters.AddWithValue("?id", assetID.ToString());
try try
@ -158,21 +158,19 @@ namespace OpenSim.Data.MySQL
asset.Data = (byte[])dbReader["data"]; asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"]; asset.Description = (string)dbReader["description"];
asset.FullID = assetID; asset.FullID = assetID;
try
{ string local = dbReader["local"].ToString();
asset.Local = (bool)dbReader["local"]; if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
} asset.Local = true;
catch (InvalidCastException) else
{
asset.Local = false; asset.Local = false;
}
asset.Name = (string)dbReader["name"]; asset.Name = (string)dbReader["name"];
asset.Type = (sbyte)dbReader["assetType"]; asset.Type = (sbyte)dbReader["assetType"];
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]); asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
} }
dbReader.Close();
cmd.Dispose();
} }
if (asset != null) if (asset != null)
UpdateAccessTime(asset); UpdateAccessTime(asset);
} }
@ -184,6 +182,7 @@ namespace OpenSim.Data.MySQL
_dbConnection.Reconnect(); _dbConnection.Reconnect();
} }
} }
}
return asset; return asset;
} }
@ -297,11 +296,10 @@ namespace OpenSim.Data.MySQL
{ {
_dbConnection.CheckConnection(); _dbConnection.CheckConnection();
MySqlCommand cmd = using (MySqlCommand cmd = new MySqlCommand(
new MySqlCommand(
"SELECT id FROM assets WHERE id=?id", "SELECT id FROM assets WHERE id=?id",
_dbConnection.Connection); _dbConnection.Connection))
{
cmd.Parameters.AddWithValue("?id", uuid.ToString()); cmd.Parameters.AddWithValue("?id", uuid.ToString());
try try
@ -309,13 +307,8 @@ namespace OpenSim.Data.MySQL
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
if (dbReader.Read()) if (dbReader.Read())
{
assetExists = true; assetExists = true;
} }
dbReader.Close();
cmd.Dispose();
}
} }
catch (Exception e) catch (Exception e)
{ {
@ -325,6 +318,7 @@ namespace OpenSim.Data.MySQL
_dbConnection.Reconnect(); _dbConnection.Reconnect();
} }
} }
}
return assetExists; return assetExists;
} }

View File

@ -55,14 +55,12 @@ namespace OpenSim.Data.MySQL
AuthenticationData ret = new AuthenticationData(); AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>(); ret.Data = new Dictionary<string, object>();
MySqlCommand cmd = new MySqlCommand( using (MySqlCommand cmd = new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID"))
"select * from `"+m_Realm+"` where UUID = ?principalID" {
);
cmd.Parameters.AddWithValue("?principalID", principalID.ToString()); cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
IDataReader result = ExecuteReader(cmd); using (IDataReader result = ExecuteReader(cmd))
{
if (result.Read()) if (result.Read())
{ {
ret.PrincipalID = principalID; ret.PrincipalID = principalID;
@ -84,14 +82,10 @@ namespace OpenSim.Data.MySQL
ret.Data[s] = result[s].ToString(); ret.Data[s] = result[s].ToString();
} }
result.Close();
CloseReaderCommand(cmd);
return ret; return ret;
} }
}
result.Close(); }
CloseReaderCommand(cmd);
return null; return null;
} }

View File

@ -95,11 +95,9 @@ namespace OpenSim.Data.MySQL
protected void GetWaitTimeout() protected void GetWaitTimeout()
{ {
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, m_connection))
m_connection); {
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
using (MySqlDataReader dbReader =
cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
if (dbReader.Read()) if (dbReader.Read())
{ {
@ -107,9 +105,7 @@ namespace OpenSim.Data.MySQL
= Convert.ToInt32(dbReader["@@wait_timeout"]) * = Convert.ToInt32(dbReader["@@wait_timeout"]) *
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
} }
}
dbReader.Close();
cmd.Dispose();
} }
m_lastConnectionUse = DateTime.Now.Ticks; m_lastConnectionUse = DateTime.Now.Ticks;
@ -147,15 +143,19 @@ namespace OpenSim.Data.MySQL
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); bool migration = true;
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql; cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
IDataReader r = cmd.ExecuteReader(); using (IDataReader r = cmd.ExecuteReader())
{
if (r.Read()) if (r.Read())
{ {
migration = false;
foreach (string name in FieldList) foreach (string name in FieldList)
{ {
if (m_FieldMap[name].GetValue(es) is bool) if (m_FieldMap[name].GetValue(es) is bool)
@ -178,20 +178,21 @@ namespace OpenSim.Data.MySQL
m_FieldMap[name].SetValue(es, r[name]); m_FieldMap[name].SetValue(es, r[name]);
} }
} }
r.Close();
} }
else }
}
if (migration)
{ {
// Migration case // Migration case
//
r.Close();
List<string> names = new List<string>(FieldList); List<string> names = new List<string>(FieldList);
names.Remove("EstateID"); names.Remove("EstateID");
sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")";
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql; cmd.CommandText = sql;
cmd.Parameters.Clear(); cmd.Parameters.Clear();
@ -215,43 +216,31 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = "select LAST_INSERT_ID() as id"; cmd.CommandText = "select LAST_INSERT_ID() as id";
cmd.Parameters.Clear(); cmd.Parameters.Clear();
r = cmd.ExecuteReader(); using (IDataReader r = cmd.ExecuteReader())
{
r.Read(); r.Read();
es.EstateID = Convert.ToUInt32(r["id"]); es.EstateID = Convert.ToUInt32(r["id"]);
}
r.Close();
cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
// This will throw on dupe key // This will throw on dupe key
try try { cmd.ExecuteNonQuery(); }
{ catch (Exception) { }
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
// Munge and transfer the ban list // Munge and transfer the ban list
//
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID"; cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
try try { cmd.ExecuteNonQuery(); }
{ catch (Exception) { }
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save(); es.Save();
} }
}
LoadBanList(es); LoadBanList(es);
@ -267,8 +256,8 @@ namespace OpenSim.Data.MySQL
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql; cmd.CommandText = sql;
foreach (string name in FieldList) foreach (string name in FieldList)
@ -287,6 +276,7 @@ namespace OpenSim.Data.MySQL
} }
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
}
SaveBanList(es); SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
@ -300,13 +290,13 @@ namespace OpenSim.Data.MySQL
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID"; cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID); cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader(); using (IDataReader r = cmd.ExecuteReader())
{
while (r.Read()) while (r.Read())
{ {
EstateBan eb = new EstateBan(); EstateBan eb = new EstateBan();
@ -319,15 +309,16 @@ namespace OpenSim.Data.MySQL
eb.BannedHostIPMask = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb); es.AddBan(eb);
} }
r.Close(); }
}
} }
private void SaveBanList(EstateSettings es) private void SaveBanList(EstateSettings es)
{ {
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = "delete from estateban where EstateID = ?EstateID"; cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
@ -346,13 +337,14 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear(); cmd.Parameters.Clear();
} }
} }
}
void SaveUUIDList(uint EstateID, string table, UUID[] data) void SaveUUIDList(uint EstateID, string table, UUID[] data)
{ {
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID"; cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
@ -371,6 +363,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear(); cmd.Parameters.Clear();
} }
} }
}
UUID[] LoadUUIDList(uint EstateID, string table) UUID[] LoadUUIDList(uint EstateID, string table)
{ {
@ -378,13 +371,13 @@ namespace OpenSim.Data.MySQL
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID"; cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID); cmd.Parameters.AddWithValue("?EstateID", EstateID);
IDataReader r = cmd.ExecuteReader(); using (IDataReader r = cmd.ExecuteReader())
{
while (r.Read()) while (r.Read())
{ {
// EstateBan eb = new EstateBan(); // EstateBan eb = new EstateBan();
@ -394,7 +387,8 @@ namespace OpenSim.Data.MySQL
uuids.Add(uuid); uuids.Add(uuid);
} }
r.Close(); }
}
return uuids.ToArray(); return uuids.ToArray();
} }

View File

@ -40,6 +40,8 @@ namespace OpenSim.Data.MySQL
/// </summary> /// </summary>
public class MySqlFramework public class MySqlFramework
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected MySqlConnection m_Connection; protected MySqlConnection m_Connection;
protected MySqlFramework(string connectionString) protected MySqlFramework(string connectionString)
@ -70,12 +72,11 @@ namespace OpenSim.Data.MySQL
} }
catch (MySqlException e) catch (MySqlException e)
{ {
Console.WriteLine(e.ToString()); m_log.Error(e.Message, e);
if (errorSeen) if (errorSeen)
throw; throw;
// This is "Server has gone away" and "Server lost" // This is "Server has gone away" and "Server lost"
//
if (e.Number == 2006 || e.Number == 2013) if (e.Number == 2006 || e.Number == 2013)
{ {
errorSeen = true; errorSeen = true;
@ -94,7 +95,7 @@ Console.WriteLine(e.ToString());
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e.ToString()); m_log.Error(e.Message, e);
return 0; return 0;
} }
} }
@ -112,12 +113,5 @@ Console.WriteLine(e.ToString());
return cmd.ExecuteReader(); return cmd.ExecuteReader();
} }
protected void CloseReaderCommand(MySqlCommand cmd)
{
cmd.Connection.Close();
cmd.Connection.Dispose();
cmd.Dispose();
}
} }
} }

View File

@ -197,29 +197,27 @@ namespace OpenSim.Data.MySQL
param["?xmax"] = xmax.ToString(); param["?xmax"] = xmax.ToString();
param["?ymax"] = ymax.ToString(); param["?ymax"] = ymax.ToString();
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row; RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>(); List<RegionProfileData> rows = new List<RegionProfileData>();
while ((row = dbm.Manager.readSimRow(reader)) != null) while ((row = dbm.Manager.readSimRow(reader)) != null)
{
rows.Add(row); rows.Add(row);
}
reader.Close();
result.Dispose();
return rows.ToArray(); return rows.ToArray();
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -243,29 +241,27 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?name"] = namePrefix + "%"; param["?name"] = namePrefix + "%";
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName LIKE ?name", "SELECT * FROM regions WHERE regionName LIKE ?name",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row; RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>(); List<RegionProfileData> rows = new List<RegionProfileData>();
while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null) while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
{
rows.Add(row); rows.Add(row);
}
reader.Close();
result.Dispose();
return rows; return rows;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -288,19 +284,19 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?handle"] = handle.ToString(); param["?handle"] = handle.ToString();
IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param); using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = dbm.Manager.readSimRow(reader); RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -323,21 +319,22 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString(); param["?uuid"] = uuid.ToString();
IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param); using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = dbm.Manager.readSimRow(reader); RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} finally }
finally
{ {
dbm.Release(); dbm.Release();
} }
@ -359,22 +356,21 @@ namespace OpenSim.Data.MySQL
// Add % because this is a like query. // Add % because this is a like query.
param["?regionName"] = regionName + "%"; param["?regionName"] = regionName + "%";
// Order by statement will return shorter matches first. Only returns one record or no record. // Order by statement will return shorter matches first. Only returns one record or no record.
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = dbm.Manager.readSimRow(reader); RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -382,6 +378,7 @@ namespace OpenSim.Data.MySQL
dbm.Release(); dbm.Release();
} }
} }
m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters");
return null; return null;
} }
@ -394,11 +391,11 @@ namespace OpenSim.Data.MySQL
override public DataResponse StoreProfile(RegionProfileData profile) override public DataResponse StoreProfile(RegionProfileData profile)
{ {
MySQLSuperManager dbm = GetLockedConnection(); MySQLSuperManager dbm = GetLockedConnection();
try { try
if (dbm.Manager.insertRegion(profile))
{ {
if (dbm.Manager.insertRegion(profile))
return DataResponse.RESPONSE_OK; return DataResponse.RESPONSE_OK;
} else
return DataResponse.RESPONSE_ERROR; return DataResponse.RESPONSE_ERROR;
} }
finally finally
@ -417,14 +414,14 @@ namespace OpenSim.Data.MySQL
{ {
MySQLSuperManager dbm = GetLockedConnection(); MySQLSuperManager dbm = GetLockedConnection();
try
try {
if (dbm.Manager.deleteRegion(uuid))
{ {
if (dbm.Manager.deleteRegion(uuid))
return DataResponse.RESPONSE_OK; return DataResponse.RESPONSE_OK;
} else
return DataResponse.RESPONSE_ERROR; return DataResponse.RESPONSE_ERROR;
} finally }
finally
{ {
dbm.Release(); dbm.Release();
} }
@ -484,24 +481,24 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?x"] = x.ToString(); param["?x"] = x.ToString();
param["?y"] = y.ToString(); param["?y"] = y.ToString();
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
ReservationData row = dbm.Manager.readReservationRow(reader); ReservationData row = dbm.Manager.readReservationRow(reader);
reader.Close();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} finally }
finally
{ {
dbm.Release(); dbm.Release();
} }

View File

@ -135,12 +135,13 @@ namespace OpenSim.Data.MySQL
database.CheckConnection(); database.CheckConnection();
MySqlCommand result = using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid", database.Connection))
database.Connection); {
result.Parameters.AddWithValue("?uuid", folderID.ToString()); result.Parameters.AddWithValue("?uuid", folderID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
// A null item (because something went wrong) breaks everything in the folder // A null item (because something went wrong) breaks everything in the folder
@ -149,16 +150,15 @@ namespace OpenSim.Data.MySQL
items.Add(item); items.Add(item);
} }
reader.Close();
result.Dispose();
return items; return items;
} }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
} }
@ -176,29 +176,28 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand result = using (MySqlCommand result = new MySqlCommand(
new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection); database.Connection))
{
result.Parameters.AddWithValue("?uuid", user.ToString()); result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString()); result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read()) while (reader.Read())
items.Add(readInventoryFolder(reader)); items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items; return items;
} }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
} }
@ -217,15 +216,15 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand result = using (MySqlCommand result = new MySqlCommand(
new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid", "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection); database.Connection))
{
result.Parameters.AddWithValue("?uuid", user.ToString()); result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString()); result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
MySqlDataReader reader = result.ExecuteReader(); using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read()) while (reader.Read())
items.Add(readInventoryFolder(reader)); items.Add(readInventoryFolder(reader));
@ -238,20 +237,17 @@ namespace OpenSim.Data.MySQL
// to put such a message out, and it's too minor right now to spare the time to // to put such a message out, and it's too minor right now to spare the time to
// suitably refactor. // suitably refactor.
if (items.Count > 0) if (items.Count > 0)
{
rootFolder = items[0]; rootFolder = items[0];
}
reader.Close();
result.Dispose();
return rootFolder; return rootFolder;
} }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
} }
@ -271,27 +267,26 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand result = using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid", database.Connection))
database.Connection); {
result.Parameters.AddWithValue("?uuid", parentID.ToString()); result.Parameters.AddWithValue("?uuid", parentID.ToString());
MySqlDataReader reader = result.ExecuteReader(); using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read()) while (reader.Read())
items.Add(readInventoryFolder(reader)); items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items; return items;
} }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
} }
@ -370,25 +365,25 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand result = using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection))
new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection); {
result.Parameters.AddWithValue("?uuid", itemID.ToString()); result.Parameters.AddWithValue("?uuid", itemID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
InventoryItemBase item = null; InventoryItemBase item = null;
if (reader.Read()) if (reader.Read())
item = readInventoryItem(reader); item = readInventoryItem(reader);
reader.Close();
result.Dispose();
return item; return item;
} }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
return null; return null;
} }
@ -413,7 +408,7 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
return null; return null;
@ -433,24 +428,25 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand result = using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection); {
result.Parameters.AddWithValue("?uuid", folderID.ToString()); result.Parameters.AddWithValue("?uuid", folderID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
InventoryFolderBase folder = null; InventoryFolderBase folder = null;
if (reader.Read()) if (reader.Read())
folder = readInventoryFolder(reader); folder = readInventoryFolder(reader);
reader.Close();
result.Dispose();
return folder; return folder;
} }
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
} }
@ -698,54 +694,58 @@ namespace OpenSim.Data.MySQL
try try
{ {
List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
Dictionary<UUID, List<InventoryFolderBase>> hashtable Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(); ;
= new Dictionary<UUID, List<InventoryFolderBase>>(); ;
List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>(); List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>();
lock (database)
{
MySqlCommand result;
MySqlDataReader reader;
bool buildResultsFromHashTable = false; bool buildResultsFromHashTable = false;
lock (database)
{
database.CheckConnection(); database.CheckConnection();
/* Fetch the parent folder from the database to determine the agent ID, and if /* Fetch the parent folder from the database to determine the agent ID, and if
* we're querying the root of the inventory folder tree */ * we're querying the root of the inventory folder tree */
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
database.Connection); {
result.Parameters.AddWithValue("?uuid", parentID.ToString()); result.Parameters.AddWithValue("?uuid", parentID.ToString());
reader = result.ExecuteReader();
while (reader.Read()) // Should be at most 1 result using (MySqlDataReader reader = result.ExecuteReader())
{
// Should be at most 1 result
while (reader.Read())
parentFolder.Add(readInventoryFolder(reader)); parentFolder.Add(readInventoryFolder(reader));
reader.Close(); }
result.Dispose(); }
if (parentFolder.Count >= 1) // No result means parent folder does not exist if (parentFolder.Count >= 1) // No result means parent folder does not exist
{ {
if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder
{ {
/* Get all of the agent's folders from the database, put them in a list and return it */ /* Get all of the agent's folders from the database, put them in a list and return it */
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
database.Connection); {
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString()); result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
InventoryFolderBase curFolder = readInventoryFolder(reader); InventoryFolderBase curFolder = readInventoryFolder(reader);
if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
folders.Add(curFolder); folders.Add(curFolder);
} }
reader.Close(); }
result.Dispose(); }
} // if we are querying the root folder } // if we are querying the root folder
else // else we are querying a subtree of the inventory folder tree else // else we are querying a subtree of the inventory folder tree
{ {
/* Get all of the agent's folders from the database, put them all in a hash table /* Get all of the agent's folders from the database, put them all in a hash table
* indexed by their parent ID */ * indexed by their parent ID */
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
database.Connection); {
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString()); result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
InventoryFolderBase curFolder = readInventoryFolder(reader); InventoryFolderBase curFolder = readInventoryFolder(reader);
@ -759,8 +759,8 @@ namespace OpenSim.Data.MySQL
hashtable.Add(curFolder.ParentID, siblingList); hashtable.Add(curFolder.ParentID, siblingList);
} }
} // while more items to read from the database } // while more items to read from the database
reader.Close(); }
result.Dispose(); }
// Set flag so we know we need to build the results from the hash table after // Set flag so we know we need to build the results from the hash table after
// we unlock the database // we unlock the database
@ -781,12 +781,13 @@ namespace OpenSim.Data.MySQL
folders.AddRange(hashtable[folders[i].ID]); folders.AddRange(hashtable[folders[i].ID]);
} }
} // lock (database) } // lock (database)
return folders; return folders;
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
} }
@ -801,19 +802,18 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand cmd = using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection))
new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection); {
cmd.Parameters.AddWithValue("?uuid", folderID.ToString()); cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database) lock (database)
{
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
} }
catch (MySqlException e) catch (MySqlException e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
} }
@ -827,12 +827,11 @@ namespace OpenSim.Data.MySQL
{ {
database.CheckConnection(); database.CheckConnection();
MySqlCommand cmd = using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection))
new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection); {
cmd.Parameters.AddWithValue("?uuid", folderID.ToString()); cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database) lock (database)
{
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
} }
@ -865,20 +864,21 @@ namespace OpenSim.Data.MySQL
public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
{ {
MySqlDataReader result = null;
MySqlCommand sqlCmd = null;
lock (database) lock (database)
{ {
try try
{ {
database.CheckConnection(); database.CheckConnection();
sqlCmd = new MySqlCommand(
using (MySqlCommand sqlCmd = new MySqlCommand(
"SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1", "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
database.Connection); database.Connection))
{
sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString()); sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture); sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
result = sqlCmd.ExecuteReader();
using (MySqlDataReader result = sqlCmd.ExecuteReader())
{
List<InventoryItemBase> list = new List<InventoryItemBase>(); List<InventoryItemBase> list = new List<InventoryItemBase>();
while (result.Read()) while (result.Read())
{ {
@ -888,17 +888,14 @@ namespace OpenSim.Data.MySQL
} }
return list; return list;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally
{
if (result != null) result.Close();
if (sqlCmd != null) sqlCmd.Dispose();
}
} }
} }
} }

View File

@ -268,6 +268,8 @@ namespace OpenSim.Data.MySQL
public void RemoveObject(UUID obj, UUID regionUUID) public void RemoveObject(UUID obj, UUID regionUUID)
{ {
List<UUID> uuids = new List<UUID>();
// Formerly, this used to check the region UUID. // Formerly, this used to check the region UUID.
// That makes no sense, as we remove the contents of a prim // That makes no sense, as we remove the contents of a prim
// unconditionally, but the prim dependent on the region ID. // unconditionally, but the prim dependent on the region ID.
@ -278,33 +280,22 @@ namespace OpenSim.Data.MySQL
// //
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select UUID from prims where "+ cmd.CommandText = "select UUID from prims where SceneGroupID= ?UUID";
"SceneGroupID= ?UUID";
cmd.Parameters.AddWithValue("UUID", obj.ToString()); cmd.Parameters.AddWithValue("UUID", obj.ToString());
List<UUID> uuids = new List<UUID>(); using (IDataReader reader = ExecuteReader(cmd))
IDataReader reader = ExecuteReader(cmd);
try
{ {
while (reader.Read()) while (reader.Read())
{
uuids.Add(new UUID(reader["UUID"].ToString())); uuids.Add(new UUID(reader["UUID"].ToString()));
} }
}
finally
{
reader.Close();
}
// delete the main prims // delete the main prims
cmd.CommandText = "delete from prims where SceneGroupID= ?UUID"; cmd.CommandText = "delete from prims where SceneGroupID= ?UUID";
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose(); }
}
// there is no way this should be < 1 unless there is // there is no way this should be < 1 unless there is
// a very corrupt database, but in that case be extra // a very corrupt database, but in that case be extra
@ -315,7 +306,6 @@ namespace OpenSim.Data.MySQL
RemoveItems(uuids); RemoveItems(uuids);
} }
} }
}
/// <summary> /// <summary>
/// Remove all persisted items of the given prim. /// Remove all persisted items of the given prim.
@ -326,18 +316,15 @@ namespace OpenSim.Data.MySQL
{ {
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "delete from primitems where " + cmd.CommandText = "delete from primitems where PrimID = ?PrimID";
"PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", uuid.ToString()); cmd.Parameters.AddWithValue("PrimID", uuid.ToString());
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose();
} }
} }
}
/// <summary> /// <summary>
/// Remove all persisted shapes for a list of prims /// Remove all persisted shapes for a list of prims
@ -349,8 +336,9 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
string sql = "delete from primshapes where "; string sql = "delete from primshapes where ";
MySqlCommand cmd = m_Connection.CreateCommand();
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
for (int i = 0; i < uuids.Count; i++) for (int i = 0; i < uuids.Count; i++)
{ {
if ((i + 1) == uuids.Count) if ((i + 1) == uuids.Count)
@ -365,12 +353,10 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = sql; cmd.CommandText = sql;
for (int i = 0; i < uuids.Count; i++) for (int i = 0; i < uuids.Count; i++)
{
cmd.Parameters.AddWithValue("UUID" + i, uuids[i].ToString()); cmd.Parameters.AddWithValue("UUID" + i, uuids[i].ToString());
}
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose(); }
} }
} }
@ -384,12 +370,14 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
string sql = "delete from primitems where "; string sql = "delete from primitems where ";
MySqlCommand cmd = m_Connection.CreateCommand();
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
for (int i = 0; i < uuids.Count; i++) for (int i = 0; i < uuids.Count; i++)
{ {
if ((i + 1) == uuids.Count) if ((i + 1) == uuids.Count)
{// end of the list {
// end of the list
sql += "(PrimID = ?PrimID" + i + ")"; sql += "(PrimID = ?PrimID" + i + ")";
} }
else else
@ -400,12 +388,10 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = sql; cmd.CommandText = sql;
for (int i = 0; i < uuids.Count; i++) for (int i = 0; i < uuids.Count; i++)
{
cmd.Parameters.AddWithValue("PrimID" + i, uuids[i].ToString()); cmd.Parameters.AddWithValue("PrimID" + i, uuids[i].ToString());
}
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose(); }
} }
} }
@ -418,8 +404,8 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select *, " + cmd.CommandText = "select *, " +
"case when prims.UUID = SceneGroupID " + "case when prims.UUID = SceneGroupID " +
"then 0 else 1 end as sort from prims " + "then 0 else 1 end as sort from prims " +
@ -429,9 +415,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString()); cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
IDataReader reader = ExecuteReader(cmd); using (IDataReader reader = ExecuteReader(cmd))
try
{ {
while (reader.Read()) while (reader.Read())
{ {
@ -481,14 +465,10 @@ namespace OpenSim.Data.MySQL
} }
} }
} }
finally
{
reader.Close();
}
if (grp != null) if (grp != null)
objects[grp.UUID] = grp; objects[grp.UUID] = grp;
cmd.Dispose(); }
} }
// Instead of attempting to LoadItems on every prim, // Instead of attempting to LoadItems on every prim,
@ -498,10 +478,10 @@ namespace OpenSim.Data.MySQL
List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>(); List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>();
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand itemCmd = m_Connection.CreateCommand(); using (MySqlCommand itemCmd = m_Connection.CreateCommand())
{
itemCmd.CommandText = "select distinct primID from primitems"; itemCmd.CommandText = "select distinct primID from primitems";
IDataReader itemReader = ExecuteReader(itemCmd); using (IDataReader itemReader = ExecuteReader(itemCmd))
try
{ {
while (itemReader.Read()) while (itemReader.Read())
{ {
@ -515,17 +495,12 @@ namespace OpenSim.Data.MySQL
} }
} }
} }
finally
{
itemReader.Close();
} }
itemCmd.Dispose();
} }
foreach (SceneObjectPart prim in primsWithInventory) foreach (SceneObjectPart prim in primsWithInventory)
{
LoadItems(prim); LoadItems(prim);
}
m_log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count); m_log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count);
return new List<SceneObjectGroup>(objects.Values); return new List<SceneObjectGroup>(objects.Values);
} }
@ -538,34 +513,25 @@ namespace OpenSim.Data.MySQL
{ {
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); List<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
cmd.CommandText = "select * from primitems where "+
"PrimID = ?PrimID";
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select * from primitems where PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString()); cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString());
IDataReader reader = ExecuteReader(cmd); using (IDataReader reader = ExecuteReader(cmd))
List<TaskInventoryItem> inventory =
new List<TaskInventoryItem>();
try
{ {
while (reader.Read()) while (reader.Read())
{ {
TaskInventoryItem item = BuildItem(reader); TaskInventoryItem item = BuildItem(reader);
item.ParentID = prim.UUID; // Values in database are item.ParentID = prim.UUID; // Values in database are often wrong
// often wrong
inventory.Add(item); inventory.Add(item);
} }
} }
finally
{
reader.Close();
} }
cmd.Dispose();
prim.Inventory.RestoreInventoryItems(inventory); prim.Inventory.RestoreInventoryItems(inventory);
} }
} }
@ -576,10 +542,9 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "delete from terrain where " + cmd.CommandText = "delete from terrain where RegionUUID = ?RegionUUID";
"RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString()); cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
@ -588,11 +553,10 @@ namespace OpenSim.Data.MySQL
"Revision, Heightfield) values (?RegionUUID, " + "Revision, Heightfield) values (?RegionUUID, " +
"1, ?Heightfield)"; "1, ?Heightfield)";
cmd.Parameters.AddWithValue("Heightfield", cmd.Parameters.AddWithValue("Heightfield", SerializeTerrain(ter));
SerializeTerrain(ter));
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose(); }
} }
} }
@ -602,42 +566,40 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select RegionUUID, Revision, Heightfield " + cmd.CommandText = "select RegionUUID, Revision, Heightfield " +
"from terrain where RegionUUID = ?RegionUUID " + "from terrain where RegionUUID = ?RegionUUID " +
"order by Revision desc limit 1"; "order by Revision desc limit 1";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString()); cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
IDataReader reader = ExecuteReader(cmd); using (IDataReader reader = ExecuteReader(cmd))
try
{ {
while (reader.Read()) while (reader.Read())
{ {
int rev = Convert.ToInt32(reader["Revision"]);
terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize];
terrain.Initialize(); terrain.Initialize();
MemoryStream mstr = new MemoryStream((byte[]) reader["Heightfield"]); using (MemoryStream mstr = new MemoryStream((byte[])reader["Heightfield"]))
int rev = 0; {
using (BinaryReader br = new BinaryReader(mstr))
BinaryReader br = new BinaryReader(mstr); {
for (int x = 0; x < (int)Constants.RegionSize; x++) for (int x = 0; x < (int)Constants.RegionSize; x++)
{ {
for (int y = 0; y < (int)Constants.RegionSize; y++) for (int y = 0; y < (int)Constants.RegionSize; y++)
{ {
terrain[x, y] = br.ReadDouble(); terrain[x, y] = br.ReadDouble();
} }
rev = Convert.ToInt32(reader["Revision"]);
}
m_log.InfoFormat("[REGION DB]: Loaded terrain " +
"revision r{0}", rev);
} }
} }
finally
{ m_log.InfoFormat("[REGION DB]: Loaded terrain revision r{0}", rev);
reader.Close(); }
}
}
} }
cmd.Dispose();
} }
return terrain; return terrain;
@ -647,14 +609,13 @@ namespace OpenSim.Data.MySQL
{ {
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "delete from land where UUID = ?UUID"; cmd.CommandText = "delete from land where UUID = ?UUID";
cmd.Parameters.AddWithValue("UUID", globalID.ToString()); cmd.Parameters.AddWithValue("UUID", globalID.ToString());
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose(); }
} }
} }
@ -662,8 +623,8 @@ namespace OpenSim.Data.MySQL
{ {
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "replace into land (UUID, RegionUUID, " + cmd.CommandText = "replace into land (UUID, RegionUUID, " +
"LocalLandID, Bitmap, Name, Description, " + "LocalLandID, Bitmap, Name, Description, " +
"OwnerUUID, IsGroupOwned, Area, AuctionID, " + "OwnerUUID, IsGroupOwned, Area, AuctionID, " +
@ -689,8 +650,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.CommandText = "delete from landaccesslist where " + cmd.CommandText = "delete from landaccesslist where LandUUID = ?UUID";
"LandUUID = ?UUID";
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
@ -699,14 +659,13 @@ namespace OpenSim.Data.MySQL
"AccessUUID, Flags) values (?LandUUID, ?AccessUUID, " + "AccessUUID, Flags) values (?LandUUID, ?AccessUUID, " +
"?Flags)"; "?Flags)";
foreach (ParcelManager.ParcelAccessEntry entry in foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList)
parcel.LandData.ParcelAccessList)
{ {
FillLandAccessCommand(cmd, entry, parcel.LandData.GlobalID); FillLandAccessCommand(cmd, entry, parcel.LandData.GlobalID);
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Parameters.Clear(); cmd.Parameters.Clear();
} }
cmd.Dispose(); }
} }
} }
@ -716,15 +675,12 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select * from regionsettings where " + cmd.CommandText = "select * from regionsettings where regionUUID = ?RegionUUID";
"regionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("regionUUID", regionUUID); cmd.Parameters.AddWithValue("regionUUID", regionUUID);
IDataReader reader = ExecuteReader(cmd); using (IDataReader reader = ExecuteReader(cmd))
try
{ {
if (reader.Read()) if (reader.Read())
{ {
@ -740,11 +696,7 @@ namespace OpenSim.Data.MySQL
StoreRegionSettings(rs); StoreRegionSettings(rs);
} }
} }
finally
{
reader.Close();
} }
cmd.Dispose();
} }
return rs; return rs;
@ -754,8 +706,8 @@ namespace OpenSim.Data.MySQL
{ {
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "replace into regionsettings (regionUUID, " + cmd.CommandText = "replace into regionsettings (regionUUID, " +
"block_terraform, block_fly, allow_damage, " + "block_terraform, block_fly, allow_damage, " +
"restrict_pushing, allow_land_resell, " + "restrict_pushing, allow_land_resell, " +
@ -792,8 +744,7 @@ namespace OpenSim.Data.MySQL
FillRegionSettingsCommand(cmd, rs); FillRegionSettingsCommand(cmd, rs);
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.Dispose(); }
} }
} }
@ -803,16 +754,12 @@ namespace OpenSim.Data.MySQL
lock (m_Connection) lock (m_Connection)
{ {
MySqlCommand cmd = m_Connection.CreateCommand(); using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select * from land where " + cmd.CommandText = "select * from land where RegionUUID = ?RegionUUID";
"RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString()); cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
IDataReader reader = ExecuteReader(cmd); using (IDataReader reader = ExecuteReader(cmd))
try
{ {
while (reader.Read()) while (reader.Read())
{ {
@ -820,35 +767,25 @@ namespace OpenSim.Data.MySQL
landData.Add(newLand); landData.Add(newLand);
} }
} }
finally
{
reader.Close();
} }
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
foreach (LandData land in landData) foreach (LandData land in landData)
{ {
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "select * from landaccesslist where LandUUID = ?LandUUID";
cmd.CommandText = "select * from landaccesslist " +
"where LandUUID = ?LandUUID";
cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString()); cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString());
reader = ExecuteReader(cmd); using (IDataReader reader = ExecuteReader(cmd))
try
{ {
while (reader.Read()) while (reader.Read())
{ {
land.ParcelAccessList.Add(BuildLandAccessData(reader)); land.ParcelAccessList.Add(BuildLandAccessData(reader));
} }
} }
finally
{
reader.Close();
} }
} }
cmd.Dispose();
} }
return landData; return landData;

View File

@ -134,8 +134,8 @@ namespace OpenSim.Data.MySQL
/// </summary> /// </summary>
protected void GetWaitTimeout() protected void GetWaitTimeout()
{ {
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon); using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon))
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
if (dbReader.Read()) if (dbReader.Read())
@ -143,9 +143,7 @@ namespace OpenSim.Data.MySQL
m_waitTimeout m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
} }
}
dbReader.Close();
cmd.Dispose();
} }
m_lastConnectionUse = DateTime.Now.Ticks; m_lastConnectionUse = DateTime.Now.Ticks;
@ -303,10 +301,10 @@ namespace OpenSim.Data.MySQL
{ {
CheckConnection(); CheckConnection();
MySqlCommand tablesCmd = using (MySqlCommand tablesCmd = new MySqlCommand(
new MySqlCommand(
"SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname", "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
dbcon); dbcon))
{
tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database); tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
using (MySqlDataReader tables = tablesCmd.ExecuteReader()) using (MySqlDataReader tables = tablesCmd.ExecuteReader())
@ -324,10 +322,10 @@ namespace OpenSim.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
}
} }
} }
tables.Close();
} }
} }
} }
@ -358,7 +356,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
// Return null if it fails. // Return null if it fails.
m_log.Error("Failed during Query generation: " + e.ToString()); m_log.Error("Failed during Query generation: " + e.Message, e);
return null; return null;
} }
} }
@ -694,8 +692,6 @@ namespace OpenSim.Data.MySQL
ret.Add(attachpoint, item); ret.Add(attachpoint, item);
} }
r.Close();
return ret; return ret;
} }

View File

@ -56,13 +56,14 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command); using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?regionName", regionName); cmd.Parameters.AddWithValue("?regionName", regionName);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd); return RunCommand(cmd);
} }
}
public RegionData Get(int posX, int posY, UUID scopeID) public RegionData Get(int posX, int posY, UUID scopeID)
{ {
@ -70,8 +71,8 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command); using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?posX", posX.ToString()); cmd.Parameters.AddWithValue("?posX", posX.ToString());
cmd.Parameters.AddWithValue("?posY", posY.ToString()); cmd.Parameters.AddWithValue("?posY", posY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
@ -82,6 +83,7 @@ namespace OpenSim.Data.MySQL
return ret[0]; return ret[0];
} }
}
public RegionData Get(UUID regionID, UUID scopeID) public RegionData Get(UUID regionID, UUID scopeID)
{ {
@ -89,8 +91,8 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command); using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?regionID", regionID.ToString()); cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
@ -100,6 +102,7 @@ namespace OpenSim.Data.MySQL
return ret[0]; return ret[0];
} }
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{ {
@ -107,8 +110,8 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command); using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?startX", startX.ToString()); cmd.Parameters.AddWithValue("?startX", startX.ToString());
cmd.Parameters.AddWithValue("?startY", startY.ToString()); cmd.Parameters.AddWithValue("?startY", startY.ToString());
cmd.Parameters.AddWithValue("?endX", endX.ToString()); cmd.Parameters.AddWithValue("?endX", endX.ToString());
@ -117,13 +120,14 @@ namespace OpenSim.Data.MySQL
return RunCommand(cmd); return RunCommand(cmd);
} }
}
public List<RegionData> RunCommand(MySqlCommand cmd) public List<RegionData> RunCommand(MySqlCommand cmd)
{ {
List<RegionData> retList = new List<RegionData>(); List<RegionData> retList = new List<RegionData>();
IDataReader result = ExecuteReader(cmd); using (IDataReader result = ExecuteReader(cmd))
{
while (result.Read()) while (result.Read())
{ {
RegionData ret = new RegionData(); RegionData ret = new RegionData();
@ -168,9 +172,7 @@ namespace OpenSim.Data.MySQL
retList.Add(ret); retList.Add(ret);
} }
}
result.Close();
CloseReaderCommand(cmd);
return retList; return retList;
} }
@ -198,8 +200,8 @@ namespace OpenSim.Data.MySQL
string[] fields = new List<string>(data.Data.Keys).ToArray(); string[] fields = new List<string>(data.Data.Keys).ToArray();
MySqlCommand cmd = new MySqlCommand(); using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY"; string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
foreach (string field in fields) foreach (string field in fields)
{ {
@ -233,41 +235,37 @@ namespace OpenSim.Data.MySQL
if (ExecuteNonQuery(cmd) < 1) if (ExecuteNonQuery(cmd) < 1)
{ {
cmd.Dispose();
return false; return false;
} }
} }
}
cmd.Dispose();
return true; return true;
} }
public bool SetDataItem(UUID regionID, string item, string value) public bool SetDataItem(UUID regionID, string item, string value)
{ {
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID"))
"` set `" + item + "` = ?" + item + " where uuid = ?UUID"); {
cmd.Parameters.AddWithValue("?" + item, value); cmd.Parameters.AddWithValue("?" + item, value);
cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0) if (ExecuteNonQuery(cmd) > 0)
return true; return true;
}
return false; return false;
} }
public bool Delete(UUID regionID) public bool Delete(UUID regionID)
{ {
MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID"))
"` where uuid = ?UUID"); {
cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0) if (ExecuteNonQuery(cmd) > 0)
return true; return true;
}
return false; return false;
} }

View File

@ -64,13 +64,13 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero) if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID"; command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command); using (MySqlCommand cmd = new MySqlCommand(command))
{
cmd.Parameters.AddWithValue("?principalID", principalID.ToString()); cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
IDataReader result = ExecuteReader(cmd); using (IDataReader result = ExecuteReader(cmd))
{
if (result.Read()) if (result.Read())
{ {
ret.PrincipalID = principalID; ret.PrincipalID = principalID;
@ -97,14 +97,10 @@ namespace OpenSim.Data.MySQL
ret.Data[s] = result[s].ToString(); ret.Data[s] = result[s].ToString();
} }
result.Close();
CloseReaderCommand(cmd);
return ret; return ret;
} }
}
result.Close(); }
CloseReaderCommand(cmd);
return null; return null;
} }
@ -118,8 +114,8 @@ namespace OpenSim.Data.MySQL
string[] fields = new List<string>(data.Data.Keys).ToArray(); string[] fields = new List<string>(data.Data.Keys).ToArray();
MySqlCommand cmd = new MySqlCommand(); using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `" + m_Realm + "` set "; string update = "update `" + m_Realm + "` set ";
bool first = true; bool first = true;
foreach (string field in fields) foreach (string field in fields)
@ -156,23 +152,22 @@ namespace OpenSim.Data.MySQL
return false; return false;
} }
} }
}
cmd.Dispose();
return true; return true;
} }
public bool SetDataItem(UUID principalID, string item, string value) public bool SetDataItem(UUID principalID, string item, string value)
{ {
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" +
"` set `" + item + "` = ?" + item + " where UUID = ?UUID"); item + "` = ?" + item + " where UUID = ?UUID"))
{
cmd.Parameters.AddWithValue("?" + item, value); cmd.Parameters.AddWithValue("?" + item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString()); cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0) if (ExecuteNonQuery(cmd) > 0)
return true; return true;
}
return false; return false;
} }

View File

@ -181,21 +181,20 @@ namespace OpenSim.Data.MySQL
param["?first"] = user; param["?first"] = user;
param["?second"] = last; param["?second"] = last;
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query( "SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param))
"SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param); {
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
UserProfileData row = dbm.Manager.readUserRow(reader); UserProfileData row = dbm.Manager.readUserRow(reader);
reader.Dispose();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -220,28 +219,30 @@ namespace OpenSim.Data.MySQL
try try
{ {
IDbCommand adder = using (IDbCommand adder = dbm.Manager.Query(
dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " + "INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " + "VALUES " +
"(?ownerID,?friendID,?friendPerms,?datetimestamp)", "(?ownerID,?friendID,?friendPerms,?datetimestamp)",
param); param))
{
adder.ExecuteNonQuery(); adder.ExecuteNonQuery();
}
adder = using (IDbCommand adder = dbm.Manager.Query(
dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " + "INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " + "VALUES " +
"(?friendID,?ownerID,?friendPerms,?datetimestamp)", "(?friendID,?ownerID,?friendPerms,?datetimestamp)",
param); param))
{
adder.ExecuteNonQuery(); adder.ExecuteNonQuery();
} }
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return; return;
} }
finally finally
@ -260,22 +261,24 @@ namespace OpenSim.Data.MySQL
try try
{ {
IDbCommand updater = using (IDbCommand updater = dbm.Manager.Query(
dbm.Manager.Query(
"delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID", "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
param); param))
{
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
}
updater = using (IDbCommand updater = dbm.Manager.Query(
dbm.Manager.Query(
"delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID", "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
param); param))
{
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
} }
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return; return;
} }
finally finally
@ -295,18 +298,19 @@ namespace OpenSim.Data.MySQL
try try
{ {
IDbCommand updater = using (IDbCommand updater = dbm.Manager.Query(
dbm.Manager.Query(
"update " + m_userFriendsTableName + "update " + m_userFriendsTableName +
" SET friendPerms = ?friendPerms " + " SET friendPerms = ?friendPerms " +
"where ownerID = ?ownerID and friendID = ?friendID", "where ownerID = ?ownerID and friendID = ?friendID",
param); param))
{
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
} }
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return; return;
} }
finally finally
@ -327,14 +331,14 @@ namespace OpenSim.Data.MySQL
try try
{ {
//Left Join userfriends to itself //Left Join userfriends to itself
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " +
m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" + m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
" where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID", " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
FriendListItem fli = new FriendListItem(); FriendListItem fli = new FriendListItem();
@ -347,14 +351,13 @@ namespace OpenSim.Data.MySQL
Lfli.Add(fli); Lfli.Add(fli);
} }
}
reader.Dispose(); }
result.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return Lfli; return Lfli;
} }
finally finally
@ -376,11 +379,12 @@ namespace OpenSim.Data.MySQL
{ {
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString(); param["?uuid"] = uuid.ToString();
IDbCommand result =
dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
" where UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader(); using (IDbCommand result = dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
" where UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
FriendRegionInfo fri = new FriendRegionInfo(); FriendRegionInfo fri = new FriendRegionInfo();
@ -389,16 +393,15 @@ namespace OpenSim.Data.MySQL
infos[uuid] = fri; infos[uuid] = fri;
} }
}
reader.Dispose(); }
result.Dispose();
} }
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e); m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e);
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
finally finally
{ {
@ -427,13 +430,13 @@ namespace OpenSim.Data.MySQL
try try
{ {
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName + "SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first AND lastname like ?second LIMIT 100", " WHERE username like ?first AND lastname like ?second LIMIT 100",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
AvatarPickerAvatar user = new AvatarPickerAvatar(); AvatarPickerAvatar user = new AvatarPickerAvatar();
@ -442,13 +445,13 @@ namespace OpenSim.Data.MySQL
user.lastName = (string)reader["lastname"]; user.lastName = (string)reader["lastname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Dispose(); }
result.Dispose(); }
} }
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return returnlist; return returnlist;
} }
finally finally
@ -465,13 +468,13 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%"; param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
IDbCommand result = using (IDbCommand result = dbm.Manager.Query(
dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName + "SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first OR lastname like ?first LIMIT 100", " WHERE username like ?first OR lastname like ?first LIMIT 100",
param); param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read()) while (reader.Read())
{ {
AvatarPickerAvatar user = new AvatarPickerAvatar(); AvatarPickerAvatar user = new AvatarPickerAvatar();
@ -480,13 +483,13 @@ namespace OpenSim.Data.MySQL
user.lastName = (string)reader["lastname"]; user.lastName = (string)reader["lastname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Dispose(); }
result.Dispose(); }
} }
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return returnlist; return returnlist;
} }
finally finally
@ -510,20 +513,19 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString(); param["?uuid"] = uuid.ToString();
IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param); using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
UserProfileData row = dbm.Manager.readUserRow(reader); UserProfileData row = dbm.Manager.readUserRow(reader);
reader.Dispose();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -577,7 +579,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return; return;
} }
finally finally
@ -600,21 +602,19 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString(); param["?uuid"] = uuid.ToString();
IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param))
param); {
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
UserAgentData row = dbm.Manager.readAgentRow(reader); UserAgentData row = dbm.Manager.readAgentRow(reader);
reader.Dispose();
result.Dispose();
return row; return row;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -638,7 +638,8 @@ namespace OpenSim.Data.MySQL
try try
{ {
dbm.Manager.insertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, dbm.Manager.insertUserRow(
user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z, user.HomeLocation.Z,
user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
@ -650,7 +651,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
finally finally
{ {
@ -676,7 +677,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
finally finally
{ {
@ -693,7 +694,8 @@ namespace OpenSim.Data.MySQL
MySQLSuperManager dbm = GetLockedConnection("UpdateUserProfile"); MySQLSuperManager dbm = GetLockedConnection("UpdateUserProfile");
try try
{ {
dbm.Manager.updateUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, dbm.Manager.updateUserRow(
user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z, user.HomeLookAt.X, user.HomeLocation.Z, user.HomeLookAt.X,
user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin,
@ -748,29 +750,29 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>(); Dictionary<string, object> param = new Dictionary<string, object>();
param["?owner"] = user.ToString(); param["?owner"] = user.ToString();
IDbCommand result = dbm.Manager.Query( using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param))
"SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param); {
IDataReader reader = result.ExecuteReader(); using (IDataReader reader = result.ExecuteReader())
{
AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader); AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader);
reader.Dispose(); if (appearance == null)
result.Dispose();
if (null == appearance)
{ {
m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString());
return null; return null;
} }
else
{
appearance.SetAttachments(GetUserAttachments(user)); appearance.SetAttachments(GetUserAttachments(user));
return appearance; return appearance;
} }
}
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -798,7 +800,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
finally finally
{ {
@ -833,20 +835,20 @@ namespace OpenSim.Data.MySQL
try try
{ {
IDbCommand result = dbm.Manager.Query( using (IDbCommand result = dbm.Manager.Query(
"SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param); "SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param))
IDataReader reader = result.ExecuteReader(); {
using (IDataReader reader = result.ExecuteReader())
{
Hashtable ret = dbm.Manager.readAttachments(reader); Hashtable ret = dbm.Manager.readAttachments(reader);
reader.Dispose();
result.Dispose();
return ret; return ret;
} }
}
}
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return null; return null;
} }
finally finally
@ -905,7 +907,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
dbm.Manager.Reconnect(); dbm.Manager.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
return; return;
} }
finally finally

View File

@ -581,8 +581,10 @@ namespace OpenSim.Data.SQLite
if (row.Read()) if (row.Read())
{ {
// TODO: put this into a function // TODO: put this into a function
MemoryStream str = new MemoryStream((byte[]) row["Heightfield"]); using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"]))
BinaryReader br = new BinaryReader(str); {
using (BinaryReader br = new BinaryReader(str))
{
for (int x = 0; x < (int)Constants.RegionSize; x++) for (int x = 0; x < (int)Constants.RegionSize; x++)
{ {
for (int y = 0; y < (int)Constants.RegionSize; y++) for (int y = 0; y < (int)Constants.RegionSize; y++)
@ -590,6 +592,8 @@ namespace OpenSim.Data.SQLite
terret[x, y] = br.ReadDouble(); terret[x, y] = br.ReadDouble();
} }
} }
}
}
rev = (int) row["Revision"]; rev = (int) row["Revision"];
} }
else else

View File

@ -49,7 +49,7 @@ namespace OpenSim.Framework
private void InternData() private void InternData()
{ {
string temp = Encoding.UTF8.GetString(Data).Trim(); string temp = Util.UTF8.GetString(Data).Trim();
string[] parts = temp.Split('\n'); string[] parts = temp.Split('\n');
int.TryParse(parts[0].Substring(17, 1), out Version); int.TryParse(parts[0].Substring(17, 1), out Version);
UUID.TryParse(parts[1].Substring(10, 36), out RegionID); UUID.TryParse(parts[1].Substring(10, 36), out RegionID);

View File

@ -112,7 +112,7 @@ namespace OpenSim.Framework.Capabilities
writer.Close(); writer.Close();
return Encoding.UTF8.GetBytes(sw.ToString()); return Util.UTF8.GetBytes(sw.ToString());
} }
/// <summary> /// <summary>
@ -329,7 +329,7 @@ namespace OpenSim.Framework.Capabilities
reader.Read(); reader.Read();
FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces);
byte[] inp = Encoding.UTF8.GetBytes(reader.ReadString()); byte[] inp = Util.UTF8.GetBytes(reader.ReadString());
ret = b64.TransformFinalBlock(inp, 0, inp.Length); ret = b64.TransformFinalBlock(inp, 0, inp.Length);
break; break;
} }

View File

@ -47,7 +47,7 @@ namespace OpenSim.Framework.Capabilities
public override byte[] Handle(string path, Stream request, public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse) OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{ {
//Encoding encoding = Encoding.UTF8; //Encoding encoding = Util.UTF8;
//StreamReader streamReader = new StreamReader(request, false); //StreamReader streamReader = new StreamReader(request, false);
//string requestBody = streamReader.ReadToEnd(); //string requestBody = streamReader.ReadToEnd();

View File

@ -106,7 +106,6 @@ namespace OpenSim.Framework.Communications.Clients
AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = AgentCreateRequest.GetRequestStream(); os = AgentCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri); //m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
} }
//catch (WebException ex) //catch (WebException ex)
@ -116,6 +115,11 @@ namespace OpenSim.Framework.Communications.Clients
reason = "cannot contact remote region"; reason = "cannot contact remote region";
return false; return false;
} }
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response // Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
@ -224,7 +228,6 @@ namespace OpenSim.Framework.Communications.Clients
ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ChildUpdateRequest.GetRequestStream(); os = ChildUpdateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri); //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
} }
//catch (WebException ex) //catch (WebException ex)
@ -234,6 +237,11 @@ namespace OpenSim.Framework.Communications.Clients
return false; return false;
} }
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response // Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate"); //m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
@ -437,7 +445,6 @@ namespace OpenSim.Framework.Communications.Clients
ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ObjectCreateRequest.GetRequestStream(); os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri); m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
} }
//catch (WebException ex) //catch (WebException ex)
@ -447,6 +454,11 @@ namespace OpenSim.Framework.Communications.Clients
return false; return false;
} }
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response // Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
@ -512,7 +524,6 @@ namespace OpenSim.Framework.Communications.Clients
ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ObjectCreateRequest.GetRequestStream(); os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri); //m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri);
} }
//catch (WebException ex) //catch (WebException ex)
@ -522,6 +533,11 @@ namespace OpenSim.Framework.Communications.Clients
return false; return false;
} }
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response // Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
@ -597,7 +613,6 @@ namespace OpenSim.Framework.Communications.Clients
HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
os = HelloNeighbourRequest.GetRequestStream(); os = HelloNeighbourRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri); //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
} }
//catch (WebException ex) //catch (WebException ex)
@ -607,7 +622,11 @@ namespace OpenSim.Framework.Communications.Clients
return false; return false;
} }
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response // Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall"); //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");

View File

@ -38,7 +38,7 @@ namespace OpenSim.Framework.Communications.XMPP
{ {
} }
public XMPPWriter(IOStream stream) : this(stream, Encoding.UTF8) public XMPPWriter(IOStream stream) : this(stream, Util.UTF8)
{ {
} }

View File

@ -77,7 +77,7 @@ namespace OpenSim.Framework.Configuration.HTTP
count = resStream.Read(buf, 0, buf.Length); count = resStream.Read(buf, 0, buf.Length);
if (count != 0) if (count != 0)
{ {
tempString = Encoding.UTF8.GetString(buf, 0, count); tempString = Util.UTF8.GetString(buf, 0, count);
sb.Append(tempString); sb.Append(tempString);
} }
} while (count > 0); } while (count > 0);

View File

@ -91,24 +91,35 @@ namespace OpenSim.Framework.Servers.HttpServer
Stream requestStream = request.EndGetRequestStream(res); Stream requestStream = request.EndGetRequestStream(res);
requestStream.Write(buffer.ToArray(), 0, length); requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
request.BeginGetResponse(delegate(IAsyncResult ar) request.BeginGetResponse(delegate(IAsyncResult ar)
{ {
response = request.EndGetResponse(ar); response = request.EndGetResponse(ar);
Stream respStream = null;
try try
{ {
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize( deserial = (TResponse)deserializer.Deserialize(
response.GetResponseStream()); respStream);
} }
catch (System.InvalidOperationException) catch (System.InvalidOperationException)
{ {
} }
finally
{
// Let's not close this
//buffer.Close();
respStream.Close();
response.Close();
}
action(deserial); action(deserial);
}, null); }, null);
}, null); }, null);
return; return;
} }
@ -120,13 +131,20 @@ namespace OpenSim.Framework.Servers.HttpServer
// documented in MSDN // documented in MSDN
response = request.EndGetResponse(res2); response = request.EndGetResponse(res2);
Stream respStream = null;
try try
{ {
deserial = (TResponse)deserializer.Deserialize(response.GetResponseStream()); respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
} }
catch (System.InvalidOperationException) catch (System.InvalidOperationException)
{ {
} }
finally
{
respStream.Close();
response.Close();
}
} }
catch (WebException e) catch (WebException e)
{ {
@ -148,7 +166,7 @@ namespace OpenSim.Framework.Servers.HttpServer
} }
else else
{ {
m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e); m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
} }
} }
catch (Exception e) catch (Exception e)

View File

@ -979,7 +979,7 @@ namespace OpenSim.Framework.Servers.HttpServer
} }
// response.ContentType = "application/llsd+json"; // response.ContentType = "application/llsd+json";
// return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse)); // return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(llsdResponse));
response.ContentType = "application/llsd+xml"; response.ContentType = "application/llsd+xml";
return OSDParser.SerializeLLSDXmlBytes(llsdResponse); return OSDParser.SerializeLLSDXmlBytes(llsdResponse);
} }

View File

@ -94,14 +94,27 @@ namespace OpenSim.Framework.Servers.HttpServer
Stream requestStream = request.GetRequestStream(); Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length); requestStream.Write(buffer.ToArray(), 0, length);
buffer.Close();
requestStream.Close(); requestStream.Close();
TResponse deserial = default(TResponse); TResponse deserial = default(TResponse);
using (WebResponse resp = request.GetResponse()) using (WebResponse resp = request.GetResponse())
{ {
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
deserial = (TResponse)deserializer.Deserialize(resp.GetResponseStream()); Stream respStream = null;
try
{
respStream = resp.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch { }
finally
{
if (respStream != null)
respStream.Close();
resp.Close(); resp.Close();
} }
}
return deserial; return deserial;
} }
} }
@ -140,6 +153,7 @@ namespace OpenSim.Framework.Servers.HttpServer
serializer.Serialize(writer, sobj); serializer.Serialize(writer, sobj);
writer.Flush(); writer.Flush();
} }
buffer.Close();
int length = (int)buffer.Length; int length = (int)buffer.Length;
request.ContentLength = length; request.ContentLength = length;
@ -165,6 +179,8 @@ namespace OpenSim.Framework.Servers.HttpServer
// m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd()); // m_log.DebugFormat("[REST OBJECT POSTER RESPONSE]: Received {0}", reader.ReadToEnd());
deserial = (TResponse)deserializer.Deserialize(stream); deserial = (TResponse)deserializer.Deserialize(stream);
if (stream != null)
stream.Close();
if (deserial != null && ResponseCallback != null) if (deserial != null && ResponseCallback != null)
{ {

View File

@ -66,9 +66,24 @@ namespace OpenSim.Framework.Servers.HttpServer
length = (int)obj.Length; length = (int)obj.Length;
request.ContentLength = length; request.ContentLength = length;
Stream requestStream = request.GetRequestStream(); Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length); requestStream.Write(buffer.ToArray(), 0, length);
} }
catch
{
}
finally
{
if (requestStream != null)
requestStream.Close();
// Let's not close this
//buffer.Close();
}
}
string respstring = String.Empty; string respstring = String.Empty;
@ -78,11 +93,22 @@ namespace OpenSim.Framework.Servers.HttpServer
{ {
if (resp.ContentLength > 0) if (resp.ContentLength > 0)
{ {
using (StreamReader reader = new StreamReader(resp.GetResponseStream())) Stream respStream = null;
try
{
respStream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(respStream))
{ {
respstring = reader.ReadToEnd(); respstring = reader.ReadToEnd();
} }
} }
catch { }
finally
{
if (respStream != null)
respStream.Close();
}
}
} }
} }
catch (System.InvalidOperationException) catch (System.InvalidOperationException)

View File

@ -58,6 +58,7 @@ namespace OpenSim.Framework.Servers.HttpServer
public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj) public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
{ {
Type type = typeof (TRequest); Type type = typeof (TRequest);
TResponse deserial = default(TResponse);
WebRequest request = WebRequest.Create(requestUrl); WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb; request.Method = verb;
@ -81,19 +82,33 @@ namespace OpenSim.Framework.Servers.HttpServer
int length = (int) buffer.Length; int length = (int) buffer.Length;
request.ContentLength = length; request.ContentLength = length;
Stream requestStream = request.GetRequestStream(); Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length); requestStream.Write(buffer.ToArray(), 0, length);
} }
catch (Exception)
{
return deserial;
}
finally
{
if (requestStream != null)
requestStream.Close();
}
}
TResponse deserial = default(TResponse);
try try
{ {
using (WebResponse resp = request.GetResponse()) using (WebResponse resp = request.GetResponse())
{ {
if (resp.ContentLength > 0) if (resp.ContentLength > 0)
{ {
Stream respStream = resp.GetResponseStream();
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
deserial = (TResponse)deserializer.Deserialize(resp.GetResponseStream()); deserial = (TResponse)deserializer.Deserialize(respStream);
respStream.Close();
} }
} }
} }

View File

@ -103,6 +103,8 @@ namespace OpenSim.Framework
} }
public static Encoding UTF8 = Encoding.UTF8;
/// <value> /// <value>
/// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards) /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
/// </value> /// </value>
@ -465,7 +467,7 @@ namespace OpenSim.Framework
output.Append(": "); output.Append(": ");
} }
output.Append(CleanString(Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1))); output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
} }
else else
{ {
@ -826,7 +828,7 @@ namespace OpenSim.Framework
public static string Compress(string text) public static string Compress(string text)
{ {
byte[] buffer = Encoding.UTF8.GetBytes(text); byte[] buffer = Util.UTF8.GetBytes(text);
MemoryStream memory = new MemoryStream(); MemoryStream memory = new MemoryStream();
using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true)) using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
{ {
@ -860,7 +862,7 @@ namespace OpenSim.Framework
decompressor.Read(buffer, 0, buffer.Length); decompressor.Read(buffer, 0, buffer.Length);
} }
return Encoding.UTF8.GetString(buffer); return Util.UTF8.GetString(buffer);
} }
} }
@ -1132,7 +1134,7 @@ namespace OpenSim.Framework
{ {
byte[] data = new byte[length]; byte[] data = new byte[length];
stream.Read(data, 0, length); stream.Read(data, 0, length);
string strdata = Encoding.UTF8.GetString(data); string strdata = Util.UTF8.GetString(data);
OSDMap args = null; OSDMap args = null;
OSD buffer; OSD buffer;
buffer = OSDParser.DeserializeJson(strdata); buffer = OSDParser.DeserializeJson(strdata);

View File

@ -39,6 +39,10 @@ using OpenSim.Data;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Grid.Framework; using OpenSim.Grid.Framework;
using Timer = System.Timers.Timer; using Timer = System.Timers.Timer;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Grid.MessagingServer.Modules namespace OpenSim.Grid.MessagingServer.Modules
{ {
@ -52,6 +56,8 @@ namespace OpenSim.Grid.MessagingServer.Modules
private IGridServiceCore m_messageCore; private IGridServiceCore m_messageCore;
private IGridService m_GridService;
// a dictionary of all current regions this server knows about // a dictionary of all current regions this server knows about
private Dictionary<ulong, RegionProfileData> m_regionInfoCache = new Dictionary<ulong, RegionProfileData>(); private Dictionary<ulong, RegionProfileData> m_regionInfoCache = new Dictionary<ulong, RegionProfileData>();
@ -59,6 +65,8 @@ namespace OpenSim.Grid.MessagingServer.Modules
{ {
m_cfg = config; m_cfg = config;
m_messageCore = messageCore; m_messageCore = messageCore;
m_GridService = new GridServicesConnector(m_cfg.GridServerURL);
} }
public void Initialise() public void Initialise()
@ -134,51 +142,30 @@ namespace OpenSim.Grid.MessagingServer.Modules
/// <returns></returns> /// <returns></returns>
public RegionProfileData RequestRegionInfo(ulong regionHandle) public RegionProfileData RequestRegionInfo(ulong regionHandle)
{ {
RegionProfileData regionProfile = null; uint x = 0, y = 0;
try Utils.LongToUInts(regionHandle, out x, out y);
{ GridRegion region = m_GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
Hashtable requestData = new Hashtable();
requestData["region_handle"] = regionHandle.ToString();
requestData["authkey"] = m_cfg.GridSendKey;
ArrayList SendParams = new ArrayList(); if (region != null)
SendParams.Add(requestData); return GridRegionToRegionProfile(region);
XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); else
XmlRpcResponse GridResp = GridReq.Send(m_cfg.GridServerURL, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("error"))
{
m_log.Error("[GRID]: error received from grid server" + responseData["error"]);
return null; return null;
} }
uint regX = Convert.ToUInt32((string)responseData["region_locx"]); private RegionProfileData GridRegionToRegionProfile(GridRegion region)
uint regY = Convert.ToUInt32((string)responseData["region_locy"]);
string internalIpStr = (string)responseData["sim_ip"];
regionProfile = new RegionProfileData();
regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]);
regionProfile.httpServerURI = "http://" + internalIpStr + ":" + regionProfile.httpPort + "/";
regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize));
regionProfile.regionLocX = regX;
regionProfile.regionLocY = regY;
regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
regionProfile.UUID = new UUID((string)responseData["region_UUID"]);
regionProfile.regionName = (string)responseData["region_name"];
}
catch (WebException)
{ {
m_log.Error("[GRID]: " + RegionProfileData rprofile = new RegionProfileData();
"Region lookup failed for: " + regionHandle.ToString() + rprofile.httpPort = region.HttpPort;
" - Is the GridServer down?"); rprofile.httpServerURI = region.ServerURI;
} rprofile.regionLocX = (uint)(region.RegionLocX / Constants.RegionSize);
rprofile.regionLocY = (uint)(region.RegionLocY / Constants.RegionSize);
return regionProfile; rprofile.RegionName = region.RegionName;
rprofile.ServerHttpPort = region.HttpPort;
rprofile.ServerIP = region.ExternalHostName;
rprofile.ServerPort = (uint)region.ExternalEndPoint.Port;
rprofile.Uuid = region.RegionID;
return rprofile;
} }
public XmlRpcResponse RegionStartup(XmlRpcRequest request, IPEndPoint remoteClient) public XmlRpcResponse RegionStartup(XmlRpcRequest request, IPEndPoint remoteClient)

View File

@ -317,6 +317,7 @@ namespace OpenSim.Grid.UserServer.Modules
{ {
m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName);
appearance = new AvatarAppearance(user.ID); appearance = new AvatarAppearance(user.ID);
loginParams["appearance"] = appearance.ToHashTable();
} }
ArrayList SendParams = new ArrayList(); ArrayList SendParams = new ArrayList();

View File

@ -205,13 +205,10 @@ namespace OpenSim
Directory.CreateDirectory(m_crashDir); Directory.CreateDirectory(m_crashDir);
} }
string log = Util.GetUniqueFilename(ex.GetType() + ".txt"); string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
StreamWriter m_crashLog = using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
new StreamWriter( {
Path.Combine(m_crashDir, log)
);
m_crashLog.WriteLine(msg); m_crashLog.WriteLine(msg);
m_crashLog.Close(); }
File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true); File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true);
} }

View File

@ -699,7 +699,7 @@ namespace OpenSim
public byte[] Handle(string path, Stream request, public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse) OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{ {
return Encoding.UTF8.GetBytes("OK"); return Util.UTF8.GetBytes("OK");
} }
public string ContentType public string ContentType
@ -736,7 +736,7 @@ namespace OpenSim
public byte[] Handle(string path, Stream request, public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse) OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{ {
return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
} }
public string ContentType public string ContentType
@ -777,7 +777,7 @@ namespace OpenSim
public byte[] Handle(string path, Stream request, public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse) OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{ {
return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest)); return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
} }
public string ContentType public string ContentType

View File

@ -47,69 +47,26 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public uint m_lastSequence; public uint LastSequence;
public float m_requestedPriority; public float Priority;
public uint m_requestedPacketNumber; public uint StartPacket;
public sbyte m_requestedDiscardLevel; public sbyte DiscardLevel;
public UUID m_requestedUUID; public UUID TextureID;
public IJ2KDecoder m_j2kDecodeModule; public IJ2KDecoder J2KDecoder;
public IAssetService m_assetCache; public IAssetService AssetService;
public OpenJPEG.J2KLayerInfo[] m_layers; public OpenJPEG.J2KLayerInfo[] Layers;
public bool m_decoded; public bool IsDecoded;
public bool m_hasasset; public bool HasAsset;
public C5.IPriorityQueueHandle<J2KImage> m_priorityQueueHandle; public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle;
private uint m_packetNumber; private uint m_currentPacket;
private bool m_decoderequested; private bool m_decodeRequested;
private bool m_asset_requested; private bool m_assetRequested;
private bool m_sentinfo; private bool m_sentInfo;
private uint m_stopPacket; private uint m_stopPacket;
private AssetBase m_asset; private byte[] m_asset;
private int m_assetDataLength;
private LLImageManager m_imageManager; private LLImageManager m_imageManager;
#region Properties
public uint m_pPacketNumber
{
get { return m_packetNumber; }
}
public uint m_pStopPacketNumber
{
get { return m_stopPacket; }
}
public byte[] Data
{
get
{
if (m_asset != null)
return m_asset.Data;
else
return null;
}
}
public ushort TexturePacketCount()
{
if (!m_decoded)
return 0;
try
{
return (ushort)(((m_assetDataLength - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
}
catch (Exception)
{
// If the asset is missing/destroyed/truncated, we will land
// here
//
return 0;
}
}
#endregion Properties
public J2KImage(LLImageManager imageManager) public J2KImage(LLImageManager imageManager)
{ {
m_imageManager = imageManager; m_imageManager = imageManager;
@ -117,33 +74,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public bool SendPackets(LLClientView client, int maxpack) public bool SendPackets(LLClientView client, int maxpack)
{ {
if (m_packetNumber <= m_stopPacket) if (m_currentPacket <= m_stopPacket)
{ {
bool SendMore = true; bool SendMore = true;
if (!m_sentinfo || (m_packetNumber == 0)) if (!m_sentInfo || (m_currentPacket == 0))
{ {
if (SendFirstPacket(client)) if (SendFirstPacket(client))
{ {
SendMore = false; SendMore = false;
} }
m_sentinfo = true; m_sentInfo = true;
m_packetNumber++; m_currentPacket++;
} }
// bool ignoreStop = false; if (m_currentPacket < 2)
if (m_packetNumber < 2)
{ {
m_packetNumber = 2; m_currentPacket = 2;
} }
int count = 0; int count = 0;
while (SendMore && count < maxpack && m_packetNumber <= m_stopPacket) while (SendMore && count < maxpack && m_currentPacket <= m_stopPacket)
{ {
count++; count++;
SendMore = SendPacket(client); SendMore = SendPacket(client);
m_packetNumber++; m_currentPacket++;
} }
if (m_packetNumber > m_stopPacket) if (m_currentPacket > m_stopPacket)
return true; return true;
} }
@ -156,68 +112,76 @@ namespace OpenSim.Region.ClientStack.LindenUDP
//and assign the real discardLevel and packetNumber //and assign the real discardLevel and packetNumber
//assuming of course that the connected client might be bonkers //assuming of course that the connected client might be bonkers
if (!m_hasasset) if (!HasAsset)
{ {
if (!m_asset_requested) if (!m_assetRequested)
{ {
m_asset_requested = true; m_assetRequested = true;
m_assetCache.Get(m_requestedUUID.ToString(), this, AssetReceived); AssetService.Get(TextureID.ToString(), this, AssetReceived);
} }
} }
else else
{ {
if (!m_decoded) if (!IsDecoded)
{ {
//We need to decode the requested image first //We need to decode the requested image first
if (!m_decoderequested) if (!m_decodeRequested)
{ {
//Request decode //Request decode
m_decoderequested = true; m_decodeRequested = true;
// Do we have a jpeg decoder? // Do we have a jpeg decoder?
if (m_j2kDecodeModule != null) if (J2KDecoder != null)
{ {
if (Data == null) if (m_asset == null)
{ {
J2KDecodedCallback(m_requestedUUID, new OpenJPEG.J2KLayerInfo[0]); J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
} }
else else
{ {
// Send it off to the jpeg decoder // Send it off to the jpeg decoder
m_j2kDecodeModule.BeginDecode(m_requestedUUID, Data, J2KDecodedCallback); J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback);
} }
} }
else else
{ {
J2KDecodedCallback(m_requestedUUID, new OpenJPEG.J2KLayerInfo[0]); J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
} }
} }
} }
else else
{ {
// Check for missing image asset data // Check for missing image asset data
if (m_asset == null || m_asset.Data == null) if (m_asset == null)
{ {
// FIXME: m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer");
m_packetNumber = m_stopPacket; m_currentPacket = m_stopPacket;
return; return;
} }
if (m_requestedDiscardLevel >= 0 || m_stopPacket == 0) if (DiscardLevel >= 0 || m_stopPacket == 0)
{ {
int maxDiscardLevel = Math.Max(0, m_layers.Length - 1); // This shouldn't happen, but if it does, we really can't proceed
if (Layers == null)
{
m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer");
m_currentPacket = m_stopPacket;
return;
}
int maxDiscardLevel = Math.Max(0, Layers.Length - 1);
// Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel // Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel
if (m_requestedDiscardLevel < 0 && m_stopPacket == 0) if (DiscardLevel < 0 && m_stopPacket == 0)
m_requestedDiscardLevel = (sbyte)maxDiscardLevel; DiscardLevel = (sbyte)maxDiscardLevel;
// Clamp at the highest discard level // Clamp at the highest discard level
m_requestedDiscardLevel = (sbyte)Math.Min(m_requestedDiscardLevel, maxDiscardLevel); DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel);
//Calculate the m_stopPacket //Calculate the m_stopPacket
if (m_layers.Length > 0) if (Layers.Length > 0)
{ {
m_stopPacket = (uint)GetPacketForBytePosition(m_layers[(m_layers.Length - 1) - m_requestedDiscardLevel].End); m_stopPacket = (uint)GetPacketForBytePosition(Layers[(Layers.Length - 1) - DiscardLevel].End);
//I don't know why, but the viewer seems to expect the final packet if the file //I don't know why, but the viewer seems to expect the final packet if the file
//is just one packet bigger. //is just one packet bigger.
if (TexturePacketCount() == m_stopPacket + 1) if (TexturePacketCount() == m_stopPacket + 1)
@ -230,9 +194,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_stopPacket = TexturePacketCount(); m_stopPacket = TexturePacketCount();
} }
m_packetNumber = m_requestedPacketNumber; m_currentPacket = StartPacket;
} }
if ((m_imageManager != null) && (m_imageManager.Client != null) && (m_imageManager.Client.PacketHandler != null))
if (m_imageManager.Client.PacketHandler.GetQueueCount(ThrottleOutPacketType.Texture) == 0) if (m_imageManager.Client.PacketHandler.GetQueueCount(ThrottleOutPacketType.Texture) == 0)
{ {
//m_log.Debug("No textures queued, sending one packet to kickstart it"); //m_log.Debug("No textures queued, sending one packet to kickstart it");
@ -242,20 +207,52 @@ namespace OpenSim.Region.ClientStack.LindenUDP
} }
} }
private bool SendFirstPacket(LLClientView client)
{
if (m_asset == null)
{
m_log.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID);
client.SendImageNotFound(TextureID);
return true;
}
else if (m_asset.Length <= FIRST_PACKET_SIZE)
{
// We have less then one packet's worth of data
client.SendImageFirstPart(1, TextureID, (uint)m_asset.Length, m_asset, 2);
m_stopPacket = 0;
return true;
}
else
{
// This is going to be a multi-packet texture download
byte[] firstImageData = new byte[FIRST_PACKET_SIZE];
try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); }
catch (Exception)
{
m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length);
return true;
}
client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint)m_asset.Length, firstImageData, (byte)ImageCodec.J2C);
}
return false;
}
private bool SendPacket(LLClientView client) private bool SendPacket(LLClientView client)
{ {
bool complete = false; bool complete = false;
int imagePacketSize = ((int)m_packetNumber == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE; int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;
try try
{ {
if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_assetDataLength) if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length)
{ {
imagePacketSize = LastPacketSize(); imagePacketSize = LastPacketSize();
complete = true; complete = true;
if ((CurrentBytePosition() + imagePacketSize) > m_assetDataLength) if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length)
{ {
imagePacketSize = m_assetDataLength - CurrentBytePosition(); imagePacketSize = m_asset.Length - CurrentBytePosition();
complete = true; complete = true;
} }
} }
@ -266,27 +263,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (imagePacketSize > 0) if (imagePacketSize > 0)
{ {
byte[] imageData = new byte[imagePacketSize]; byte[] imageData = new byte[imagePacketSize];
try int currentPosition = CurrentBytePosition();
{
Buffer.BlockCopy(m_asset.Data, CurrentBytePosition(), imageData, 0, imagePacketSize); try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); }
}
catch (Exception e) catch (Exception e)
{ {
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()); m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}",
TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message);
return false; return false;
} }
//Send the packet //Send the packet
client.SendImageNextPart((ushort)(m_packetNumber - 1), m_requestedUUID, imageData); client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData);
}
if (complete)
{
return false;
}
else
{
return true;
} }
return !complete;
} }
catch (Exception) catch (Exception)
{ {
@ -294,6 +285,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
} }
} }
private ushort TexturePacketCount()
{
if (!IsDecoded)
return 0;
if (m_asset == null)
return 0;
if (m_asset.Length <= FIRST_PACKET_SIZE)
return 1;
return (ushort)(((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
}
private int GetPacketForBytePosition(int bytePosition) private int GetPacketForBytePosition(int bytePosition)
{ {
return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1; return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1;
@ -301,9 +306,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private int LastPacketSize() private int LastPacketSize()
{ {
if (m_packetNumber == 1) if (m_currentPacket == 1)
return m_assetDataLength; return m_asset.Length;
int lastsize = (m_assetDataLength - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE; int lastsize = (m_asset.Length - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE;
//If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary //If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary
if (lastsize == 0) if (lastsize == 0)
{ {
@ -314,12 +319,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private int CurrentBytePosition() private int CurrentBytePosition()
{ {
if (m_packetNumber == 0) if (m_currentPacket == 0)
return 0; return 0;
if (m_packetNumber == 1) if (m_currentPacket == 1)
return FIRST_PACKET_SIZE; return FIRST_PACKET_SIZE;
int result = FIRST_PACKET_SIZE + ((int)m_packetNumber - 2) * IMAGE_PACKET_SIZE; int result = FIRST_PACKET_SIZE + ((int)m_currentPacket - 2) * IMAGE_PACKET_SIZE;
if (result < 0) if (result < 0)
{ {
result = FIRST_PACKET_SIZE; result = FIRST_PACKET_SIZE;
@ -327,68 +332,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
return result; return result;
} }
private bool SendFirstPacket(LLClientView client)
{
// this means we don't have
if (Data == null)
{
client.SendImageNotFound(m_requestedUUID);
m_log.WarnFormat("[TEXTURE]: Got null Data element on a asset {0}.. and the missing image Data property is also null", m_requestedUUID);
return true;
}
// Do we have less then 1 packet's worth of data?
else if (m_assetDataLength <= FIRST_PACKET_SIZE)
{
// Send only 1 packet
client.SendImageFirstPart(1, m_requestedUUID, (uint)m_assetDataLength, m_asset.Data, 2);
m_stopPacket = 0;
return true;
}
else
{
byte[] firstImageData = new byte[FIRST_PACKET_SIZE];
try
{
Buffer.BlockCopy(m_asset.Data, 0, firstImageData, 0, (int)FIRST_PACKET_SIZE);
client.SendImageFirstPart(TexturePacketCount(), m_requestedUUID, (uint)m_assetDataLength, firstImageData, 2);
}
catch (Exception)
{
m_log.Error("Texture block copy failed. Possibly out of memory?");
return true;
}
}
return false;
}
private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers) private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers)
{ {
m_layers = layers; Layers = layers;
m_decoded = true; IsDecoded = true;
RunUpdate(); RunUpdate();
} }
private void AssetDataCallback(UUID AssetID, AssetBase asset) private void AssetDataCallback(UUID AssetID, AssetBase asset)
{ {
m_hasasset = true; HasAsset = true;
if (asset == null || asset.Data == null) if (asset == null || asset.Data == null)
{ {
if (m_imageManager.MissingImage != null) if (m_imageManager.MissingImage != null)
{ {
m_asset = m_imageManager.MissingImage; m_asset = m_imageManager.MissingImage.Data;
m_assetDataLength = m_asset.Data.Length;
} }
else else
{ {
m_asset = null; m_asset = null;
m_decoded = true; IsDecoded = true;
} }
} }
else else
{ {
m_asset = asset; m_asset = asset.Data;
m_assetDataLength = m_asset.Data.Length;
} }
RunUpdate(); RunUpdate();

View File

@ -4751,7 +4751,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{ {
Hashtable mp = (Hashtable)simMapProfiles[iii]; Hashtable mp = (Hashtable)simMapProfiles[iii];
mbReply.Data[iii] = new MapBlockReplyPacket.DataBlock(); mbReply.Data[iii] = new MapBlockReplyPacket.DataBlock();
mbReply.Data[iii].Name = System.Text.Encoding.UTF8.GetBytes((string)mp["name"]); mbReply.Data[iii].Name = Util.UTF8.GetBytes((string)mp["name"]);
mbReply.Data[iii].Access = System.Convert.ToByte(mp["access"]); mbReply.Data[iii].Access = System.Convert.ToByte(mp["access"]);
mbReply.Data[iii].Agents = System.Convert.ToByte(mp["agents"]); mbReply.Data[iii].Agents = System.Convert.ToByte(mp["agents"]);
mbReply.Data[iii].MapImageID = new UUID((string)mp["map-image-id"]); mbReply.Data[iii].MapImageID = new UUID((string)mp["map-image-id"]);
@ -7341,7 +7341,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
} }
#endregion #endregion
string mapName = Encoding.UTF8.GetString(map.NameData.Name, 0, string mapName = Util.UTF8.GetString(map.NameData.Name, 0,
map.NameData.Name.Length - 1); map.NameData.Name.Length - 1);
handlerMapNameRequest = OnMapNameRequest; handlerMapNameRequest = OnMapNameRequest;
if (handlerMapNameRequest != null) if (handlerMapNameRequest != null)

View File

@ -45,48 +45,43 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{ {
public int Compare(J2KImage x, J2KImage y) public int Compare(J2KImage x, J2KImage y)
{ {
return x.m_requestedPriority.CompareTo(y.m_requestedPriority); return x.Priority.CompareTo(y.Priority);
} }
} }
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_shuttingdown = false; private bool m_shuttingdown;
private long m_lastloopprocessed = 0; private long m_lastloopprocessed;
private AssetBase m_missingImage = null; private AssetBase m_missingImage;
private LLClientView m_client; //Client we're assigned to private LLClientView m_client; //Client we're assigned to
private IAssetService m_assetCache; //Asset Cache private IAssetService m_assetCache; //Asset Cache
private IJ2KDecoder m_j2kDecodeModule; //Our J2K module private IJ2KDecoder m_j2kDecodeModule; //Our J2K module
private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer()); private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());
private object m_syncRoot = new object();
public LLClientView Client { get { return m_client; } }
public AssetBase MissingImage { get { return m_missingImage; } }
public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule) public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
{ {
m_client = client; m_client = client;
m_assetCache = pAssetCache; m_assetCache = pAssetCache;
if (pAssetCache != null) if (pAssetCache != null)
m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f"); m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
else
m_log.Error("[ClientView] - couldn't set missing image asset, falling back to missing image packet. This is known to crash the client"); if (m_missingImage == null)
m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
m_j2kDecodeModule = pJ2kDecodeModule; m_j2kDecodeModule = pJ2kDecodeModule;
} }
public LLClientView Client /// <summary>
{ /// Handles an incoming texture request or update to an existing texture request
get { return m_client; } /// </summary>
} /// <param name="newRequest"></param>
public AssetBase MissingImage
{
get { return m_missingImage; }
}
public void EnqueueReq(TextureRequestArgs newRequest) public void EnqueueReq(TextureRequestArgs newRequest)
{ {
//newRequest is the properties of our new texture fetch request.
//Basically, here is where we queue up "new" requests..
// .. or modify existing requests to suit.
//Make sure we're not shutting down.. //Make sure we're not shutting down..
if (!m_shuttingdown) if (!m_shuttingdown)
{ {
@ -94,7 +89,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Do a linear search for this texture download // Do a linear search for this texture download
lock (m_priorityQueue) lock (m_priorityQueue)
m_priorityQueue.Find(delegate(J2KImage img) { return img.m_requestedUUID == newRequest.RequestedAssetID; }, out imgrequest); m_priorityQueue.Find(delegate(J2KImage img) { return img.TextureID == newRequest.RequestedAssetID; }, out imgrequest);
if (imgrequest != null) if (imgrequest != null)
{ {
@ -105,7 +100,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
try try
{ {
lock (m_priorityQueue) lock (m_priorityQueue)
m_priorityQueue.Delete(imgrequest.m_priorityQueueHandle); m_priorityQueue.Delete(imgrequest.PriorityQueueHandle);
} }
catch (Exception) { } catch (Exception) { }
} }
@ -116,30 +111,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
//Check the packet sequence to make sure this isn't older than //Check the packet sequence to make sure this isn't older than
//one we've already received //one we've already received
if (newRequest.requestSequence > imgrequest.m_lastSequence) if (newRequest.requestSequence > imgrequest.LastSequence)
{ {
//Update the sequence number of the last RequestImage packet //Update the sequence number of the last RequestImage packet
imgrequest.m_lastSequence = newRequest.requestSequence; imgrequest.LastSequence = newRequest.requestSequence;
//Update the requested discard level //Update the requested discard level
imgrequest.m_requestedDiscardLevel = newRequest.DiscardLevel; imgrequest.DiscardLevel = newRequest.DiscardLevel;
//Update the requested packet number //Update the requested packet number
imgrequest.m_requestedPacketNumber = newRequest.PacketNumber; imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Update the requested priority //Update the requested priority
imgrequest.m_requestedPriority = newRequest.Priority; imgrequest.Priority = newRequest.Priority;
try UpdateImageInQueue(imgrequest);
{
lock (m_priorityQueue)
m_priorityQueue.Replace(imgrequest.m_priorityQueueHandle, imgrequest);
}
catch (Exception)
{
imgrequest.m_priorityQueueHandle = null;
lock (m_priorityQueue)
m_priorityQueue.Add(ref imgrequest.m_priorityQueueHandle, imgrequest);
}
//Run an update //Run an update
imgrequest.RunUpdate(); imgrequest.RunUpdate();
@ -159,31 +144,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority); // newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
imgrequest = new J2KImage(this); imgrequest = new J2KImage(this);
imgrequest.J2KDecoder = m_j2kDecodeModule;
//Assign our decoder module imgrequest.AssetService = m_assetCache;
imgrequest.m_j2kDecodeModule = m_j2kDecodeModule; imgrequest.DiscardLevel = newRequest.DiscardLevel;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Assign our asset cache module imgrequest.Priority = newRequest.Priority;
imgrequest.m_assetCache = m_assetCache; imgrequest.TextureID = newRequest.RequestedAssetID;
imgrequest.Priority = newRequest.Priority;
//Assign the requested discard level
imgrequest.m_requestedDiscardLevel = newRequest.DiscardLevel;
//Assign the requested packet number
imgrequest.m_requestedPacketNumber = newRequest.PacketNumber;
//Assign the requested priority
imgrequest.m_requestedPriority = newRequest.Priority;
//Assign the asset uuid
imgrequest.m_requestedUUID = newRequest.RequestedAssetID;
//Assign the requested priority
imgrequest.m_requestedPriority = newRequest.Priority;
//Add this download to the priority queue //Add this download to the priority queue
lock (m_priorityQueue) AddImageToQueue(imgrequest);
m_priorityQueue.Add(ref imgrequest.m_priorityQueueHandle, imgrequest);
//Run an update //Run an update
imgrequest.RunUpdate(); imgrequest.RunUpdate();
@ -194,105 +164,99 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public bool ProcessImageQueue(int count, int maxpack) public bool ProcessImageQueue(int count, int maxpack)
{ {
lock (this) J2KImage imagereq;
{
//count is the number of textures we want to process in one go.
//As part of this class re-write, that number will probably rise
//since we're processing in a more efficient manner.
// this can happen during Close()
if (m_client == null)
return false;
int numCollected = 0; int numCollected = 0;
//Calculate our threshold //lock (m_syncRoot)
int threshold; //{
if (m_lastloopprocessed == 0)
{
if (m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null || m_client.PacketHandler.PacketQueue.TextureThrottle == null)
return false;
//This is decent for a semi fast machine, but we'll calculate it more accurately based on time below
threshold = m_client.PacketHandler.PacketQueue.TextureThrottle.Current / 6300;
m_lastloopprocessed = DateTime.Now.Ticks;
}
else
{
double throttleseconds = ((double)DateTime.Now.Ticks - (double)m_lastloopprocessed) / (double)TimeSpan.TicksPerSecond;
throttleseconds = throttleseconds * m_client.PacketHandler.PacketQueue.TextureThrottle.Current;
//Average of 1000 bytes per packet
throttleseconds = throttleseconds / 1000;
//Safe-zone multiplier of 2.0
threshold = (int)(throttleseconds * 2.0);
m_lastloopprocessed = DateTime.Now.Ticks; m_lastloopprocessed = DateTime.Now.Ticks;
} // This can happen during Close()
if (m_client == null || m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null)
if (m_client.PacketHandler == null)
return false; return false;
if (m_client.PacketHandler.PacketQueue == null) while ((imagereq = GetHighestPriorityImage()) != null)
return false;
if (threshold < 10)
threshold = 10;
//Uncomment this to see what the texture stack is doing
//m_log.Debug("Queue: " + m_client.PacketHandler.PacketQueue.getQueueCount(ThrottleOutPacketType.Texture).ToString() + " Threshold: " + threshold.ToString() + " outstanding: " + m_outstandingtextures.ToString());
if (true) //m_client.PacketHandler.PacketQueue.GetQueueCount(ThrottleOutPacketType.Texture) < threshold)
{ {
while (m_priorityQueue.Count > 0) if (imagereq.IsDecoded == true)
{ {
J2KImage imagereq = null;
lock (m_priorityQueue)
imagereq = m_priorityQueue.FindMax();
if (imagereq.m_decoded == true)
{
// we need to test this here now that we are dropping assets
if (!imagereq.m_hasasset)
{
m_log.WarnFormat("[LLIMAGE MANAGER]: Re-requesting the image asset {0}", imagereq.m_requestedUUID);
imagereq.RunUpdate();
continue;
}
++numCollected; ++numCollected;
//SendPackets will send up to ten packets per cycle
if (imagereq.SendPackets(m_client, maxpack)) if (imagereq.SendPackets(m_client, maxpack))
{ {
// Send complete. Destroy any knowledge of this transfer // Send complete. Destroy any knowledge of this transfer
try RemoveImageFromQueue(imagereq);
{
lock (m_priorityQueue)
m_priorityQueue.Delete(imagereq.m_priorityQueueHandle);
}
catch (Exception) { }
} }
} }
if (numCollected == count) if (numCollected == count)
break; break;
} }
} //}
return m_priorityQueue.Count > 0; return m_priorityQueue.Count > 0;
} }
}
//Faux destructor //Faux destructor
public void Close() public void Close()
{ {
m_shuttingdown = true; m_shuttingdown = true;
m_j2kDecodeModule = null; m_j2kDecodeModule = null;
m_assetCache = null; m_assetCache = null;
m_client = null; m_client = null;
} }
#region Priority Queue Helpers
J2KImage GetHighestPriorityImage()
{
J2KImage image = null;
lock (m_priorityQueue)
{
if (m_priorityQueue.Count > 0)
{
try
{
image = m_priorityQueue.FindMax();
}
catch (Exception) { }
}
}
return image;
}
void AddImageToQueue(J2KImage image)
{
image.PriorityQueueHandle = null;
lock (m_priorityQueue)
m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
}
void RemoveImageFromQueue(J2KImage image)
{
try
{
lock (m_priorityQueue)
m_priorityQueue.Delete(image.PriorityQueueHandle);
}
catch (Exception) { }
}
void UpdateImageInQueue(J2KImage image)
{
lock (m_priorityQueue)
{
try { m_priorityQueue.Replace(image.PriorityQueueHandle, image); }
catch (Exception)
{
image.PriorityQueueHandle = null;
m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
}
}
}
#endregion Priority Queue Helpers
} }
} }

View File

@ -257,7 +257,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd);
} }
layerDecodeAsset.Data = Encoding.UTF8.GetBytes(stringResult.ToString()); layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
#endregion Serialize Layer Data #endregion Serialize Layer Data
@ -280,7 +280,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
{ {
#region Deserialize Layer Data #region Deserialize Layer Data
string readResult = Encoding.UTF8.GetString(layerDecodeAsset.Data); string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0) if (lines.Length == 0)

View File

@ -323,13 +323,13 @@ namespace Flotsam.RegionModules.AssetCache
string filename = GetFileName(id); string filename = GetFileName(id);
if (File.Exists(filename)) if (File.Exists(filename))
{ {
FileStream stream = null;
try try
{ {
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read); stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter bformatter = new BinaryFormatter(); BinaryFormatter bformatter = new BinaryFormatter();
asset = (AssetBase)bformatter.Deserialize(stream); asset = (AssetBase)bformatter.Deserialize(stream);
stream.Close();
UpdateMemoryCache(id, asset); UpdateMemoryCache(id, asset);
@ -349,6 +349,11 @@ namespace Flotsam.RegionModules.AssetCache
{ {
LogException(e); LogException(e);
} }
finally
{
if (stream != null)
stream.Close();
}
} }
@ -493,19 +498,20 @@ namespace Flotsam.RegionModules.AssetCache
private void WriteFileCache(string filename, AssetBase asset) private void WriteFileCache(string filename, AssetBase asset)
{ {
try Stream stream = null;
{
// Make sure the target cache directory exists // Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename); string directory = Path.GetDirectoryName(filename);
// Write file first to a temp name, so that it doesn't look
// like it's already cached while it's still writing.
string tempname = Path.Combine(directory, Path.GetRandomFileName());
try
{
if (!Directory.Exists(directory)) if (!Directory.Exists(directory))
{ {
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
} }
// Write file first to a temp name, so that it doesn't look stream = File.Open(tempname, FileMode.Create);
// like it's already cached while it's still writing.
string tempname = Path.Combine(directory, Path.GetRandomFileName());
Stream stream = File.Open(tempname, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter(); BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, asset); bformatter.Serialize(stream, asset);
stream.Close(); stream.Close();
@ -522,6 +528,9 @@ namespace Flotsam.RegionModules.AssetCache
} }
finally finally
{ {
if (stream != null)
stream.Close();
// Even if the write fails with an exception, we need to make sure // Even if the write fails with an exception, we need to make sure
// that we release the lock on that file, otherwise it'll never get // that we release the lock on that file, otherwise it'll never get
// cached // cached

View File

@ -367,7 +367,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
// Encode outbound data // Encode outbound data
if (OutboundBody.Length > 0) if (OutboundBody.Length > 0)
{ {
byte[] data = Encoding.UTF8.GetBytes(OutboundBody); byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length; Request.ContentLength = data.Length;
Stream bstream = Request.GetRequestStream(); Stream bstream = Request.GetRequestStream();
@ -390,7 +390,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
if (count != 0) if (count != 0)
{ {
// translate from bytes to ASCII text // translate from bytes to ASCII text
tempString = Encoding.UTF8.GetString(buf, 0, count); tempString = Util.UTF8.GetString(buf, 0, count);
// continue building the string // continue building the string
sb.Append(tempString); sb.Append(tempString);

View File

@ -397,11 +397,16 @@ namespace OpenSim.Region.CoreModules.World.Permissions
// with the powers requested (powers = 0 for no powers check) // with the powers requested (powers = 0 for no powers check)
protected bool IsGroupMember(UUID groupID, UUID userID, ulong powers) protected bool IsGroupMember(UUID groupID, UUID userID, ulong powers)
{ {
IClientAPI client = m_scene.GetScenePresence(userID).ControllingClient; ScenePresence sp = m_scene.GetScenePresence(userID);
if (sp != null)
{
IClientAPI client = sp.ControllingClient;
return ((groupID == client.ActiveGroupId) && (client.ActiveGroupPowers != 0) && return ((groupID == client.ActiveGroupId) && (client.ActiveGroupPowers != 0) &&
((powers == 0) || ((client.ActiveGroupPowers & powers) == powers))); ((powers == 0) || ((client.ActiveGroupPowers & powers) == powers)));
} }
return false;
}
/// <summary> /// <summary>
/// Parse a user set configuration setting /// Parse a user set configuration setting
@ -576,9 +581,12 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return objectOwnerMask; return objectOwnerMask;
} }
if ((objectOwnerMask & (uint)PermissionMask.Transfer) != 0 && task.ObjectSaleType != 0)
objectEveryoneMask |= (uint)PrimFlags.ObjectTransfer;
// Group permissions // Group permissions
if ((task.GroupID != UUID.Zero) && IsGroupMember(task.GroupID, user, 0)) if ((task.GroupID != UUID.Zero) && IsGroupMember(task.GroupID, user, 0))
return objectGroupMask; return objectGroupMask | objectEveryoneMask;
return objectEveryoneMask; return objectEveryoneMask;
} }

View File

@ -36,10 +36,10 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{ {
public struct HeightmapLookupValue : IComparable<HeightmapLookupValue> public struct HeightmapLookupValue : IComparable<HeightmapLookupValue>
{ {
public int Index; public ushort Index;
public double Value; public float Value;
public HeightmapLookupValue(int index, double value) public HeightmapLookupValue(ushort index, float value)
{ {
Index = index; Index = index;
Value = value; Value = value;
@ -62,7 +62,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{ {
for (int j = 0; j < 256; j++) for (int j = 0; j < 256; j++)
{ {
LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue(i + (j * 256), ((double)i * ((double)j / 128.0d))); LookupHeightTable[i + (j * 256)] = new HeightmapLookupValue((ushort)(i + (j * 256)), (float)((double)i * ((double)j / 128.0d)));
} }
} }
Array.Sort<HeightmapLookupValue>(LookupHeightTable); Array.Sort<HeightmapLookupValue>(LookupHeightTable);
@ -196,7 +196,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
// The lookup table is pre-sorted, so we either find an exact match or // The lookup table is pre-sorted, so we either find an exact match or
// the next closest (smaller) match with a binary search // the next closest (smaller) match with a binary search
index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, t)); index = Array.BinarySearch<HeightmapLookupValue>(LookupHeightTable, new HeightmapLookupValue(0, (float)t));
if (index < 0) if (index < 0)
index = ~index - 1; index = ~index - 1;

View File

@ -352,7 +352,7 @@ namespace OpenSim.Region.DataSnapshot
m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace); m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace);
} }
// This is not quite working, so... // This is not quite working, so...
// string responseStr = Encoding.UTF8.GetString(response); // string responseStr = Util.UTF8.GetString(response);
m_log.Info("[DATASNAPSHOT]: data service notified: " + url); m_log.Info("[DATASNAPSHOT]: data service notified: " + url);
} }

View File

@ -73,7 +73,7 @@ namespace OpenSim.Region.Framework.Scenes
public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) public byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{ {
return Encoding.UTF8.GetBytes(Report()); return Util.UTF8.GetBytes(Report());
} }
public string ContentType public string ContentType

View File

@ -1332,7 +1332,8 @@ if (m_shape != null) {
bool RigidBody = isPhysical && !isPhantom; bool RigidBody = isPhysical && !isPhantom;
// 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 // 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
if (!isPhantom && !IsAttachment) // or flexible
if (!isPhantom && !IsAttachment && !(Shape.PathCurve == (byte) Extrusion.Flexible))
{ {
PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape(
Name, Name,
@ -3396,7 +3397,7 @@ if (m_shape != null) {
} }
if (IsPhantom || IsAttachment) // note: this may have been changed above in the case of joints if (IsPhantom || IsAttachment || (Shape.PathCurve == (byte)Extrusion.Flexible)) // note: this may have been changed above in the case of joints
{ {
AddFlag(PrimFlags.Phantom); AddFlag(PrimFlags.Phantom);
if (PhysActor != null) if (PhysActor != null)

View File

@ -172,7 +172,7 @@ namespace OpenSim.Region.Framework.Scenes
public string SaveToXmlString() public string SaveToXmlString()
{ {
XmlWriterSettings settings = new XmlWriterSettings(); XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8; settings.Encoding = Util.UTF8;
using (StringWriter sw = new StringWriter()) using (StringWriter sw = new StringWriter())
{ {
using (XmlWriter writer = XmlWriter.Create(sw, settings)) using (XmlWriter writer = XmlWriter.Create(sw, settings))

View File

@ -81,7 +81,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
{ {
m_log.Info("[IRCd] Sending >>> " + command); m_log.Info("[IRCd] Sending >>> " + command);
byte[] buf = Encoding.UTF8.GetBytes(command + "\r\n"); byte[] buf = Util.UTF8.GetBytes(command + "\r\n");
m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null); m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null);
} }
@ -109,7 +109,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
byte[] buf = new byte[8]; // RFC1459 defines max message size as 512. byte[] buf = new byte[8]; // RFC1459 defines max message size as 512.
int count = m_client.GetStream().Read(buf, 0, buf.Length); int count = m_client.GetStream().Read(buf, 0, buf.Length);
string line = Encoding.UTF8.GetString(buf, 0, count); string line = Util.UTF8.GetString(buf, 0, count);
strbuf += line; strbuf += line;

View File

@ -559,7 +559,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
if (method == "POST") if (method == "POST")
{ {
byte[] contentreq = Encoding.UTF8.GetBytes(body); byte[] contentreq = Util.UTF8.GetBytes(body);
forwardreq.ContentLength = contentreq.Length; forwardreq.ContentLength = contentreq.Length;
Stream reqStream = forwardreq.GetRequestStream(); Stream reqStream = forwardreq.GetRequestStream();
reqStream.Write(contentreq, 0, contentreq.Length); reqStream.Write(contentreq, 0, contentreq.Length);
@ -567,7 +567,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
} }
HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse(); HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse();
Encoding encoding = Encoding.UTF8; Encoding encoding = Util.UTF8;
StreamReader fwdresponsestream = new StreamReader(fwdrsp.GetResponseStream(), encoding); StreamReader fwdresponsestream = new StreamReader(fwdrsp.GetResponseStream(), encoding);
fwdresponsestr = fwdresponsestream.ReadToEnd(); fwdresponsestr = fwdresponsestream.ReadToEnd();
fwdresponsecontenttype = fwdrsp.ContentType; fwdresponsecontenttype = fwdrsp.ContentType;

View File

@ -539,7 +539,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
{ {
XmlSerializer xs = new XmlSerializer(typeof(Copse)); XmlSerializer xs = new XmlSerializer(typeof(Copse));
using (XmlTextWriter writer = new XmlTextWriter(fileName, System.Text.Encoding.UTF8)) using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
{ {
writer.Formatting = Formatting.Indented; writer.Formatting = Formatting.Indented;
xs.Serialize(writer, obj); xs.Serialize(writer, obj);

View File

@ -224,6 +224,14 @@ namespace OpenSim.Region.Physics.Meshing
for (int i = 0; i < lodBytes.Length; i++) for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]); hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (pbs.SculptEntry)
{
scaleBytes = pbs.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
}
return hash; return hash;
} }
@ -389,7 +397,7 @@ namespace OpenSim.Region.Physics.Meshing
primMesh.pathCutBegin = pathBegin; primMesh.pathCutBegin = pathBegin;
primMesh.pathCutEnd = pathEnd; primMesh.pathCutEnd = pathEnd;
if (primShape.PathCurve == (byte)Extrusion.Straight) if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
{ {
primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10; primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
primMesh.twistEnd = primShape.PathTwist * 18 / 10; primMesh.twistEnd = primShape.PathTwist * 18 / 10;
@ -484,12 +492,18 @@ namespace OpenSim.Region.Physics.Meshing
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical) public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical)
{ {
Mesh mesh = null;
ulong key = 0;
// If this mesh has been created already, return it instead of creating another copy // If this mesh has been created already, return it instead of creating another copy
// For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
ulong key = GetMeshKey(primShape, size, lod);
Mesh mesh = null; if (! primShape.SculptEntry)
{
key = GetMeshKey(primShape, size, lod);
if (m_uniqueMeshes.TryGetValue(key, out mesh)) if (m_uniqueMeshes.TryGetValue(key, out mesh))
return mesh; return mesh;
}
if (size.X < 0.01f) size.X = 0.01f; if (size.X < 0.01f) size.X = 0.01f;
if (size.Y < 0.01f) size.Y = 0.01f; if (size.Y < 0.01f) size.Y = 0.01f;
@ -512,7 +526,10 @@ namespace OpenSim.Region.Physics.Meshing
// trim the vertex and triangle lists to free up memory // trim the vertex and triangle lists to free up memory
mesh.TrimExcess(); mesh.TrimExcess();
} }
if (!primShape.SculptEntry)
m_uniqueMeshes.Add(key, mesh); m_uniqueMeshes.Add(key, mesh);
return mesh; return mesh;
} }
} }

View File

@ -7080,7 +7080,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
try try
{ {
byte[] encData_byte = new byte[str.Length]; byte[] encData_byte = new byte[str.Length];
encData_byte = Encoding.UTF8.GetBytes(str); encData_byte = Util.UTF8.GetBytes(str);
string encodedData = Convert.ToBase64String(encData_byte); string encodedData = Convert.ToBase64String(encData_byte);
return encodedData; return encodedData;
} }

View File

@ -1491,7 +1491,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
notecardData = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length " notecardData = "Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length "
+ textLength.ToString() + "\n" + notecardData + "}\n"; + textLength.ToString() + "\n" + notecardData + "}\n";
asset.Data = Encoding.UTF8.GetBytes(notecardData); asset.Data = Util.UTF8.GetBytes(notecardData);
World.AssetService.Store(asset); World.AssetService.Store(asset);
// Create Task Entry // Create Task Entry

View File

@ -87,7 +87,7 @@ namespace OpenSim.Server.Base
public static byte[] SerializeResult(XmlSerializer xs, object data) public static byte[] SerializeResult(XmlSerializer xs, object data)
{ {
MemoryStream ms = new MemoryStream(); MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, Encoding.UTF8); XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
xw.Formatting = Formatting.Indented; xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data); xs.Serialize(xw, data);
xw.Flush(); xw.Flush();

View File

@ -160,7 +160,7 @@ namespace OpenSim.Server.Handlers.Neighbour
httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.StatusCode = (int)HttpStatusCode.OK;
return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)); return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
} }
} }

View File

@ -161,7 +161,7 @@ namespace OpenSim.Server.Handlers.Simulation
httpResponse.StatusCode = (int)HttpStatusCode.OK; httpResponse.StatusCode = (int)HttpStatusCode.OK;
return Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(resp)); return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
} }
} }

View File

@ -171,6 +171,8 @@ namespace OpenSim.Services.Connectors
if (asset == null) if (asset == null)
{ {
bool result = false;
AsynchronousRestObjectRequester. AsynchronousRestObjectRequester.
MakeRequest<int, AssetBase>("GET", uri, 0, MakeRequest<int, AssetBase>("GET", uri, 0,
delegate(AssetBase a) delegate(AssetBase a)
@ -178,12 +180,15 @@ namespace OpenSim.Services.Connectors
if (m_Cache != null) if (m_Cache != null)
m_Cache.Cache(a); m_Cache.Cache(a);
handler(id, sender, a); handler(id, sender, a);
result = true;
}); });
return result;
} }
else else
{ {
Util.FireAndForget(delegate { handler(id, sender, asset); }); //Util.FireAndForget(delegate { handler(id, sender, asset); });
handler(id, sender, asset);
} }
return true; return true;

Binary file not shown.

View File

@ -17,7 +17,7 @@
[GridService] [GridService]
; ;
; change this to your grid-wide inventory server ; change this to your grid-wide grid server
; ;
GridServerURI = "http://mygridserver.com:8001" GridServerURI = "http://mygridserver.com:8001"

View File

@ -957,75 +957,6 @@
</Project> </Project>
<Project frameworkVersion="v3_5" name="OpenSim.Grid.MessagingServer.Modules" path="OpenSim/Grid/MessagingServer.Modules" type="Library">
<Configuration name="Debug">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Data"/>
<Reference name="System.Xml"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Communications"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Grid.Framework"/>
<Reference name="OpenMetaverseTypes.dll"/>
<Reference name="OpenMetaverse.dll"/>
<Reference name="XMLRPC.dll"/>
<Reference name="log4net.dll"/>
<Files>
<Match pattern="*.cs" recurse="true"/>
</Files>
</Project>
<Project frameworkVersion="v3_5" name="OpenSim.Grid.MessagingServer" path="OpenSim/Grid/MessagingServer" type="Exe">
<Configuration name="Debug">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Data"/>
<Reference name="System.Xml"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Communications"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Grid.Framework"/>
<Reference name="OpenSim.Grid.MessagingServer.Modules"/>
<Reference name="OpenMetaverseTypes.dll"/>
<Reference name="OpenMetaverse.dll"/>
<Reference name="XMLRPC.dll"/>
<Reference name="log4net.dll"/>
<Reference name="Nini.dll"/>
<Files>
<Match pattern="*.cs" recurse="true"/>
</Files>
</Project>
<Project frameworkVersion="v3_5" name="OpenSim.Server.Base" path="OpenSim/Server/Base" type="Library"> <Project frameworkVersion="v3_5" name="OpenSim.Server.Base" path="OpenSim/Server/Base" type="Library">
<Configuration name="Debug"> <Configuration name="Debug">
<Options> <Options>
@ -1230,6 +1161,78 @@
</Files> </Files>
</Project> </Project>
<Project frameworkVersion="v3_5" name="OpenSim.Grid.MessagingServer.Modules" path="OpenSim/Grid/MessagingServer.Modules" type="Library">
<Configuration name="Debug">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Data"/>
<Reference name="System.Xml"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Communications"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Grid.Framework"/>
<Reference name="OpenSim.Services.Interfaces"/>
<Reference name="OpenSim.Services.Connectors"/>
<Reference name="OpenMetaverseTypes.dll"/>
<Reference name="OpenMetaverse.dll"/>
<Reference name="XMLRPC.dll"/>
<Reference name="log4net.dll"/>
<Reference name="Nini.dll"/>
<Files>
<Match pattern="*.cs" recurse="true"/>
</Files>
</Project>
<Project frameworkVersion="v3_5" name="OpenSim.Grid.MessagingServer" path="OpenSim/Grid/MessagingServer" type="Exe">
<Configuration name="Debug">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Data"/>
<Reference name="System.Xml"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Communications"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Grid.Framework"/>
<Reference name="OpenSim.Grid.MessagingServer.Modules"/>
<Reference name="OpenMetaverseTypes.dll"/>
<Reference name="OpenMetaverse.dll"/>
<Reference name="XMLRPC.dll"/>
<Reference name="log4net.dll"/>
<Reference name="Nini.dll"/>
<Files>
<Match pattern="*.cs" recurse="true"/>
</Files>
</Project>
<Project frameworkVersion="v3_5" name="OpenSim.Services.AssetService" path="OpenSim/Services/AssetService" type="Library"> <Project frameworkVersion="v3_5" name="OpenSim.Services.AssetService" path="OpenSim/Services/AssetService" type="Library">
<Configuration name="Debug"> <Configuration name="Debug">
<Options> <Options>