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,103 +182,125 @@ namespace OpenSim.Client.Linden
/// <returns></returns> /// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient) public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient)
{ {
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string)requestData["session_id"]);
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
agentData.firstname = (string)requestData["firstname"];
agentData.lastname = (string)requestData["lastname"];
agentData.AgentID = new UUID((string)requestData["agent_id"]);
agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
// Appearance
if (requestData["appearance"] != null)
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat(
"[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
agentData.firstname, agentData.lastname, agentData.AgentID, agentData.circuitcode);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
//m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDecimal((string)requestData["startpos_x"]),
(float)Convert.ToDecimal((string)requestData["startpos_y"]),
(float)Convert.ToDecimal((string)requestData["startpos_z"]));
agentData.child = false;
}
XmlRpcResponse resp = new XmlRpcResponse(); XmlRpcResponse resp = new XmlRpcResponse();
if (!RegionLoginsEnabled) try
{ {
m_log.InfoFormat( ulong regionHandle = 0;
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled", Hashtable requestData = (Hashtable)request.Params[0];
agentData.firstname, agentData.lastname); AgentCircuitData agentData = new AgentCircuitData();
if (requestData.ContainsKey("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"]);
if (requestData.ContainsKey("firstname"))
agentData.firstname = (string)requestData["firstname"];
if (requestData.ContainsKey("lastname"))
agentData.lastname = (string)requestData["lastname"];
if (requestData.ContainsKey("agent_id"))
agentData.AgentID = new UUID((string)requestData["agent_id"]);
if (requestData.ContainsKey("circuit_code"))
agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
if (requestData.ContainsKey("caps_path"))
agentData.CapsPath = (string)requestData["caps_path"];
if (requestData.ContainsKey("regionhandle"))
regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
else
m_log.Warn("[CLIENT]: request from login server did not contain regionhandle");
Hashtable respdata = new Hashtable(); // Appearance
respdata["success"] = "FALSE"; if (requestData.ContainsKey("appearance"))
respdata["reason"] = "region login currently disabled"; agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
resp.Value = respdata;
}
else
{
bool success = false;
string denyMess = "";
Scene scene; m_log.DebugFormat(
if (TryGetRegion(regionHandle, out scene)) "[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
agentData.firstname, agentData.lastname, agentData.AgentID, agentData.circuitcode);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{ {
if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID)) //m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDecimal((string)requestData["startpos_x"]),
(float)Convert.ToDecimal((string)requestData["startpos_y"]),
(float)Convert.ToDecimal((string)requestData["startpos_z"]));
agentData.child = false;
}
if (!RegionLoginsEnabled)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
agentData.firstname, agentData.lastname);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "region login currently disabled";
resp.Value = respdata;
}
else
{
bool success = false;
string denyMess = "";
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{ {
denyMess = "User is banned from this region"; if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.firstname, agentData.lastname);
}
else
{
string reason;
if (scene.NewUserConnection(agentData, out reason))
{ {
success = true; denyMess = "User is banned from this region";
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.firstname, agentData.lastname);
} }
else else
{ {
denyMess = String.Format("Login refused by region: {0}", reason); string reason;
m_log.InfoFormat( if (scene.NewUserConnection(agentData, out reason))
"[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region", {
agentData.firstname, agentData.lastname); success = true;
}
else
{
denyMess = String.Format("Login refused by region: {0}", reason);
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region",
agentData.firstname, agentData.lastname);
}
} }
}
else
{
denyMess = "Region not found";
} }
if (success)
{
Hashtable respdata = new Hashtable();
respdata["success"] = "TRUE";
resp.Value = respdata;
}
else
{
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = denyMess;
resp.Value = respdata;
}
} }
else }
{ catch (Exception e)
denyMess = "Region not found"; {
} m_log.WarnFormat("[CLIENT]: Unable to receive user. Reason: {0}", e);
Hashtable respdata = new Hashtable();
if (success) respdata["success"] = "FALSE";
{ respdata["reason"] = "Exception occurred";
Hashtable respdata = new Hashtable(); resp.Value = respdata;
respdata["success"] = "TRUE";
resp.Value = respdata;
}
else
{
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = denyMess;
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,25 +131,26 @@ 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)
{ {
int newversion = kvp.Key; foreach (KeyValuePair<int, string> kvp in migrations)
cmd.CommandText = kvp.Value; {
// we need to up the command timeout to infinite as we might be doing long migrations. int newversion = kvp.Key;
cmd.CommandTimeout = 0; cmd.CommandText = kvp.Value;
cmd.ExecuteNonQuery(); // we need to up the command timeout to infinite as we might be doing long migrations.
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
if (version == 0) if (version == 0)
{ {
InsertVersion(_type, newversion); InsertVersion(_type, newversion);
}
else
{
UpdateVersion(_type, newversion);
}
version = newversion;
} }
else
{
UpdateVersion(_type, 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();
try using (DbCommand cmd = conn.CreateCommand())
{ {
cmd.CommandText = "select version from migrations where name='" + type +"' order by version desc"; try
using (IDataReader reader = cmd.ExecuteReader())
{ {
if (reader.Read()) cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
using (IDataReader reader = cmd.ExecuteReader())
{ {
version = Convert.ToInt32(reader["version"]); if (reader.Read())
version = Convert.ToInt32(reader["version"]);
} }
reader.Close(); }
catch
{
// Something went wrong, so we're version 0
} }
} }
catch
{
// 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 + ")"; {
m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version); cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
cmd.ExecuteNonQuery(); m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
cmd.Dispose(); cmd.ExecuteNonQuery();
}
} }
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 + "'"; {
m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version); cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
cmd.ExecuteNonQuery(); m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
cmd.Dispose(); cmd.ExecuteNonQuery();
}
} }
// private SortedList<int, string> GetAllMigrations() // private SortedList<int, string> GetAllMigrations()

View File

@ -142,46 +142,45 @@ 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
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
if (dbReader.Read()) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
asset = new AssetBase(); if (dbReader.Read())
asset.Data = (byte[]) dbReader["data"];
asset.Description = (string) dbReader["description"];
asset.FullID = assetID;
try
{ {
asset.Local = (bool)dbReader["local"]; asset = new AssetBase();
asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"];
asset.FullID = assetID;
string local = dbReader["local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
asset.Local = true;
else
asset.Local = false;
asset.Name = (string)dbReader["name"];
asset.Type = (sbyte)dbReader["assetType"];
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
} }
catch (InvalidCastException)
{
asset.Local = false;
}
asset.Name = (string) dbReader["name"];
asset.Type = (sbyte) dbReader["assetType"];
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
} }
dbReader.Close();
cmd.Dispose(); if (asset != null)
UpdateAccessTime(asset);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Reconnecting", assetID);
_dbConnection.Reconnect();
} }
if (asset != null)
UpdateAccessTime(asset);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Reconnecting", assetID);
_dbConnection.Reconnect();
} }
} }
return asset; return asset;
@ -297,32 +296,27 @@ 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());
try
{ {
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) cmd.Parameters.AddWithValue("?id", uuid.ToString());
try
{ {
if (dbReader.Read()) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
assetExists = true; if (dbReader.Read())
assetExists = true;
} }
dbReader.Close();
cmd.Dispose();
} }
} catch (Exception e)
catch (Exception e) {
{ m_log.ErrorFormat(
m_log.ErrorFormat( "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
"[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection", uuid);
+ Environment.NewLine + "Attempting reconnection", uuid); _dbConnection.Reconnect();
_dbConnection.Reconnect(); }
} }
} }

View File

@ -55,44 +55,38 @@ 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());
IDataReader result = ExecuteReader(cmd);
if (result.Read())
{ {
ret.PrincipalID = principalID; cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
if (m_ColumnNames == null) using (IDataReader result = ExecuteReader(cmd))
{ {
m_ColumnNames = new List<string>(); if (result.Read())
{
ret.PrincipalID = principalID;
DataTable schemaTable = result.GetSchemaTable(); if (m_ColumnNames == null)
foreach (DataRow row in schemaTable.Rows) {
m_ColumnNames.Add(row["ColumnName"].ToString()); m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
} }
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
ret.Data[s] = result[s].ToString();
}
result.Close();
CloseReaderCommand(cmd);
return ret;
} }
result.Close();
CloseReaderCommand(cmd);
return null; return null;
} }

View File

@ -95,21 +95,17 @@ 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))
{ {
if (dbReader.Read()) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
m_waitTimeout if (dbReader.Read())
= Convert.ToInt32(dbReader["@@wait_timeout"]) * {
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) *
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
} }
dbReader.Close();
cmd.Dispose();
} }
m_lastConnectionUse = DateTime.Now.Ticks; m_lastConnectionUse = DateTime.Now.Ticks;
@ -147,53 +143,122 @@ namespace OpenSim.Data.MySQL
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); bool migration = true;
cmd.CommandText = sql; using (MySqlCommand cmd = m_connection.CreateCommand())
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
IDataReader r = cmd.ExecuteReader();
if (r.Read())
{ {
foreach (string name in FieldList) cmd.CommandText = sql;
{ cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid); using (IDataReader r = cmd.ExecuteReader())
m_FieldMap[name].SetValue(es, uuid); {
} if (r.Read())
else
{ {
m_FieldMap[name].SetValue(es, r[name]); migration = false;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
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.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue("?" + name, "1");
else
cmd.Parameters.AddWithValue("?" + name, "0");
}
else
{
cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ID() as id";
cmd.Parameters.Clear();
using (IDataReader r = cmd.ExecuteReader())
{
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
}
cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
// This will throw on dupe key
try { cmd.ExecuteNonQuery(); }
catch (Exception) { }
// Munge and transfer the ban list
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
try { cmd.ExecuteNonQuery(); }
catch (Exception) { }
es.Save();
}
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")";
CheckConnection();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql; cmd.CommandText = sql;
cmd.Parameters.Clear();
foreach (string name in FieldList) foreach (string name in FieldList)
{ {
@ -211,83 +276,8 @@ namespace OpenSim.Data.MySQL
} }
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ID() as id";
cmd.Parameters.Clear();
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
r.Close();
cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
// Munge and transfer the ban list
//
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
} }
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")";
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue("?" + name, "1");
else
cmd.Parameters.AddWithValue("?" + name, "0");
}
else
{
cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
SaveBanList(es); SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
@ -300,50 +290,52 @@ 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.Parameters.AddWithValue("?EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{ {
EstateBan eb = new EstateBan(); cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
UUID uuid = new UUID(); using (IDataReader r = cmd.ExecuteReader())
UUID.TryParse(r["bannedUUID"].ToString(), out uuid); {
while (r.Read())
{
EstateBan eb = new EstateBan();
eb.BannedUserID = uuid; UUID uuid = new UUID();
eb.BannedHostAddress = "0.0.0.0"; UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb); eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
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.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{ {
cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
} }
} }
@ -351,24 +343,25 @@ namespace OpenSim.Data.MySQL
{ {
CheckConnection(); CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand(); using (MySqlCommand cmd = m_connection.CreateCommand())
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )";
foreach (UUID uuid in data)
{ {
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
} }
} }
@ -378,23 +371,24 @@ 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.Parameters.AddWithValue("?EstateID", EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{ {
// EstateBan eb = new EstateBan(); cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID);
UUID uuid = new UUID(); using (IDataReader r = cmd.ExecuteReader())
UUID.TryParse(r["uuid"].ToString(), out uuid); {
while (r.Read())
{
// EstateBan eb = new EstateBan();
uuids.Add(uuid); UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out 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();
RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>();
while ((row = dbm.Manager.readSimRow(reader)) != null)
{ {
rows.Add(row); using (IDataReader reader = result.ExecuteReader())
} {
reader.Close(); RegionProfileData row;
result.Dispose();
return rows.ToArray(); List<RegionProfileData> rows = new List<RegionProfileData>();
while ((row = dbm.Manager.readSimRow(reader)) != null)
rows.Add(row);
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();
RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>();
while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
{ {
rows.Add(row); using (IDataReader reader = result.ExecuteReader())
} {
reader.Close(); RegionProfileData row;
result.Dispose();
return rows; List<RegionProfileData> rows = new List<RegionProfileData>();
while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
rows.Add(row);
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
@ -286,21 +282,21 @@ namespace OpenSim.Data.MySQL
try try
{ {
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); {
reader.Close(); RegionProfileData row = dbm.Manager.readSimRow(reader);
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
@ -321,23 +317,24 @@ namespace OpenSim.Data.MySQL
try try
{ {
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); {
reader.Close(); RegionProfileData row = dbm.Manager.readSimRow(reader);
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(); return row;
result.Dispose(); }
}
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,12 +391,12 @@ 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();
} }
@ -482,26 +479,26 @@ namespace OpenSim.Data.MySQL
try try
{ {
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(); return row;
result.Dispose(); }
}
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,30 +135,30 @@ 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());
MySqlDataReader reader = result.ExecuteReader();
while (reader.Read())
{ {
// A null item (because something went wrong) breaks everything in the folder result.Parameters.AddWithValue("?uuid", folderID.ToString());
InventoryItemBase item = readInventoryItem(reader);
if (item != null) using (MySqlDataReader reader = result.ExecuteReader())
items.Add(item); {
while (reader.Read())
{
// A null item (because something went wrong) breaks everything in the folder
InventoryItemBase item = readInventoryItem(reader);
if (item != null)
items.Add(item);
}
return items;
}
} }
reader.Close();
result.Dispose();
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();
List<InventoryFolderBase> items = new List<InventoryFolderBase>(); using (MySqlDataReader reader = result.ExecuteReader())
while (reader.Read()) {
items.Add(readInventoryFolder(reader)); List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
return items;
reader.Close(); }
result.Dispose(); }
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,41 +216,38 @@ 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("?zero", UUID.Zero.ToString());
MySqlDataReader reader = result.ExecuteReader();
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
InventoryFolderBase rootFolder = null;
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (items.Count > 0)
{ {
rootFolder = items[0]; result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
InventoryFolderBase rootFolder = null;
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (items.Count > 0)
rootFolder = items[0];
return rootFolder;
}
} }
reader.Close();
result.Dispose();
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())
items.Add(readInventoryFolder(reader));
while (reader.Read()) return items;
items.Add(readInventoryFolder(reader)); }
}
reader.Close();
result.Dispose();
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();
InventoryItemBase item = null; using (MySqlDataReader reader = result.ExecuteReader())
if (reader.Read()) {
item = readInventoryItem(reader); InventoryItemBase item = null;
if (reader.Read())
item = readInventoryItem(reader);
reader.Close(); return item;
result.Dispose(); }
}
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();
InventoryFolderBase folder = null; using (MySqlDataReader reader = result.ExecuteReader())
if (reader.Read()) {
folder = readInventoryFolder(reader); InventoryFolderBase folder = null;
reader.Close(); if (reader.Read())
result.Dispose(); folder = readInventoryFolder(reader);
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,69 +694,73 @@ 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>();
bool buildResultsFromHashTable = false;
lock (database) lock (database)
{ {
MySqlCommand result;
MySqlDataReader reader;
bool buildResultsFromHashTable = false;
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())
parentFolder.Add(readInventoryFolder(reader)); {
reader.Close(); // Should be at most 1 result
result.Dispose(); while (reader.Read())
parentFolder.Add(readInventoryFolder(reader));
}
}
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());
reader = result.ExecuteReader();
while (reader.Read())
{ {
InventoryFolderBase curFolder = readInventoryFolder(reader); result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
folders.Add(curFolder); using (MySqlDataReader reader = result.ExecuteReader())
{
while (reader.Read())
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
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());
reader = result.ExecuteReader();
while (reader.Read())
{ {
InventoryFolderBase curFolder = readInventoryFolder(reader); result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling
hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list using (MySqlDataReader reader = result.ExecuteReader())
else // else current folder has no known (yet) siblings
{ {
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>(); while (reader.Read())
siblingList.Add(curFolder); {
// Current folder has no known (yet) siblings InventoryFolderBase curFolder = readInventoryFolder(reader);
hashtable.Add(curFolder.ParentID, siblingList); if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling
hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list
else // else current folder has no known (yet) siblings
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
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());
lock (database)
{ {
cmd.ExecuteNonQuery(); cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
cmd.ExecuteNonQuery();
} }
} }
catch (MySqlException e) catch (MySqlException e)
{ {
database.Reconnect(); database.Reconnect();
m_log.Error(e.ToString()); m_log.Error(e.Message, e);
} }
} }
@ -827,13 +827,12 @@ 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());
lock (database)
{ {
cmd.ExecuteNonQuery(); cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
cmd.ExecuteNonQuery();
} }
} }
catch (MySqlException e) catch (MySqlException e)
@ -865,40 +864,38 @@ 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(
"SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
database.Connection);
sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
result = sqlCmd.ExecuteReader();
List<InventoryItemBase> list = new List<InventoryItemBase>(); using (MySqlCommand sqlCmd = new MySqlCommand(
while (result.Read()) "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
database.Connection))
{ {
InventoryItemBase item = readInventoryItem(result); sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
if (item != null) sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
list.Add(item);
using (MySqlDataReader result = sqlCmd.ExecuteReader())
{
List<InventoryItemBase> list = new List<InventoryItemBase>();
while (result.Read())
{
InventoryItemBase item = readInventoryItem(result);
if (item != null)
list.Add(item);
}
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,43 +280,31 @@ 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 "+
"SceneGroupID= ?UUID";
cmd.Parameters.AddWithValue("UUID", obj.ToString());
List<UUID> uuids = new List<UUID>();
IDataReader reader = ExecuteReader(cmd);
try
{ {
while (reader.Read()) cmd.CommandText = "select UUID from prims where SceneGroupID= ?UUID";
cmd.Parameters.AddWithValue("UUID", obj.ToString());
using (IDataReader reader = ExecuteReader(cmd))
{ {
uuids.Add(new UUID(reader["UUID"].ToString())); while (reader.Read())
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
// a very corrupt database, but in that case be extra
// safe anyway.
if (uuids.Count > 0)
{
RemoveShapes(uuids);
RemoveItems(uuids);
} }
} }
// there is no way this should be < 1 unless there is
// a very corrupt database, but in that case be extra
// safe anyway.
if (uuids.Count > 0)
{
RemoveShapes(uuids);
RemoveItems(uuids);
}
} }
/// <summary> /// <summary>
@ -326,19 +316,16 @@ 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 PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", uuid.ToString());
cmd.CommandText = "delete from primitems where " + ExecuteNonQuery(cmd);
"PrimID = ?PrimID"; }
cmd.Parameters.AddWithValue("PrimID", uuid.ToString());
ExecuteNonQuery(cmd);
cmd.Dispose();
} }
} }
/// <summary> /// <summary>
/// Remove all persisted shapes for a list of prims /// Remove all persisted shapes for a list of prims
/// The caller must acquire the necessrary synchronization locks /// The caller must acquire the necessrary synchronization locks
@ -349,28 +336,27 @@ 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();
for (int i = 0; i < uuids.Count; i++) using (MySqlCommand cmd = m_Connection.CreateCommand())
{ {
if ((i + 1) == uuids.Count) for (int i = 0; i < uuids.Count; i++)
{// end of the list
sql += "(UUID = ?UUID" + i + ")";
}
else
{ {
sql += "(UUID = ?UUID" + i + ") or "; if ((i + 1) == uuids.Count)
{// end of the list
sql += "(UUID = ?UUID" + i + ")";
}
else
{
sql += "(UUID = ?UUID" + i + ") or ";
}
} }
} 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,28 +370,28 @@ 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();
for (int i = 0; i < uuids.Count; i++) using (MySqlCommand cmd = m_Connection.CreateCommand())
{ {
if ((i + 1) == uuids.Count) for (int i = 0; i < uuids.Count; i++)
{// end of the list
sql += "(PrimID = ?PrimID" + i + ")";
}
else
{ {
sql += "(PrimID = ?PrimID" + i + ") or "; if ((i + 1) == uuids.Count)
{
// end of the list
sql += "(PrimID = ?PrimID" + i + ")";
}
else
{
sql += "(PrimID = ?PrimID" + i + ") or ";
}
} }
} 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,77 +404,71 @@ 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 " +
"left join primshapes on prims.UUID = primshapes.UUID "+ "left join primshapes on prims.UUID = primshapes.UUID " +
"where RegionUUID = ?RegionUUID " + "where RegionUUID = ?RegionUUID " +
"order by SceneGroupID asc, sort asc, LinkNumber asc"; "order by SceneGroupID asc, sort asc, LinkNumber asc";
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())
{ {
SceneObjectPart prim = BuildPrim(reader); while (reader.Read())
if (reader["Shape"] is DBNull)
prim.Shape = PrimitiveBaseShape.Default;
else
prim.Shape = BuildShape(reader);
prims[prim.UUID] = prim;
UUID groupID = new UUID(reader["SceneGroupID"].ToString());
if (groupID != lastGroupID) // New SOG
{ {
if (grp != null) SceneObjectPart prim = BuildPrim(reader);
objects[grp.UUID] = grp; if (reader["Shape"] is DBNull)
prim.Shape = PrimitiveBaseShape.Default;
else
prim.Shape = BuildShape(reader);
lastGroupID = groupID; prims[prim.UUID] = prim;
// There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are UUID groupID = new UUID(reader["SceneGroupID"].ToString());
// recorded as the root prim (for which the UUID must equal the persisted group UUID). In
// this case, force the UUID to be the same as the group UUID so that at least these can be if (groupID != lastGroupID) // New SOG
// deleted (we need to change the UUID so that any other prims in the linkset can also be
// deleted).
if (prim.UUID != groupID && groupID != UUID.Zero)
{ {
m_log.WarnFormat( if (grp != null)
"[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID", objects[grp.UUID] = grp;
prim.Name, prim.UUID, prim.GroupPosition, groupID);
prim.UUID = groupID; lastGroupID = groupID;
// There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are
// recorded as the root prim (for which the UUID must equal the persisted group UUID). In
// this case, force the UUID to be the same as the group UUID so that at least these can be
// deleted (we need to change the UUID so that any other prims in the linkset can also be
// deleted).
if (prim.UUID != groupID && groupID != UUID.Zero)
{
m_log.WarnFormat(
"[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID",
prim.Name, prim.UUID, prim.GroupPosition, groupID);
prim.UUID = groupID;
}
grp = new SceneObjectGroup(prim);
} }
else
{
// Black magic to preserve link numbers
//
int link = prim.LinkNum;
grp = new SceneObjectGroup(prim); grp.AddPart(prim);
}
else
{
// Black magic to preserve link numbers
//
int link = prim.LinkNum;
grp.AddPart(prim); if (link != 0)
prim.LinkNum = link;
if (link != 0) }
prim.LinkNum = link;
} }
} }
}
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,34 +478,29 @@ 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";
IDataReader itemReader = ExecuteReader(itemCmd);
try
{ {
while (itemReader.Read()) itemCmd.CommandText = "select distinct primID from primitems";
using (IDataReader itemReader = ExecuteReader(itemCmd))
{ {
if (!(itemReader["primID"] is DBNull)) while (itemReader.Read())
{ {
UUID primID = new UUID(itemReader["primID"].ToString()); if (!(itemReader["primID"] is DBNull))
if (prims.ContainsKey(primID))
{ {
primsWithInventory.Add(prims[primID]); UUID primID = new UUID(itemReader["primID"].ToString());
if (prims.ContainsKey(primID))
{
primsWithInventory.Add(prims[primID]);
}
} }
} }
} }
} }
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 "+ using (MySqlCommand cmd = m_Connection.CreateCommand())
"PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString());
IDataReader reader = ExecuteReader(cmd);
List<TaskInventoryItem> inventory =
new List<TaskInventoryItem>();
try
{ {
while (reader.Read()) cmd.CommandText = "select * from primitems where PrimID = ?PrimID";
{ cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString());
TaskInventoryItem item = BuildItem(reader);
item.ParentID = prim.UUID; // Values in database are using (IDataReader reader = ExecuteReader(cmd))
// often wrong {
inventory.Add(item); while (reader.Read())
{
TaskInventoryItem item = BuildItem(reader);
item.ParentID = prim.UUID; // Values in database are often wrong
inventory.Add(item);
}
} }
} }
finally
{
reader.Close();
}
cmd.Dispose();
prim.Inventory.RestoreInventoryItems(inventory); prim.Inventory.RestoreInventoryItems(inventory);
} }
} }
@ -576,23 +542,21 @@ 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 RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
cmd.CommandText = "delete from terrain where " + ExecuteNonQuery(cmd);
"RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
ExecuteNonQuery(cmd); cmd.CommandText = "insert into terrain (RegionUUID, " +
cmd.CommandText = "insert into terrain (RegionUUID, " +
"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 " +
"from terrain where RegionUUID = ?RegionUUID "+
"order by Revision desc limit 1";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
IDataReader reader = ExecuteReader(cmd);
try
{ {
while (reader.Read()) cmd.CommandText = "select RegionUUID, Revision, Heightfield " +
"from terrain where RegionUUID = ?RegionUUID " +
"order by Revision desc limit 1";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
using (IDataReader reader = ExecuteReader(cmd))
{ {
terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; while (reader.Read())
terrain.Initialize();
MemoryStream mstr = new MemoryStream((byte[]) reader["Heightfield"]);
int rev = 0;
BinaryReader br = new BinaryReader(mstr);
for (int x = 0; x < (int)Constants.RegionSize; x++)
{ {
for (int y = 0; y < (int)Constants.RegionSize; y++) int rev = Convert.ToInt32(reader["Revision"]);
terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize];
terrain.Initialize();
using (MemoryStream mstr = new MemoryStream((byte[])reader["Heightfield"]))
{ {
terrain[x, y] = br.ReadDouble(); using (BinaryReader br = new BinaryReader(mstr))
{
for (int x = 0; x < (int)Constants.RegionSize; x++)
{
for (int y = 0; y < (int)Constants.RegionSize; y++)
{
terrain[x, y] = br.ReadDouble();
}
}
}
m_log.InfoFormat("[REGION DB]: Loaded terrain revision r{0}", rev);
} }
rev = Convert.ToInt32(reader["Revision"]);
} }
m_log.InfoFormat("[REGION DB]: Loaded terrain " +
"revision r{0}", rev);
} }
} }
finally
{
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.Parameters.AddWithValue("UUID", globalID.ToString());
cmd.CommandText = "delete from land where UUID = ?UUID"; ExecuteNonQuery(cmd);
}
cmd.Parameters.AddWithValue("UUID", globalID.ToString());
ExecuteNonQuery(cmd);
cmd.Dispose();
} }
} }
@ -662,9 +623,9 @@ 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, " +
"Category, ClaimDate, ClaimPrice, GroupUUID, " + "Category, ClaimDate, ClaimPrice, GroupUUID, " +
@ -685,28 +646,26 @@ namespace OpenSim.Data.MySQL
"?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " + "?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " +
"?AuthbuyerID, ?OtherCleanTime, ?Dwell)"; "?AuthbuyerID, ?OtherCleanTime, ?Dwell)";
FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID); FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID);
ExecuteNonQuery(cmd);
cmd.CommandText = "delete from landaccesslist where " +
"LandUUID = ?UUID";
ExecuteNonQuery(cmd);
cmd.Parameters.Clear();
cmd.CommandText = "insert into landaccesslist (LandUUID, " +
"AccessUUID, Flags) values (?LandUUID, ?AccessUUID, " +
"?Flags)";
foreach (ParcelManager.ParcelAccessEntry entry in
parcel.LandData.ParcelAccessList)
{
FillLandAccessCommand(cmd, entry, parcel.LandData.GlobalID);
ExecuteNonQuery(cmd); ExecuteNonQuery(cmd);
cmd.CommandText = "delete from landaccesslist where LandUUID = ?UUID";
ExecuteNonQuery(cmd);
cmd.Parameters.Clear(); cmd.Parameters.Clear();
cmd.CommandText = "insert into landaccesslist (LandUUID, " +
"AccessUUID, Flags) values (?LandUUID, ?AccessUUID, " +
"?Flags)";
foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList)
{
FillLandAccessCommand(cmd, entry, parcel.LandData.GlobalID);
ExecuteNonQuery(cmd);
cmd.Parameters.Clear();
}
} }
cmd.Dispose();
} }
} }
@ -716,35 +675,28 @@ 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 " +
"regionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("regionUUID", regionUUID);
IDataReader reader = ExecuteReader(cmd);
try
{ {
if (reader.Read()) cmd.CommandText = "select * from regionsettings where regionUUID = ?RegionUUID";
{ cmd.Parameters.AddWithValue("regionUUID", regionUUID);
rs = BuildRegionSettings(reader);
rs.OnSave += StoreRegionSettings;
}
else
{
rs = new RegionSettings();
rs.RegionUUID = regionUUID;
rs.OnSave += StoreRegionSettings;
StoreRegionSettings(rs); using (IDataReader reader = ExecuteReader(cmd))
{
if (reader.Read())
{
rs = BuildRegionSettings(reader);
rs.OnSave += StoreRegionSettings;
}
else
{
rs = new RegionSettings();
rs.RegionUUID = regionUUID;
rs.OnSave += StoreRegionSettings;
StoreRegionSettings(rs);
}
} }
} }
finally
{
reader.Close();
}
cmd.Dispose();
} }
return rs; return rs;
@ -754,9 +706,9 @@ 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, " +
"allow_land_join_divide, block_show_in_search, " + "allow_land_join_divide, block_show_in_search, " +
@ -766,8 +718,8 @@ namespace OpenSim.Data.MySQL
"terrain_texture_2, terrain_texture_3, " + "terrain_texture_2, terrain_texture_3, " +
"terrain_texture_4, elevation_1_nw, " + "terrain_texture_4, elevation_1_nw, " +
"elevation_2_nw, elevation_1_ne, " + "elevation_2_nw, elevation_1_ne, " +
"elevation_2_ne, elevation_1_se, "+ "elevation_2_ne, elevation_1_se, " +
"elevation_2_se, elevation_1_sw, "+ "elevation_2_se, elevation_1_sw, " +
"elevation_2_sw, water_height, " + "elevation_2_sw, water_height, " +
"terrain_raise_limit, terrain_lower_limit, " + "terrain_raise_limit, terrain_lower_limit, " +
"use_estate_sun, fixed_sun, sun_position, " + "use_estate_sun, fixed_sun, sun_position, " +
@ -789,11 +741,10 @@ namespace OpenSim.Data.MySQL
"?SunVectorX, ?SunVectorY, ?SunVectorZ, " + "?SunVectorX, ?SunVectorY, ?SunVectorZ, " +
"?LoadedCreationDateTime, ?LoadedCreationID)"; "?LoadedCreationDateTime, ?LoadedCreationID)";
FillRegionSettingsCommand(cmd, rs); FillRegionSettingsCommand(cmd, rs);
ExecuteNonQuery(cmd);
cmd.Dispose();
ExecuteNonQuery(cmd);
}
} }
} }
@ -803,52 +754,38 @@ 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 " +
"RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
IDataReader reader = ExecuteReader(cmd);
try
{ {
while (reader.Read()) cmd.CommandText = "select * from land where RegionUUID = ?RegionUUID";
{ cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
LandData newLand = BuildLandData(reader);
landData.Add(newLand);
}
}
finally
{
reader.Close();
}
foreach (LandData land in landData) using (IDataReader reader = ExecuteReader(cmd))
{
cmd.Parameters.Clear();
cmd.CommandText = "select * from landaccesslist " +
"where LandUUID = ?LandUUID";
cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString());
reader = ExecuteReader(cmd);
try
{ {
while (reader.Read()) while (reader.Read())
{ {
land.ParcelAccessList.Add(BuildLandAccessData(reader)); LandData newLand = BuildLandData(reader);
landData.Add(newLand);
} }
} }
finally }
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
foreach (LandData land in landData)
{ {
reader.Close(); cmd.Parameters.Clear();
cmd.CommandText = "select * from landaccesslist where LandUUID = ?LandUUID";
cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString());
using (IDataReader reader = ExecuteReader(cmd))
{
while (reader.Read())
{
land.ParcelAccessList.Add(BuildLandAccessData(reader));
}
}
} }
} }
cmd.Dispose();
} }
return landData; return landData;

View File

@ -134,18 +134,16 @@ 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))
{ {
if (dbReader.Read()) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{ {
m_waitTimeout if (dbReader.Read())
= Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; {
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
} }
dbReader.Close();
cmd.Dispose();
} }
m_lastConnectionUse = DateTime.Now.Ticks; m_lastConnectionUse = DateTime.Now.Ticks;
@ -303,31 +301,31 @@ 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);
using (MySqlDataReader tables = tablesCmd.ExecuteReader())
{ {
while (tables.Read()) tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
using (MySqlDataReader tables = tablesCmd.ExecuteReader())
{ {
try while (tables.Read())
{ {
string tableName = (string) tables["TABLE_NAME"]; try
string comment = (string) tables["TABLE_COMMENT"];
if (tableList.ContainsKey(tableName))
{ {
tableList[tableName] = comment; string tableName = (string)tables["TABLE_NAME"];
string comment = (string)tables["TABLE_COMMENT"];
if (tableList.ContainsKey(tableName))
{
tableList[tableName] = comment;
}
}
catch (Exception e)
{
m_log.Error(e.Message, e);
} }
} }
catch (Exception e)
{
m_log.Error(e.ToString());
}
} }
tables.Close();
} }
} }
} }
@ -346,19 +344,19 @@ namespace OpenSim.Data.MySQL
{ {
CheckConnection(); // Not sure if this one is necessary CheckConnection(); // Not sure if this one is necessary
MySqlCommand dbcommand = (MySqlCommand) dbcon.CreateCommand(); MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
dbcommand.CommandText = sql; dbcommand.CommandText = sql;
foreach (KeyValuePair<string, object> param in parameters) foreach (KeyValuePair<string, object> param in parameters)
{ {
dbcommand.Parameters.AddWithValue(param.Key, param.Value); dbcommand.Parameters.AddWithValue(param.Key, param.Value);
} }
return (IDbCommand) dbcommand; return (IDbCommand)dbcommand;
} }
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,12 +56,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("?regionName", regionName);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
cmd.Parameters.AddWithValue("?regionName", regionName); return RunCommand(cmd);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); }
return RunCommand(cmd);
} }
public RegionData Get(int posX, int posY, UUID scopeID) public RegionData Get(int posX, int posY, UUID scopeID)
@ -70,17 +71,18 @@ 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("?posY", posY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
cmd.Parameters.AddWithValue("?posX", posX.ToString()); List<RegionData> ret = RunCommand(cmd);
cmd.Parameters.AddWithValue("?posY", posY.ToString()); if (ret.Count == 0)
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return null;
List<RegionData> ret = RunCommand(cmd); return ret[0];
if (ret.Count == 0) }
return null;
return ret[0];
} }
public RegionData Get(UUID regionID, UUID scopeID) public RegionData Get(UUID regionID, UUID scopeID)
@ -89,16 +91,17 @@ 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("?scopeID", scopeID.ToString());
cmd.Parameters.AddWithValue("?regionID", regionID.ToString()); List<RegionData> ret = RunCommand(cmd);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); if (ret.Count == 0)
return null;
List<RegionData> ret = RunCommand(cmd); return ret[0];
if (ret.Count == 0) }
return null;
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,71 +110,70 @@ 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("?startY", startY.ToString());
cmd.Parameters.AddWithValue("?endX", endX.ToString());
cmd.Parameters.AddWithValue("?endY", endY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
cmd.Parameters.AddWithValue("?startX", startX.ToString()); return RunCommand(cmd);
cmd.Parameters.AddWithValue("?startY", startY.ToString()); }
cmd.Parameters.AddWithValue("?endX", endX.ToString());
cmd.Parameters.AddWithValue("?endY", endY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
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())
{ {
RegionData ret = new RegionData(); while (result.Read())
ret.Data = new Dictionary<string, object>();
UUID regionID;
UUID.TryParse(result["uuid"].ToString(), out regionID);
ret.RegionID = regionID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
ret.RegionName = result["regionName"].ToString();
ret.posX = Convert.ToInt32(result["locX"]);
ret.posY = Convert.ToInt32(result["locY"]);
ret.sizeX = Convert.ToInt32(result["sizeX"]);
ret.sizeY = Convert.ToInt32(result["sizeY"]);
if (m_ColumnNames == null)
{ {
m_ColumnNames = new List<string>(); RegionData ret = new RegionData();
ret.Data = new Dictionary<string, object>();
DataTable schemaTable = result.GetSchemaTable(); UUID regionID;
foreach (DataRow row in schemaTable.Rows) UUID.TryParse(result["uuid"].ToString(), out regionID);
m_ColumnNames.Add(row["ColumnName"].ToString()); ret.RegionID = regionID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
ret.RegionName = result["regionName"].ToString();
ret.posX = Convert.ToInt32(result["locX"]);
ret.posY = Convert.ToInt32(result["locY"]);
ret.sizeX = Convert.ToInt32(result["sizeX"]);
ret.sizeY = Convert.ToInt32(result["sizeY"]);
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "uuid")
continue;
if (s == "ScopeID")
continue;
if (s == "regionName")
continue;
if (s == "locX")
continue;
if (s == "locY")
continue;
ret.Data[s] = result[s].ToString();
}
retList.Add(ret);
} }
foreach (string s in m_ColumnNames)
{
if (s == "uuid")
continue;
if (s == "ScopeID")
continue;
if (s == "regionName")
continue;
if (s == "locX")
continue;
if (s == "locY")
continue;
ret.Data[s] = result[s].ToString();
}
retList.Add(ret);
} }
result.Close();
CloseReaderCommand(cmd);
return retList; return retList;
} }
@ -198,76 +200,72 @@ 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";
foreach (string field in fields)
{ {
update += ", "; string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
update += "`" + field + "` = ?"+field; foreach (string field in fields)
{
update += ", ";
update += "`" + field + "` = ?" + field;
cmd.Parameters.AddWithValue("?"+field, data.Data[field]); cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
} }
update += " where uuid = ?regionID"; update += " where uuid = ?regionID";
if (data.ScopeID != UUID.Zero) if (data.ScopeID != UUID.Zero)
update += " and ScopeID = ?scopeID"; update += " and ScopeID = ?scopeID";
cmd.CommandText = update; cmd.CommandText = update;
cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString()); cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
cmd.Parameters.AddWithValue("?regionName", data.RegionName); cmd.Parameters.AddWithValue("?regionName", data.RegionName);
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
cmd.Parameters.AddWithValue("?posX", data.posX.ToString()); cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
cmd.Parameters.AddWithValue("?posY", data.posY.ToString()); cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString()); cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString());
cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString()); cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" +
String.Join("`, `", fields) +
"`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1) if (ExecuteNonQuery(cmd) < 1)
{ {
cmd.Dispose(); string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" +
return false; String.Join("`, `", fields) +
"`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
{
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("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
cmd.Parameters.AddWithValue("?"+item, value); return true;
cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); }
if (ExecuteNonQuery(cmd) > 0)
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());
if (ExecuteNonQuery(cmd) > 0)
cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); return true;
}
if (ExecuteNonQuery(cmd) > 0)
return true;
return false; return false;
} }

View File

@ -64,48 +64,44 @@ 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("?scopeID", scopeID.ToString());
IDataReader result = ExecuteReader(cmd);
if (result.Read())
{ {
ret.PrincipalID = principalID; cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
UUID scope; cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
if (m_ColumnNames == null) using (IDataReader result = ExecuteReader(cmd))
{ {
m_ColumnNames = new List<string>(); if (result.Read())
{
ret.PrincipalID = principalID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
DataTable schemaTable = result.GetSchemaTable(); if (m_ColumnNames == null)
foreach (DataRow row in schemaTable.Rows) {
m_ColumnNames.Add(row["ColumnName"].ToString()); m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
if (s == "ScopeID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
} }
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
if (s == "ScopeID")
continue;
ret.Data[s] = result[s].ToString();
}
result.Close();
CloseReaderCommand(cmd);
return ret;
} }
result.Close();
CloseReaderCommand(cmd);
return null; return null;
} }
@ -118,61 +114,60 @@ 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 ";
bool first = true;
foreach (string field in fields)
{ {
if (!first) string update = "update `" + m_Realm + "` set ";
update += ", "; bool first = true;
update += "`" + field + "` = ?"+field; foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = ?" + field;
first = false; first = false;
cmd.Parameters.AddWithValue("?"+field, data.Data[field]); cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
} }
update += " where UUID = ?principalID"; update += " where UUID = ?principalID";
if (data.ScopeID != UUID.Zero) if (data.ScopeID != UUID.Zero)
update += " and ScopeID = ?scopeID"; update += " and ScopeID = ?scopeID";
cmd.CommandText = update; cmd.CommandText = update;
cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString()); cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
String.Join("`, `", fields) +
"`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1) if (ExecuteNonQuery(cmd) < 1)
{ {
cmd.Dispose(); string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
return false; String.Join("`, `", fields) +
"`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
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("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0)
cmd.Parameters.AddWithValue("?"+item, value); return true;
cmd.Parameters.AddWithValue("?UUID", principalID.ToString()); }
if (ExecuteNonQuery(cmd) > 0)
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);
return row;
reader.Dispose(); }
result.Dispose(); }
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,34 +331,33 @@ 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();
while (reader.Read())
{ {
FriendListItem fli = new FriendListItem(); using (IDataReader reader = result.ExecuteReader())
fli.FriendListOwner = new UUID((string) reader["ownerID"]); {
fli.Friend = new UUID((string) reader["friendID"]); while (reader.Read())
fli.FriendPerms = (uint) Convert.ToInt32(reader["friendPerms"]); {
FriendListItem fli = new FriendListItem();
fli.FriendListOwner = new UUID((string)reader["ownerID"]);
fli.Friend = new UUID((string)reader["friendID"]);
fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]);
// This is not a real column in the database table, it's a joined column from the opposite record // This is not a real column in the database table, it's a joined column from the opposite record
fli.FriendListOwnerPerms = (uint) Convert.ToInt32(reader["ownerperms"]); fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]);
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,29 +379,29 @@ 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 +
while (reader.Read()) " where UUID = ?uuid", param))
{ {
FriendRegionInfo fri = new FriendRegionInfo(); using (IDataReader reader = result.ExecuteReader())
fri.isOnline = (sbyte)reader["agentOnline"] != 0; {
fri.regionHandle = (ulong)reader["currentHandle"]; while (reader.Read())
{
FriendRegionInfo fri = new FriendRegionInfo();
fri.isOnline = (sbyte)reader["agentOnline"] != 0;
fri.regionHandle = (ulong)reader["currentHandle"];
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,28 +430,28 @@ 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();
while (reader.Read())
{ {
AvatarPickerAvatar user = new AvatarPickerAvatar(); using (IDataReader reader = result.ExecuteReader())
user.AvatarID = new UUID((string) reader["UUID"]); {
user.firstName = (string) reader["username"]; while (reader.Read())
user.lastName = (string) reader["lastname"]; {
returnlist.Add(user); AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new UUID((string)reader["UUID"]);
user.firstName = (string)reader["username"];
user.lastName = (string)reader["lastname"];
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,28 +468,28 @@ 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();
while (reader.Read())
{ {
AvatarPickerAvatar user = new AvatarPickerAvatar(); using (IDataReader reader = result.ExecuteReader())
user.AvatarID = new UUID((string) reader["UUID"]); {
user.firstName = (string) reader["username"]; while (reader.Read())
user.lastName = (string) reader["lastname"]; {
returnlist.Add(user); AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new UUID((string)reader["UUID"]);
user.firstName = (string)reader["username"];
user.lastName = (string)reader["lastname"];
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(); return row;
result.Dispose(); }
}
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
@ -569,15 +571,15 @@ namespace OpenSim.Data.MySQL
try try
{ {
dbm.Manager.ExecuteParameterizedSql( dbm.Manager.ExecuteParameterizedSql(
"update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " + "update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " +
"where UUID = ?UUID", "where UUID = ?UUID",
param); param);
} }
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);
return row;
reader.Dispose(); }
result.Dispose(); }
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,19 +638,20 @@ 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.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeLocation.Z, user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.HomeLocation.Z,
user.LastLogin, user.UserInventoryURI, user.UserAssetURI, user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
user.CanDoMask, user.WantDoMask, user.LastLogin, user.UserInventoryURI, user.UserAssetURI,
user.AboutText, user.FirstLifeAboutText, user.Image, user.CanDoMask, user.WantDoMask,
user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner); user.AboutText, user.FirstLifeAboutText, user.Image,
user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
} }
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,14 +694,15 @@ 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.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeLocation.Z, user.HomeLookAt.X, user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, user.HomeLocation.Z, user.HomeLookAt.X,
user.UserInventoryURI, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin,
user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText, user.UserInventoryURI,
user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey, user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText,
user.UserFlags, user.GodLevel, user.CustomType, user.Partner); user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey,
user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
} }
finally finally
{ {
@ -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();
AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader);
reader.Dispose();
result.Dispose();
if (null == appearance)
{ {
m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); using (IDataReader reader = result.ExecuteReader())
return null; {
AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader);
if (appearance == null)
{
m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString());
return null;
}
else
{
appearance.SetAttachments(GetUserAttachments(user));
return appearance;
}
}
} }
appearance.SetAttachments(GetUserAttachments(user));
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(); return ret;
result.Dispose(); }
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,13 +581,17 @@ 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);
for (int x = 0; x < (int)Constants.RegionSize; x++)
{ {
for (int y = 0; y < (int)Constants.RegionSize; y++) using (BinaryReader br = new BinaryReader(str))
{ {
terret[x, y] = br.ReadDouble(); for (int x = 0; x < (int)Constants.RegionSize; x++)
{
for (int y = 0; y < (int)Constants.RegionSize; y++)
{
terret[x, y] = br.ReadDouble();
}
}
} }
} }
rev = (int) row["Revision"]; rev = (int) row["Revision"];

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
{ {
deserial = (TResponse) deserializer.Deserialize( respStream = response.GetResponseStream();
response.GetResponseStream()); deserial = (TResponse)deserializer.Deserialize(
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,13 +94,26 @@ 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;
resp.Close(); try
{
respStream = resp.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch { }
finally
{
if (respStream != null)
respStream.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,8 +66,23 @@ 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;
requestStream.Write(buffer.ToArray(), 0, length); try
{
requestStream = request.GetRequestStream();
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,9 +93,20 @@ namespace OpenSim.Framework.Servers.HttpServer
{ {
if (resp.ContentLength > 0) if (resp.ContentLength > 0)
{ {
using (StreamReader reader = new StreamReader(resp.GetResponseStream())) Stream respStream = null;
try
{ {
respstring = reader.ReadToEnd(); respStream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(respStream))
{
respstring = reader.ReadToEnd();
}
}
catch { }
finally
{
if (respStream != null)
respStream.Close();
} }
} }
} }

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;
requestStream.Write(buffer.ToArray(), 0, length); try
{
requestStream = request.GetRequestStream();
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
return null;
}
XmlRpcResponse GridResp = GridReq.Send(m_cfg.GridServerURL, 3000); private RegionProfileData GridRegionToRegionProfile(GridRegion region)
{
Hashtable responseData = (Hashtable)GridResp.Value; RegionProfileData rprofile = new RegionProfileData();
rprofile.httpPort = region.HttpPort;
if (responseData.ContainsKey("error")) rprofile.httpServerURI = region.ServerURI;
{ rprofile.regionLocX = (uint)(region.RegionLocX / Constants.RegionSize);
m_log.Error("[GRID]: error received from grid server" + responseData["error"]); rprofile.regionLocY = (uint)(region.RegionLocY / Constants.RegionSize);
return null; rprofile.RegionName = region.RegionName;
} rprofile.ServerHttpPort = region.HttpPort;
rprofile.ServerIP = region.ExternalHostName;
uint regX = Convert.ToUInt32((string)responseData["region_locx"]); rprofile.ServerPort = (uint)region.ExternalEndPoint.Port;
uint regY = Convert.ToUInt32((string)responseData["region_locy"]); rprofile.Uuid = region.RegionID;
string internalIpStr = (string)responseData["sim_ip"]; return rprofile;
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]: " +
"Region lookup failed for: " + regionHandle.ToString() +
" - Is the GridServer down?");
}
return regionProfile;
} }
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,32 +194,65 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_stopPacket = TexturePacketCount(); m_stopPacket = TexturePacketCount();
} }
m_packetNumber = m_requestedPacketNumber; m_currentPacket = StartPacket;
} }
if (m_imageManager.Client.PacketHandler.GetQueueCount(ThrottleOutPacketType.Texture) == 0) if ((m_imageManager != null) && (m_imageManager.Client != null) && (m_imageManager.Client.PacketHandler != null))
{ if (m_imageManager.Client.PacketHandler.GetQueueCount(ThrottleOutPacketType.Texture) == 0)
//m_log.Debug("No textures queued, sending one packet to kickstart it"); {
SendPacket(m_imageManager.Client); //m_log.Debug("No textures queued, sending one packet to kickstart it");
} SendPacket(m_imageManager.Client);
}
} }
} }
} }
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;
{ int numCollected = 0;
//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() //lock (m_syncRoot)
if (m_client == null) //{
m_lastloopprocessed = DateTime.Now.Ticks;
// This can happen during Close()
if (m_client == null || m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null)
return false; return false;
int numCollected = 0; while ((imagereq = GetHighestPriorityImage()) != null)
//Calculate our threshold
int threshold;
if (m_lastloopprocessed == 0)
{ {
if (m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null || m_client.PacketHandler.PacketQueue.TextureThrottle == null) if (imagereq.IsDecoded == true)
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;
}
if (m_client.PacketHandler == null)
return false;
if (m_client.PacketHandler.PacketQueue == 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)
{ {
J2KImage imagereq = null; ++numCollected;
lock (m_priorityQueue)
imagereq = m_priorityQueue.FindMax();
if (imagereq.m_decoded == true) if (imagereq.SendPackets(m_client, maxpack))
{ {
// we need to test this here now that we are dropping assets // Send complete. Destroy any knowledge of this transfer
if (!imagereq.m_hasasset) RemoveImageFromQueue(imagereq);
{
m_log.WarnFormat("[LLIMAGE MANAGER]: Re-requesting the image asset {0}", imagereq.m_requestedUUID);
imagereq.RunUpdate();
continue;
}
++numCollected;
//SendPackets will send up to ten packets per cycle
if (imagereq.SendPackets(m_client, maxpack))
{
// Send complete. Destroy any knowledge of this transfer
try
{
lock (m_priorityQueue)
m_priorityQueue.Delete(imagereq.m_priorityQueueHandle);
}
catch (Exception) { }
}
} }
if (numCollected == count)
break;
} }
}
return m_priorityQueue.Count > 0; if (numCollected == count)
} break;
}
//}
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)
{ {
Stream stream = null;
// Make sure the target cache directory exists
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 try
{ {
// Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename);
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,10 +397,15 @@ 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>
@ -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)
if (m_uniqueMeshes.TryGetValue(key, out mesh)) {
return mesh; key = GetMeshKey(primShape, size, lod);
if (m_uniqueMeshes.TryGetValue(key, out 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();
} }
m_uniqueMeshes.Add(key, mesh);
if (!primShape.SculptEntry)
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>