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; }
}
internal static Encoding Encoding = Encoding.UTF8;
internal static Encoding Encoding = Util.UTF8;
/// <summary>
/// Version control for REST implementation. This
@ -435,7 +435,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
try
{
byte[] encData_byte = new byte[str.Length];
encData_byte = Encoding.UTF8.GetBytes(str);
encData_byte = Util.UTF8.GetBytes(str);
return Convert.ToBase64String(encData_byte);
}
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()
{
//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("logoff_user", LogOffUser);
MainServer.Instance.AddXmlRPCHandler("expect_user", ExpectUser, false);
MainServer.Instance.AddXmlRPCHandler("logoff_user", LogOffUser, false);
}
protected void AddScene(Scene scene)
@ -182,103 +182,125 @@ namespace OpenSim.Client.Linden
/// <returns></returns>
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();
if (!RegionLoginsEnabled)
try
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
agentData.firstname, agentData.lastname);
ulong regionHandle = 0;
Hashtable requestData = (Hashtable)request.Params[0];
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();
respdata["success"] = "FALSE";
respdata["reason"] = "region login currently disabled";
resp.Value = respdata;
}
else
{
bool success = false;
string denyMess = "";
// Appearance
if (requestData.ContainsKey("appearance"))
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
Scene scene;
if (TryGetRegion(regionHandle, out scene))
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"))
{
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";
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))
if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
{
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
{
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);
string reason;
if (scene.NewUserConnection(agentData, out reason))
{
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
{
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;
}
}
catch (Exception e)
{
m_log.WarnFormat("[CLIENT]: Unable to receive user. Reason: {0}", e);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "Exception occurred";
resp.Value = respdata;
}
return resp;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -131,25 +131,26 @@ namespace OpenSim.Data
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!");
DbCommand cmd = _conn.CreateCommand();
foreach (KeyValuePair<int, string> kvp in migrations)
using (DbCommand cmd = _conn.CreateCommand())
{
int newversion = kvp.Key;
cmd.CommandText = kvp.Value;
// we need to up the command timeout to infinite as we might be doing long migrations.
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
foreach (KeyValuePair<int, string> kvp in migrations)
{
int newversion = kvp.Key;
cmd.CommandText = kvp.Value;
// we need to up the command timeout to infinite as we might be doing long migrations.
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
if (version == 0)
{
InsertVersion(_type, newversion);
if (version == 0)
{
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)
{
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";
using (IDataReader reader = cmd.ExecuteReader())
try
{
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;
}
private void InsertVersion(string type, int version)
{
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.ExecuteNonQuery();
cmd.Dispose();
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.ExecuteNonQuery();
}
}
private void UpdateVersion(string type, int version)
{
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.ExecuteNonQuery();
cmd.Dispose();
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.ExecuteNonQuery();
}
}
// private SortedList<int, string> GetAllMigrations()

View File

@ -142,46 +142,45 @@ namespace OpenSim.Data.MySQL
{
_dbConnection.CheckConnection();
MySqlCommand cmd =
new MySqlCommand(
"SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id",
_dbConnection.Connection);
cmd.Parameters.AddWithValue("?id", assetID.ToString());
using (MySqlCommand cmd = new MySqlCommand(
"SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id",
_dbConnection.Connection))
{
cmd.Parameters.AddWithValue("?id", assetID.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
try
{
if (dbReader.Read())
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
asset = new AssetBase();
asset.Data = (byte[]) dbReader["data"];
asset.Description = (string) dbReader["description"];
asset.FullID = assetID;
try
if (dbReader.Read())
{
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;
@ -297,32 +296,27 @@ namespace OpenSim.Data.MySQL
{
_dbConnection.CheckConnection();
MySqlCommand cmd =
new MySqlCommand(
"SELECT id FROM assets WHERE id=?id",
_dbConnection.Connection);
cmd.Parameters.AddWithValue("?id", uuid.ToString());
try
using (MySqlCommand cmd = new MySqlCommand(
"SELECT id FROM assets WHERE id=?id",
_dbConnection.Connection))
{
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)
{
m_log.ErrorFormat(
"[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Attempting reconnection", uuid);
_dbConnection.Reconnect();
catch (Exception e)
{
m_log.ErrorFormat(
"[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Attempting reconnection", uuid);
_dbConnection.Reconnect();
}
}
}

View File

@ -55,44 +55,38 @@ namespace OpenSim.Data.MySQL
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
MySqlCommand cmd = new MySqlCommand(
"select * from `"+m_Realm+"` where UUID = ?principalID"
);
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
IDataReader result = ExecuteReader(cmd);
if (result.Read())
using (MySqlCommand cmd = new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID"))
{
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();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
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;
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;
}

View File

@ -95,21 +95,17 @@ namespace OpenSim.Data.MySQL
protected void GetWaitTimeout()
{
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect,
m_connection);
using (MySqlDataReader dbReader =
cmd.ExecuteReader(CommandBehavior.SingleRow))
using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, m_connection))
{
if (dbReader.Read())
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) *
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
if (dbReader.Read())
{
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) *
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
}
dbReader.Close();
cmd.Dispose();
}
m_lastConnectionUse = DateTime.Now.Ticks;
@ -147,53 +143,122 @@ namespace OpenSim.Data.MySQL
CheckConnection();
MySqlCommand cmd = m_connection.CreateCommand();
bool migration = true;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
IDataReader r = cmd.ExecuteReader();
if (r.Read())
using (MySqlCommand cmd = m_connection.CreateCommand())
{
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;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
using (IDataReader r = cmd.ExecuteReader())
{
if (r.Read())
{
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
//
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
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.Parameters.Clear();
foreach (string name in FieldList)
{
@ -211,83 +276,8 @@ namespace OpenSim.Data.MySQL
}
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);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
@ -300,50 +290,52 @@ namespace OpenSim.Data.MySQL
CheckConnection();
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())
using (MySqlCommand cmd = m_connection.CreateCommand())
{
EstateBan eb = new EstateBan();
cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
using (IDataReader r = cmd.ExecuteReader())
{
while (r.Read())
{
EstateBan eb = new EstateBan();
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
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)
{
CheckConnection();
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)
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.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.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();
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)
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue("?uuid", uuid.ToString());
cmd.ExecuteNonQuery();
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();
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())
using (MySqlCommand cmd = m_connection.CreateCommand())
{
// EstateBan eb = new EstateBan();
cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID);
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
using (IDataReader r = cmd.ExecuteReader())
{
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();
}

View File

@ -40,6 +40,8 @@ namespace OpenSim.Data.MySQL
/// </summary>
public class MySqlFramework
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected MySqlConnection m_Connection;
protected MySqlFramework(string connectionString)
@ -70,12 +72,11 @@ namespace OpenSim.Data.MySQL
}
catch (MySqlException e)
{
Console.WriteLine(e.ToString());
m_log.Error(e.Message, e);
if (errorSeen)
throw;
// This is "Server has gone away" and "Server lost"
//
if (e.Number == 2006 || e.Number == 2013)
{
errorSeen = true;
@ -94,7 +95,7 @@ Console.WriteLine(e.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
m_log.Error(e.Message, e);
return 0;
}
}
@ -112,12 +113,5 @@ Console.WriteLine(e.ToString());
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["?ymax"] = ymax.ToString();
IDbCommand result =
dbm.Manager.Query(
using (IDbCommand result = dbm.Manager.Query(
"SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax",
param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>();
while ((row = dbm.Manager.readSimRow(reader)) != null)
param))
{
rows.Add(row);
}
reader.Close();
result.Dispose();
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row;
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)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -243,29 +241,27 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?name"] = namePrefix + "%";
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName LIKE ?name",
param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>();
while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
using (IDbCommand result = dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName LIKE ?name",
param))
{
rows.Add(row);
}
reader.Close();
result.Dispose();
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row;
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)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -286,21 +282,21 @@ namespace OpenSim.Data.MySQL
try
{
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);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row;
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param))
{
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = dbm.Manager.readSimRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -321,23 +317,24 @@ namespace OpenSim.Data.MySQL
try
{
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);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row;
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = dbm.Manager.readSimRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
} finally
}
finally
{
dbm.Release();
}
@ -359,22 +356,21 @@ namespace OpenSim.Data.MySQL
// Add % because this is a like query.
param["?regionName"] = regionName + "%";
// Order by statement will return shorter matches first. Only returns one record or no record.
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1",
param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row;
using (IDbCommand result = dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
RegionProfileData row = dbm.Manager.readSimRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -382,6 +378,7 @@ namespace OpenSim.Data.MySQL
dbm.Release();
}
}
m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters");
return null;
}
@ -394,12 +391,12 @@ namespace OpenSim.Data.MySQL
override public DataResponse StoreProfile(RegionProfileData profile)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
try
{
if (dbm.Manager.insertRegion(profile))
{
return DataResponse.RESPONSE_OK;
}
return DataResponse.RESPONSE_ERROR;
else
return DataResponse.RESPONSE_ERROR;
}
finally
{
@ -417,14 +414,14 @@ namespace OpenSim.Data.MySQL
{
MySQLSuperManager dbm = GetLockedConnection();
try {
try
{
if (dbm.Manager.deleteRegion(uuid))
{
return DataResponse.RESPONSE_OK;
}
return DataResponse.RESPONSE_ERROR;
} finally
else
return DataResponse.RESPONSE_ERROR;
}
finally
{
dbm.Release();
}
@ -482,26 +479,26 @@ namespace OpenSim.Data.MySQL
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
param["?x"] = x.ToString();
param["?y"] = y.ToString();
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
param);
IDataReader reader = result.ExecuteReader();
ReservationData row = dbm.Manager.readReservationRow(reader);
reader.Close();
result.Dispose();
return row;
param["?x"] = x.ToString();
param["?y"] = y.ToString();
using (IDbCommand result = dbm.Manager.Query(
"SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
ReservationData row = dbm.Manager.readReservationRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
} finally
}
finally
{
dbm.Release();
}

View File

@ -135,30 +135,30 @@ namespace OpenSim.Data.MySQL
database.CheckConnection();
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", folderID.ToString());
MySqlDataReader reader = result.ExecuteReader();
while (reader.Read())
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
database.Connection))
{
// A null item (because something went wrong) breaks everything in the folder
InventoryItemBase item = readInventoryItem(reader);
if (item != null)
items.Add(item);
result.Parameters.AddWithValue("?uuid", folderID.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
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)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
}
@ -176,29 +176,28 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand result =
new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlCommand result = new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection))
{
result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items;
return items;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
}
@ -217,41 +216,38 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand result =
new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
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)
using (MySqlCommand result = new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection))
{
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)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
}
@ -271,27 +267,26 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
database.Connection))
{
result.Parameters.AddWithValue("?uuid", parentID.ToString());
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())
items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items;
return items;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
}
@ -370,25 +365,25 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection);
result.Parameters.AddWithValue("?uuid", itemID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection))
{
result.Parameters.AddWithValue("?uuid", itemID.ToString());
InventoryItemBase item = null;
if (reader.Read())
item = readInventoryItem(reader);
using (MySqlDataReader reader = result.ExecuteReader())
{
InventoryItemBase item = null;
if (reader.Read())
item = readInventoryItem(reader);
reader.Close();
result.Dispose();
return item;
return item;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
return null;
}
@ -413,7 +408,7 @@ namespace OpenSim.Data.MySQL
}
catch (Exception e)
{
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
return null;
@ -433,24 +428,25 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection);
result.Parameters.AddWithValue("?uuid", folderID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
{
result.Parameters.AddWithValue("?uuid", folderID.ToString());
InventoryFolderBase folder = null;
if (reader.Read())
folder = readInventoryFolder(reader);
reader.Close();
result.Dispose();
using (MySqlDataReader reader = result.ExecuteReader())
{
InventoryFolderBase folder = null;
if (reader.Read())
folder = readInventoryFolder(reader);
return folder;
return folder;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
}
@ -698,69 +694,73 @@ namespace OpenSim.Data.MySQL
try
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
Dictionary<UUID, List<InventoryFolderBase>> hashtable
= new Dictionary<UUID, List<InventoryFolderBase>>(); ;
Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(); ;
List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>();
bool buildResultsFromHashTable = false;
lock (database)
{
MySqlCommand result;
MySqlDataReader reader;
bool buildResultsFromHashTable = false;
database.CheckConnection();
/* Fetch the parent folder from the database to determine the agent ID, and if
* we're querying the root of the inventory folder tree */
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentID.ToString());
reader = result.ExecuteReader();
while (reader.Read()) // Should be at most 1 result
parentFolder.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
{
result.Parameters.AddWithValue("?uuid", parentID.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
// Should be at most 1 result
while (reader.Read())
parentFolder.Add(readInventoryFolder(reader));
}
}
if (parentFolder.Count >= 1) // No result means parent folder does not exist
{
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 */
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
reader = result.ExecuteReader();
while (reader.Read())
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
{
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);
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
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
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
* indexed by their parent ID */
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
reader = result.ExecuteReader();
while (reader.Read())
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
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
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
hashtable.Add(curFolder.ParentID, siblingList);
while (reader.Read())
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
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
// we unlock the database
@ -781,12 +781,13 @@ namespace OpenSim.Data.MySQL
folders.AddRange(hashtable[folders[i].ID]);
}
} // lock (database)
return folders;
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
}
@ -801,19 +802,18 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection))
{
cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
cmd.ExecuteNonQuery();
}
}
catch (MySqlException e)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
}
@ -827,13 +827,12 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection))
{
cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
cmd.ExecuteNonQuery();
}
}
catch (MySqlException e)
@ -865,40 +864,38 @@ namespace OpenSim.Data.MySQL
public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
{
MySqlDataReader result = null;
MySqlCommand sqlCmd = null;
lock (database)
{
try
{
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>();
while (result.Read())
using (MySqlCommand sqlCmd = new MySqlCommand(
"SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
database.Connection))
{
InventoryItemBase item = readInventoryItem(result);
if (item != null)
list.Add(item);
sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
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)
{
database.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
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)
{
List<UUID> uuids = new List<UUID>();
// Formerly, this used to check the region UUID.
// That makes no sense, as we remove the contents of a prim
// unconditionally, but the prim dependent on the region ID.
@ -278,43 +280,31 @@ namespace OpenSim.Data.MySQL
//
lock (m_Connection)
{
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
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
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
cmd.CommandText = "delete from prims where SceneGroupID= ?UUID";
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);
// delete the main prims
cmd.CommandText = "delete from prims where SceneGroupID= ?UUID";
ExecuteNonQuery(cmd);
}
}
// 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>
@ -326,19 +316,16 @@ namespace OpenSim.Data.MySQL
{
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 " +
"PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", uuid.ToString());
ExecuteNonQuery(cmd);
cmd.Dispose();
ExecuteNonQuery(cmd);
}
}
}
/// <summary>
/// Remove all persisted shapes for a list of prims
/// The caller must acquire the necessrary synchronization locks
@ -349,28 +336,27 @@ namespace OpenSim.Data.MySQL
lock (m_Connection)
{
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)
{// end of the list
sql += "(UUID = ?UUID" + i + ")";
}
else
for (int i = 0; i < uuids.Count; i++)
{
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++)
{
cmd.Parameters.AddWithValue("UUID" + i, uuids[i].ToString());
}
for (int i = 0; i < uuids.Count; i++)
cmd.Parameters.AddWithValue("UUID" + i, uuids[i].ToString());
ExecuteNonQuery(cmd);
cmd.Dispose();
ExecuteNonQuery(cmd);
}
}
}
@ -384,28 +370,28 @@ namespace OpenSim.Data.MySQL
lock (m_Connection)
{
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)
{// end of the list
sql += "(PrimID = ?PrimID" + i + ")";
}
else
for (int i = 0; i < uuids.Count; i++)
{
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++)
{
cmd.Parameters.AddWithValue("PrimID" + i, uuids[i].ToString());
}
for (int i = 0; i < uuids.Count; i++)
cmd.Parameters.AddWithValue("PrimID" + i, uuids[i].ToString());
ExecuteNonQuery(cmd);
cmd.Dispose();
ExecuteNonQuery(cmd);
}
}
}
@ -418,77 +404,71 @@ namespace OpenSim.Data.MySQL
lock (m_Connection)
{
MySqlCommand cmd = m_Connection.CreateCommand();
cmd.CommandText = "select *, " +
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "select *, " +
"case when prims.UUID = SceneGroupID " +
"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 " +
"order by SceneGroupID asc, sort asc, LinkNumber asc";
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
IDataReader reader = ExecuteReader(cmd);
try
{
while (reader.Read())
using (IDataReader reader = ExecuteReader(cmd))
{
SceneObjectPart prim = BuildPrim(reader);
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
while (reader.Read())
{
if (grp != null)
objects[grp.UUID] = grp;
SceneObjectPart prim = BuildPrim(reader);
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
// 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)
UUID groupID = new UUID(reader["SceneGroupID"].ToString());
if (groupID != lastGroupID) // New SOG
{
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);
if (grp != null)
objects[grp.UUID] = grp;
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);
}
else
{
// Black magic to preserve link numbers
//
int link = prim.LinkNum;
grp.AddPart(prim);
grp.AddPart(prim);
if (link != 0)
prim.LinkNum = link;
if (link != 0)
prim.LinkNum = link;
}
}
}
}
finally
{
reader.Close();
}
if (grp != null)
objects[grp.UUID] = grp;
cmd.Dispose();
if (grp != null)
objects[grp.UUID] = grp;
}
}
// Instead of attempting to LoadItems on every prim,
@ -498,34 +478,29 @@ namespace OpenSim.Data.MySQL
List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>();
lock (m_Connection)
{
MySqlCommand itemCmd = m_Connection.CreateCommand();
itemCmd.CommandText = "select distinct primID from primitems";
IDataReader itemReader = ExecuteReader(itemCmd);
try
using (MySqlCommand itemCmd = m_Connection.CreateCommand())
{
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 (prims.ContainsKey(primID))
if (!(itemReader["primID"] is DBNull))
{
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)
{
LoadItems(prim);
}
m_log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count);
return new List<SceneObjectGroup>(objects.Values);
}
@ -538,34 +513,25 @@ namespace OpenSim.Data.MySQL
{
lock (m_Connection)
{
MySqlCommand cmd = m_Connection.CreateCommand();
List<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
cmd.CommandText = "select * from primitems where "+
"PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString());
IDataReader reader = ExecuteReader(cmd);
List<TaskInventoryItem> inventory =
new List<TaskInventoryItem>();
try
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
while (reader.Read())
{
TaskInventoryItem item = BuildItem(reader);
cmd.CommandText = "select * from primitems where PrimID = ?PrimID";
cmd.Parameters.AddWithValue("PrimID", prim.UUID.ToString());
item.ParentID = prim.UUID; // Values in database are
// often wrong
inventory.Add(item);
using (IDataReader reader = ExecuteReader(cmd))
{
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);
}
}
@ -576,23 +542,21 @@ namespace OpenSim.Data.MySQL
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 " +
"RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionID.ToString());
ExecuteNonQuery(cmd);
ExecuteNonQuery(cmd);
cmd.CommandText = "insert into terrain (RegionUUID, " +
cmd.CommandText = "insert into terrain (RegionUUID, " +
"Revision, Heightfield) values (?RegionUUID, " +
"1, ?Heightfield)";
cmd.Parameters.AddWithValue("Heightfield",
SerializeTerrain(ter));
cmd.Parameters.AddWithValue("Heightfield", SerializeTerrain(ter));
ExecuteNonQuery(cmd);
cmd.Dispose();
ExecuteNonQuery(cmd);
}
}
}
@ -602,42 +566,40 @@ namespace OpenSim.Data.MySQL
lock (m_Connection)
{
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
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
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];
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++)
while (reader.Read())
{
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;
@ -647,14 +609,13 @@ namespace OpenSim.Data.MySQL
{
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";
cmd.Parameters.AddWithValue("UUID", globalID.ToString());
ExecuteNonQuery(cmd);
cmd.Dispose();
ExecuteNonQuery(cmd);
}
}
}
@ -662,9 +623,9 @@ namespace OpenSim.Data.MySQL
{
lock (m_Connection)
{
MySqlCommand cmd = m_Connection.CreateCommand();
cmd.CommandText = "replace into land (UUID, RegionUUID, " +
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "replace into land (UUID, RegionUUID, " +
"LocalLandID, Bitmap, Name, Description, " +
"OwnerUUID, IsGroupOwned, Area, AuctionID, " +
"Category, ClaimDate, ClaimPrice, GroupUUID, " +
@ -685,28 +646,26 @@ namespace OpenSim.Data.MySQL
"?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " +
"?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);
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);
cmd.Parameters.Clear();
}
}
cmd.Dispose();
}
}
@ -716,35 +675,28 @@ namespace OpenSim.Data.MySQL
lock (m_Connection)
{
MySqlCommand cmd = m_Connection.CreateCommand();
cmd.CommandText = "select * from regionsettings where " +
"regionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("regionUUID", regionUUID);
IDataReader reader = ExecuteReader(cmd);
try
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
if (reader.Read())
{
rs = BuildRegionSettings(reader);
rs.OnSave += StoreRegionSettings;
}
else
{
rs = new RegionSettings();
rs.RegionUUID = regionUUID;
rs.OnSave += StoreRegionSettings;
cmd.CommandText = "select * from regionsettings where regionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("regionUUID", regionUUID);
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;
@ -754,9 +706,9 @@ namespace OpenSim.Data.MySQL
{
lock (m_Connection)
{
MySqlCommand cmd = m_Connection.CreateCommand();
cmd.CommandText = "replace into regionsettings (regionUUID, " +
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
cmd.CommandText = "replace into regionsettings (regionUUID, " +
"block_terraform, block_fly, allow_damage, " +
"restrict_pushing, allow_land_resell, " +
"allow_land_join_divide, block_show_in_search, " +
@ -766,8 +718,8 @@ namespace OpenSim.Data.MySQL
"terrain_texture_2, terrain_texture_3, " +
"terrain_texture_4, elevation_1_nw, " +
"elevation_2_nw, elevation_1_ne, " +
"elevation_2_ne, elevation_1_se, "+
"elevation_2_se, elevation_1_sw, "+
"elevation_2_ne, elevation_1_se, " +
"elevation_2_se, elevation_1_sw, " +
"elevation_2_sw, water_height, " +
"terrain_raise_limit, terrain_lower_limit, " +
"use_estate_sun, fixed_sun, sun_position, " +
@ -789,11 +741,10 @@ namespace OpenSim.Data.MySQL
"?SunVectorX, ?SunVectorY, ?SunVectorZ, " +
"?LoadedCreationDateTime, ?LoadedCreationID)";
FillRegionSettingsCommand(cmd, rs);
ExecuteNonQuery(cmd);
cmd.Dispose();
FillRegionSettingsCommand(cmd, rs);
ExecuteNonQuery(cmd);
}
}
}
@ -803,52 +754,38 @@ namespace OpenSim.Data.MySQL
lock (m_Connection)
{
MySqlCommand cmd = m_Connection.CreateCommand();
cmd.CommandText = "select * from land where " +
"RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
IDataReader reader = ExecuteReader(cmd);
try
using (MySqlCommand cmd = m_Connection.CreateCommand())
{
while (reader.Read())
{
LandData newLand = BuildLandData(reader);
landData.Add(newLand);
}
}
finally
{
reader.Close();
}
cmd.CommandText = "select * from land where RegionUUID = ?RegionUUID";
cmd.Parameters.AddWithValue("RegionUUID", regionUUID.ToString());
foreach (LandData land in landData)
{
cmd.Parameters.Clear();
cmd.CommandText = "select * from landaccesslist " +
"where LandUUID = ?LandUUID";
cmd.Parameters.AddWithValue("LandUUID", land.GlobalID.ToString());
reader = ExecuteReader(cmd);
try
using (IDataReader reader = ExecuteReader(cmd))
{
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;

View File

@ -134,18 +134,16 @@ namespace OpenSim.Data.MySQL
/// </summary>
protected void GetWaitTimeout()
{
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon);
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon))
{
if (dbReader.Read())
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
if (dbReader.Read())
{
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
}
dbReader.Close();
cmd.Dispose();
}
m_lastConnectionUse = DateTime.Now.Ticks;
@ -303,31 +301,31 @@ namespace OpenSim.Data.MySQL
{
CheckConnection();
MySqlCommand tablesCmd =
new MySqlCommand(
"SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
dbcon);
tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
using (MySqlDataReader tables = tablesCmd.ExecuteReader())
using (MySqlCommand tablesCmd = new MySqlCommand(
"SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
dbcon))
{
while (tables.Read())
tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
using (MySqlDataReader tables = tablesCmd.ExecuteReader())
{
try
while (tables.Read())
{
string tableName = (string) tables["TABLE_NAME"];
string comment = (string) tables["TABLE_COMMENT"];
if (tableList.ContainsKey(tableName))
try
{
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
MySqlCommand dbcommand = (MySqlCommand) dbcon.CreateCommand();
MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
dbcommand.CommandText = sql;
foreach (KeyValuePair<string, object> param in parameters)
{
dbcommand.Parameters.AddWithValue(param.Key, param.Value);
}
return (IDbCommand) dbcommand;
return (IDbCommand)dbcommand;
}
catch (Exception e)
{
// 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;
}
}
@ -694,8 +692,6 @@ namespace OpenSim.Data.MySQL
ret.Add(attachpoint, item);
}
r.Close();
return ret;
}

View File

@ -56,12 +56,13 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
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);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd);
return RunCommand(cmd);
}
}
public RegionData Get(int posX, int posY, UUID scopeID)
@ -70,17 +71,18 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
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());
cmd.Parameters.AddWithValue("?posY", posY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
return ret[0];
}
}
public RegionData Get(UUID regionID, UUID scopeID)
@ -89,16 +91,17 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
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());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
return ret[0];
}
}
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)
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());
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);
return RunCommand(cmd);
}
}
public List<RegionData> RunCommand(MySqlCommand cmd)
{
List<RegionData> retList = new List<RegionData>();
IDataReader result = ExecuteReader(cmd);
while (result.Read())
using (IDataReader result = ExecuteReader(cmd))
{
RegionData ret = new RegionData();
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)
while (result.Read())
{
m_ColumnNames = new List<string>();
RegionData ret = new RegionData();
ret.Data = new Dictionary<string, object>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
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>();
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;
}
@ -198,76 +200,72 @@ namespace OpenSim.Data.MySQL
string[] fields = new List<string>(data.Data.Keys).ToArray();
MySqlCommand cmd = new MySqlCommand();
string update = "update `"+m_Realm+"` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
foreach (string field in fields)
using (MySqlCommand cmd = new MySqlCommand())
{
update += ", ";
update += "`" + field + "` = ?"+field;
string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
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)
update += " and ScopeID = ?scopeID";
if (data.ScopeID != UUID.Zero)
update += " and ScopeID = ?scopeID";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
cmd.Parameters.AddWithValue("?regionName", data.RegionName);
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
cmd.Parameters.AddWithValue("?sizeX", data.sizeX.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;
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
cmd.Parameters.AddWithValue("?regionName", data.RegionName);
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString());
cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
return false;
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)
{
return false;
}
}
}
cmd.Dispose();
return true;
}
public bool SetDataItem(UUID regionID, string item, string value)
{
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm +
"` set `" + item + "` = ?" + item + " where uuid = ?UUID");
using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID"))
{
cmd.Parameters.AddWithValue("?" + item, value);
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
cmd.Parameters.AddWithValue("?"+item, value);
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
public bool Delete(UUID regionID)
{
MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm +
"` where uuid = ?UUID");
using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID"))
{
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}

View File

@ -64,48 +64,44 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
IDataReader result = ExecuteReader(cmd);
if (result.Read())
using (MySqlCommand cmd = new MySqlCommand(command))
{
ret.PrincipalID = principalID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
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();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
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;
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;
}
@ -118,61 +114,60 @@ namespace OpenSim.Data.MySQL
string[] fields = new List<string>(data.Data.Keys).ToArray();
MySqlCommand cmd = new MySqlCommand();
string update = "update `"+m_Realm+"` set ";
bool first = true;
foreach (string field in fields)
using (MySqlCommand cmd = new MySqlCommand())
{
if (!first)
update += ", ";
update += "`" + field + "` = ?"+field;
string update = "update `" + m_Realm + "` set ";
bool first = true;
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)
update += " and ScopeID = ?scopeID";
if (data.ScopeID != UUID.Zero)
update += " and ScopeID = ?scopeID";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.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;
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
return false;
string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
String.Join("`, `", fields) +
"`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
return false;
}
}
}
cmd.Dispose();
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm +
"` set `" + item + "` = ?" + item + " where UUID = ?UUID");
using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" +
item + "` = ?" + item + " where UUID = ?UUID"))
{
cmd.Parameters.AddWithValue("?" + item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
cmd.Parameters.AddWithValue("?"+item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}

View File

@ -181,21 +181,20 @@ namespace OpenSim.Data.MySQL
param["?first"] = user;
param["?second"] = last;
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param);
IDataReader reader = result.ExecuteReader();
UserProfileData row = dbm.Manager.readUserRow(reader);
reader.Dispose();
result.Dispose();
return row;
using (IDbCommand result = dbm.Manager.Query(
"SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param))
{
using (IDataReader reader = result.ExecuteReader())
{
UserProfileData row = dbm.Manager.readUserRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -220,28 +219,30 @@ namespace OpenSim.Data.MySQL
try
{
IDbCommand adder =
dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?ownerID,?friendID,?friendPerms,?datetimestamp)",
param);
adder.ExecuteNonQuery();
using (IDbCommand adder = dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?ownerID,?friendID,?friendPerms,?datetimestamp)",
param))
{
adder.ExecuteNonQuery();
}
adder =
dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?friendID,?ownerID,?friendPerms,?datetimestamp)",
param);
adder.ExecuteNonQuery();
using (IDbCommand adder = dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?friendID,?ownerID,?friendPerms,?datetimestamp)",
param))
{
adder.ExecuteNonQuery();
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return;
}
finally
@ -260,22 +261,24 @@ namespace OpenSim.Data.MySQL
try
{
IDbCommand updater =
dbm.Manager.Query(
using (IDbCommand updater = dbm.Manager.Query(
"delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
param);
updater.ExecuteNonQuery();
param))
{
updater.ExecuteNonQuery();
}
updater =
dbm.Manager.Query(
using (IDbCommand updater = dbm.Manager.Query(
"delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
param);
updater.ExecuteNonQuery();
param))
{
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return;
}
finally
@ -295,18 +298,19 @@ namespace OpenSim.Data.MySQL
try
{
IDbCommand updater =
dbm.Manager.Query(
using (IDbCommand updater = dbm.Manager.Query(
"update " + m_userFriendsTableName +
" SET friendPerms = ?friendPerms " +
"where ownerID = ?ownerID and friendID = ?friendID",
param);
updater.ExecuteNonQuery();
param))
{
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return;
}
finally
@ -327,34 +331,33 @@ namespace OpenSim.Data.MySQL
try
{
//Left Join userfriends to itself
IDbCommand result =
dbm.Manager.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " +
m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
" where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
using (IDbCommand result = dbm.Manager.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " +
m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
" where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param))
{
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"]);
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read())
{
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
fli.FriendListOwnerPerms = (uint) Convert.ToInt32(reader["ownerperms"]);
// 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"]);
Lfli.Add(fli);
Lfli.Add(fli);
}
}
}
reader.Dispose();
result.Dispose();
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return Lfli;
}
finally
@ -376,29 +379,29 @@ namespace OpenSim.Data.MySQL
{
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
IDbCommand result =
dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
" where UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
using (IDbCommand result = dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
" where UUID = ?uuid", param))
{
FriendRegionInfo fri = new FriendRegionInfo();
fri.isOnline = (sbyte)reader["agentOnline"] != 0;
fri.regionHandle = (ulong)reader["currentHandle"];
using (IDataReader reader = result.ExecuteReader())
{
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)
{
m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e);
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
finally
{
@ -427,28 +430,28 @@ namespace OpenSim.Data.MySQL
try
{
IDbCommand result =
dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first AND lastname like ?second LIMIT 100",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
using (IDbCommand result = dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first AND lastname like ?second LIMIT 100",
param))
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new UUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["lastname"];
returnlist.Add(user);
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read())
{
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)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return returnlist;
}
finally
@ -465,28 +468,28 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
IDbCommand result =
dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first OR lastname like ?first LIMIT 100",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
using (IDbCommand result = dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first OR lastname like ?first LIMIT 100",
param))
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new UUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["lastname"];
returnlist.Add(user);
using (IDataReader reader = result.ExecuteReader())
{
while (reader.Read())
{
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)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return returnlist;
}
finally
@ -510,20 +513,19 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader();
UserProfileData row = dbm.Manager.readUserRow(reader);
reader.Dispose();
result.Dispose();
return row;
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
UserProfileData row = dbm.Manager.readUserRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -569,15 +571,15 @@ namespace OpenSim.Data.MySQL
try
{
dbm.Manager.ExecuteParameterizedSql(
"update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " +
"where UUID = ?UUID",
param);
dbm.Manager.ExecuteParameterizedSql(
"update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " +
"where UUID = ?UUID",
param);
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return;
}
finally
@ -600,21 +602,19 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid",
param);
IDataReader reader = result.ExecuteReader();
UserAgentData row = dbm.Manager.readAgentRow(reader);
reader.Dispose();
result.Dispose();
return row;
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
UserAgentData row = dbm.Manager.readAgentRow(reader);
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -638,19 +638,20 @@ namespace OpenSim.Data.MySQL
try
{
dbm.Manager.insertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z,
user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
user.LastLogin, user.UserInventoryURI, user.UserAssetURI,
user.CanDoMask, user.WantDoMask,
user.AboutText, user.FirstLifeAboutText, user.Image,
user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
dbm.Manager.insertUserRow(
user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z,
user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
user.LastLogin, user.UserInventoryURI, user.UserAssetURI,
user.CanDoMask, user.WantDoMask,
user.AboutText, user.FirstLifeAboutText, user.Image,
user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
finally
{
@ -676,7 +677,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
finally
{
@ -693,14 +694,15 @@ namespace OpenSim.Data.MySQL
MySQLSuperManager dbm = GetLockedConnection("UpdateUserProfile");
try
{
dbm.Manager.updateUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z, user.HomeLookAt.X,
user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin,
user.UserInventoryURI,
user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText,
user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey,
user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
dbm.Manager.updateUserRow(
user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z, user.HomeLookAt.X,
user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin,
user.UserInventoryURI,
user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText,
user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey,
user.UserFlags, user.GodLevel, user.CustomType, user.Partner);
}
finally
{
@ -748,29 +750,29 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?owner"] = user.ToString();
IDbCommand result = dbm.Manager.Query(
"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)
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param))
{
m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString());
return null;
using (IDataReader reader = result.ExecuteReader())
{
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)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -798,7 +800,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
}
finally
{
@ -833,20 +835,20 @@ namespace OpenSim.Data.MySQL
try
{
IDbCommand result = dbm.Manager.Query(
"SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader();
Hashtable ret = dbm.Manager.readAttachments(reader);
reader.Dispose();
result.Dispose();
return ret;
using (IDbCommand result = dbm.Manager.Query(
"SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
Hashtable ret = dbm.Manager.readAttachments(reader);
return ret;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return null;
}
finally
@ -905,7 +907,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.ToString());
m_log.Error(e.Message, e);
return;
}
finally

View File

@ -581,13 +581,17 @@ namespace OpenSim.Data.SQLite
if (row.Read())
{
// TODO: put this into a function
MemoryStream str = new MemoryStream((byte[]) row["Heightfield"]);
BinaryReader br = new BinaryReader(str);
for (int x = 0; x < (int)Constants.RegionSize; x++)
using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"]))
{
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"];

View File

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

View File

@ -112,7 +112,7 @@ namespace OpenSim.Framework.Capabilities
writer.Close();
return Encoding.UTF8.GetBytes(sw.ToString());
return Util.UTF8.GetBytes(sw.ToString());
}
/// <summary>
@ -329,7 +329,7 @@ namespace OpenSim.Framework.Capabilities
reader.Read();
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);
break;
}

View File

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

View File

@ -106,7 +106,6 @@ namespace OpenSim.Framework.Communications.Clients
AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = AgentCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
}
//catch (WebException ex)
@ -116,6 +115,11 @@ namespace OpenSim.Framework.Communications.Clients
reason = "cannot contact remote region";
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//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
os = ChildUpdateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
//catch (WebException ex)
@ -234,6 +237,11 @@ namespace OpenSim.Framework.Communications.Clients
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//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
os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
//catch (WebException ex)
@ -447,6 +454,11 @@ namespace OpenSim.Framework.Communications.Clients
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//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
os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri);
}
//catch (WebException ex)
@ -522,6 +533,11 @@ namespace OpenSim.Framework.Communications.Clients
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//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
os = HelloNeighbourRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
os.Close();
//m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
}
//catch (WebException ex)
@ -607,7 +622,11 @@ namespace OpenSim.Framework.Communications.Clients
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//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);
if (count != 0)
{
tempString = Encoding.UTF8.GetString(buf, 0, count);
tempString = Util.UTF8.GetString(buf, 0, count);
sb.Append(tempString);
}
} while (count > 0);

View File

@ -91,24 +91,35 @@ namespace OpenSim.Framework.Servers.HttpServer
Stream requestStream = request.EndGetRequestStream(res);
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
request.BeginGetResponse(delegate(IAsyncResult ar)
{
response = request.EndGetResponse(ar);
Stream respStream = null;
try
{
deserial = (TResponse) deserializer.Deserialize(
response.GetResponseStream());
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(
respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
// Let's not close this
//buffer.Close();
respStream.Close();
response.Close();
}
action(deserial);
}, null);
}, null);
return;
}
@ -120,13 +131,20 @@ namespace OpenSim.Framework.Servers.HttpServer
// documented in MSDN
response = request.EndGetResponse(res2);
Stream respStream = null;
try
{
deserial = (TResponse)deserializer.Deserialize(response.GetResponseStream());
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
respStream.Close();
response.Close();
}
}
catch (WebException e)
{
@ -148,7 +166,7 @@ namespace OpenSim.Framework.Servers.HttpServer
}
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)

View File

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

View File

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

View File

@ -66,8 +66,23 @@ namespace OpenSim.Framework.Servers.HttpServer
length = (int)obj.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
Stream requestStream = null;
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;
@ -78,9 +93,20 @@ namespace OpenSim.Framework.Servers.HttpServer
{
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)
{
Type type = typeof (TRequest);
TResponse deserial = default(TResponse);
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
@ -81,19 +82,33 @@ namespace OpenSim.Framework.Servers.HttpServer
int length = (int) buffer.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
Stream requestStream = null;
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
{
using (WebResponse resp = request.GetResponse())
{
if (resp.ContentLength > 0)
{
Stream respStream = resp.GetResponseStream();
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>
/// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
/// </value>
@ -465,7 +467,7 @@ namespace OpenSim.Framework
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
{
@ -826,7 +828,7 @@ namespace OpenSim.Framework
public static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
byte[] buffer = Util.UTF8.GetBytes(text);
MemoryStream memory = new MemoryStream();
using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
{
@ -860,7 +862,7 @@ namespace OpenSim.Framework
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];
stream.Read(data, 0, length);
string strdata = Encoding.UTF8.GetString(data);
string strdata = Util.UTF8.GetString(data);
OSDMap args = null;
OSD buffer;
buffer = OSDParser.DeserializeJson(strdata);

View File

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

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);
appearance = new AvatarAppearance(user.ID);
loginParams["appearance"] = appearance.ToHashTable();
}
ArrayList SendParams = new ArrayList();

View File

@ -205,13 +205,10 @@ namespace OpenSim
Directory.CreateDirectory(m_crashDir);
}
string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
StreamWriter m_crashLog =
new StreamWriter(
Path.Combine(m_crashDir, log)
);
m_crashLog.WriteLine(msg);
m_crashLog.Close();
using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
{
m_crashLog.WriteLine(msg);
}
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,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return Encoding.UTF8.GetBytes("OK");
return Util.UTF8.GetBytes("OK");
}
public string ContentType
@ -736,7 +736,7 @@ namespace OpenSim
public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
}
public string ContentType
@ -777,7 +777,7 @@ namespace OpenSim
public byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return Encoding.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
return Util.UTF8.GetBytes(m_opensim.StatReport(httpRequest));
}
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);
public uint m_lastSequence;
public float m_requestedPriority;
public uint m_requestedPacketNumber;
public sbyte m_requestedDiscardLevel;
public UUID m_requestedUUID;
public IJ2KDecoder m_j2kDecodeModule;
public IAssetService m_assetCache;
public OpenJPEG.J2KLayerInfo[] m_layers;
public bool m_decoded;
public bool m_hasasset;
public C5.IPriorityQueueHandle<J2KImage> m_priorityQueueHandle;
public uint LastSequence;
public float Priority;
public uint StartPacket;
public sbyte DiscardLevel;
public UUID TextureID;
public IJ2KDecoder J2KDecoder;
public IAssetService AssetService;
public OpenJPEG.J2KLayerInfo[] Layers;
public bool IsDecoded;
public bool HasAsset;
public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle;
private uint m_packetNumber;
private bool m_decoderequested;
private bool m_asset_requested;
private bool m_sentinfo;
private uint m_currentPacket;
private bool m_decodeRequested;
private bool m_assetRequested;
private bool m_sentInfo;
private uint m_stopPacket;
private AssetBase m_asset;
private int m_assetDataLength;
private byte[] m_asset;
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)
{
m_imageManager = imageManager;
@ -117,33 +74,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public bool SendPackets(LLClientView client, int maxpack)
{
if (m_packetNumber <= m_stopPacket)
if (m_currentPacket <= m_stopPacket)
{
bool SendMore = true;
if (!m_sentinfo || (m_packetNumber == 0))
if (!m_sentInfo || (m_currentPacket == 0))
{
if (SendFirstPacket(client))
{
SendMore = false;
}
m_sentinfo = true;
m_packetNumber++;
m_sentInfo = true;
m_currentPacket++;
}
// bool ignoreStop = false;
if (m_packetNumber < 2)
if (m_currentPacket < 2)
{
m_packetNumber = 2;
m_currentPacket = 2;
}
int count = 0;
while (SendMore && count < maxpack && m_packetNumber <= m_stopPacket)
while (SendMore && count < maxpack && m_currentPacket <= m_stopPacket)
{
count++;
SendMore = SendPacket(client);
m_packetNumber++;
m_currentPacket++;
}
if (m_packetNumber > m_stopPacket)
if (m_currentPacket > m_stopPacket)
return true;
}
@ -156,68 +112,76 @@ namespace OpenSim.Region.ClientStack.LindenUDP
//and assign the real discardLevel and packetNumber
//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_assetCache.Get(m_requestedUUID.ToString(), this, AssetReceived);
m_assetRequested = true;
AssetService.Get(TextureID.ToString(), this, AssetReceived);
}
}
else
{
if (!m_decoded)
if (!IsDecoded)
{
//We need to decode the requested image first
if (!m_decoderequested)
if (!m_decodeRequested)
{
//Request decode
m_decoderequested = true;
m_decodeRequested = true;
// 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
{
// Send it off to the jpeg decoder
m_j2kDecodeModule.BeginDecode(m_requestedUUID, Data, J2KDecodedCallback);
J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback);
}
}
else
{
J2KDecodedCallback(m_requestedUUID, new OpenJPEG.J2KLayerInfo[0]);
J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
}
}
}
else
{
// Check for missing image asset data
if (m_asset == null || m_asset.Data == null)
if (m_asset == null)
{
// FIXME:
m_packetNumber = m_stopPacket;
m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer");
m_currentPacket = m_stopPacket;
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
if (m_requestedDiscardLevel < 0 && m_stopPacket == 0)
m_requestedDiscardLevel = (sbyte)maxDiscardLevel;
if (DiscardLevel < 0 && m_stopPacket == 0)
DiscardLevel = (sbyte)maxDiscardLevel;
// Clamp at the highest discard level
m_requestedDiscardLevel = (sbyte)Math.Min(m_requestedDiscardLevel, maxDiscardLevel);
DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel);
//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
//is just one packet bigger.
if (TexturePacketCount() == m_stopPacket + 1)
@ -230,32 +194,65 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_stopPacket = TexturePacketCount();
}
m_packetNumber = m_requestedPacketNumber;
m_currentPacket = StartPacket;
}
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);
}
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);
}
}
}
}
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)
{
bool complete = false;
int imagePacketSize = ((int)m_packetNumber == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;
int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;
try
{
if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_assetDataLength)
if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length)
{
imagePacketSize = LastPacketSize();
complete = true;
if ((CurrentBytePosition() + imagePacketSize) > m_assetDataLength)
if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length)
{
imagePacketSize = m_assetDataLength - CurrentBytePosition();
imagePacketSize = m_asset.Length - CurrentBytePosition();
complete = true;
}
}
@ -266,27 +263,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (imagePacketSize > 0)
{
byte[] imageData = new byte[imagePacketSize];
try
{
Buffer.BlockCopy(m_asset.Data, CurrentBytePosition(), imageData, 0, imagePacketSize);
}
int currentPosition = CurrentBytePosition();
try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); }
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;
}
//Send the packet
client.SendImageNextPart((ushort)(m_packetNumber - 1), m_requestedUUID, imageData);
}
if (complete)
{
return false;
}
else
{
return true;
client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData);
}
return !complete;
}
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)
{
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()
{
if (m_packetNumber == 1)
return m_assetDataLength;
int lastsize = (m_assetDataLength - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE;
if (m_currentPacket == 1)
return m_asset.Length;
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 (lastsize == 0)
{
@ -314,12 +319,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private int CurrentBytePosition()
{
if (m_packetNumber == 0)
if (m_currentPacket == 0)
return 0;
if (m_packetNumber == 1)
if (m_currentPacket == 1)
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)
{
result = FIRST_PACKET_SIZE;
@ -327,68 +332,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
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)
{
m_layers = layers;
m_decoded = true;
Layers = layers;
IsDecoded = true;
RunUpdate();
}
private void AssetDataCallback(UUID AssetID, AssetBase asset)
{
m_hasasset = true;
HasAsset = true;
if (asset == null || asset.Data == null)
{
if (m_imageManager.MissingImage != null)
{
m_asset = m_imageManager.MissingImage;
m_assetDataLength = m_asset.Data.Length;
m_asset = m_imageManager.MissingImage.Data;
}
else
{
m_asset = null;
m_decoded = true;
IsDecoded = true;
}
}
else
{
m_asset = asset;
m_assetDataLength = m_asset.Data.Length;
m_asset = asset.Data;
}
RunUpdate();

View File

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

View File

@ -45,48 +45,43 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
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 bool m_shuttingdown = false;
private long m_lastloopprocessed = 0;
private AssetBase m_missingImage = null;
private bool m_shuttingdown;
private long m_lastloopprocessed;
private AssetBase m_missingImage;
private LLClientView m_client; //Client we're assigned to
private IAssetService m_assetCache; //Asset Cache
private IJ2KDecoder m_j2kDecodeModule; //Our J2K module
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)
{
m_client = client;
m_assetCache = pAssetCache;
if (pAssetCache != null)
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;
}
public LLClientView Client
{
get { return m_client; }
}
public AssetBase MissingImage
{
get { return m_missingImage; }
}
/// <summary>
/// Handles an incoming texture request or update to an existing texture request
/// </summary>
/// <param name="newRequest"></param>
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..
if (!m_shuttingdown)
{
@ -94,7 +89,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Do a linear search for this texture download
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)
{
@ -105,7 +100,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
try
{
lock (m_priorityQueue)
m_priorityQueue.Delete(imgrequest.m_priorityQueueHandle);
m_priorityQueue.Delete(imgrequest.PriorityQueueHandle);
}
catch (Exception) { }
}
@ -116,30 +111,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
//Check the packet sequence to make sure this isn't older than
//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
imgrequest.m_lastSequence = newRequest.requestSequence;
imgrequest.LastSequence = newRequest.requestSequence;
//Update the requested discard level
imgrequest.m_requestedDiscardLevel = newRequest.DiscardLevel;
imgrequest.DiscardLevel = newRequest.DiscardLevel;
//Update the requested packet number
imgrequest.m_requestedPacketNumber = newRequest.PacketNumber;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Update the requested priority
imgrequest.m_requestedPriority = newRequest.Priority;
try
{
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);
}
imgrequest.Priority = newRequest.Priority;
UpdateImageInQueue(imgrequest);
//Run an update
imgrequest.RunUpdate();
@ -159,31 +144,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
imgrequest = new J2KImage(this);
//Assign our decoder module
imgrequest.m_j2kDecodeModule = m_j2kDecodeModule;
//Assign our asset cache module
imgrequest.m_assetCache = m_assetCache;
//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;
imgrequest.J2KDecoder = m_j2kDecodeModule;
imgrequest.AssetService = m_assetCache;
imgrequest.DiscardLevel = newRequest.DiscardLevel;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
imgrequest.Priority = newRequest.Priority;
imgrequest.TextureID = newRequest.RequestedAssetID;
imgrequest.Priority = newRequest.Priority;
//Add this download to the priority queue
lock (m_priorityQueue)
m_priorityQueue.Add(ref imgrequest.m_priorityQueueHandle, imgrequest);
AddImageToQueue(imgrequest);
//Run an update
imgrequest.RunUpdate();
@ -194,105 +164,99 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public bool ProcessImageQueue(int count, int maxpack)
{
lock (this)
{
//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.
J2KImage imagereq;
int numCollected = 0;
// this can happen during Close()
if (m_client == null)
//lock (m_syncRoot)
//{
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;
int numCollected = 0;
//Calculate our threshold
int threshold;
if (m_lastloopprocessed == 0)
while ((imagereq = GetHighestPriorityImage()) != null)
{
if (m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null || m_client.PacketHandler.PacketQueue.TextureThrottle == null)
return false;
//This is decent for a semi fast machine, but we'll calculate it more accurately based on time below
threshold = m_client.PacketHandler.PacketQueue.TextureThrottle.Current / 6300;
m_lastloopprocessed = DateTime.Now.Ticks;
}
else
{
double throttleseconds = ((double)DateTime.Now.Ticks - (double)m_lastloopprocessed) / (double)TimeSpan.TicksPerSecond;
throttleseconds = throttleseconds * m_client.PacketHandler.PacketQueue.TextureThrottle.Current;
//Average of 1000 bytes per packet
throttleseconds = throttleseconds / 1000;
//Safe-zone multiplier of 2.0
threshold = (int)(throttleseconds * 2.0);
m_lastloopprocessed = DateTime.Now.Ticks;
}
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)
if (imagereq.IsDecoded == true)
{
J2KImage imagereq = null;
lock (m_priorityQueue)
imagereq = m_priorityQueue.FindMax();
++numCollected;
if (imagereq.m_decoded == true)
if (imagereq.SendPackets(m_client, maxpack))
{
// we need to test this here now that we are dropping assets
if (!imagereq.m_hasasset)
{
m_log.WarnFormat("[LLIMAGE MANAGER]: Re-requesting the image asset {0}", imagereq.m_requestedUUID);
imagereq.RunUpdate();
continue;
}
++numCollected;
//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) { }
}
// Send complete. Destroy any knowledge of this transfer
RemoveImageFromQueue(imagereq);
}
if (numCollected == count)
break;
}
}
return m_priorityQueue.Count > 0;
}
if (numCollected == count)
break;
}
//}
return m_priorityQueue.Count > 0;
}
//Faux destructor
public void Close()
{
m_shuttingdown = true;
m_j2kDecodeModule = null;
m_assetCache = 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);
}
layerDecodeAsset.Data = Encoding.UTF8.GetBytes(stringResult.ToString());
layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
#endregion Serialize Layer Data
@ -280,7 +280,7 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
{
#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);
if (lines.Length == 0)

View File

@ -323,13 +323,13 @@ namespace Flotsam.RegionModules.AssetCache
string filename = GetFileName(id);
if (File.Exists(filename))
{
FileStream stream = null;
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();
asset = (AssetBase)bformatter.Deserialize(stream);
stream.Close();
UpdateMemoryCache(id, asset);
@ -349,6 +349,11 @@ namespace Flotsam.RegionModules.AssetCache
{
LogException(e);
}
finally
{
if (stream != null)
stream.Close();
}
}
@ -493,19 +498,20 @@ namespace Flotsam.RegionModules.AssetCache
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
{
// Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// 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());
Stream stream = File.Open(tempname, FileMode.Create);
stream = File.Open(tempname, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, asset);
stream.Close();
@ -522,6 +528,9 @@ namespace Flotsam.RegionModules.AssetCache
}
finally
{
if (stream != null)
stream.Close();
// 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
// cached

View File

@ -367,7 +367,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
// Encode outbound data
if (OutboundBody.Length > 0)
{
byte[] data = Encoding.UTF8.GetBytes(OutboundBody);
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
Stream bstream = Request.GetRequestStream();
@ -390,7 +390,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.UTF8.GetString(buf, 0, count);
tempString = Util.UTF8.GetString(buf, 0, count);
// continue building the string
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)
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) &&
((powers == 0) || ((client.ActiveGroupPowers & powers) == powers)));
return ((groupID == client.ActiveGroupId) && (client.ActiveGroupPowers != 0) &&
((powers == 0) || ((client.ActiveGroupPowers & powers) == powers)));
}
return false;
}
/// <summary>
@ -576,9 +581,12 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return objectOwnerMask;
}
if ((objectOwnerMask & (uint)PermissionMask.Transfer) != 0 && task.ObjectSaleType != 0)
objectEveryoneMask |= (uint)PrimFlags.ObjectTransfer;
// Group permissions
if ((task.GroupID != UUID.Zero) && IsGroupMember(task.GroupID, user, 0))
return objectGroupMask;
return objectGroupMask | objectEveryoneMask;
return objectEveryoneMask;
}

View File

@ -36,10 +36,10 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{
public struct HeightmapLookupValue : IComparable<HeightmapLookupValue>
{
public int Index;
public double Value;
public ushort Index;
public float Value;
public HeightmapLookupValue(int index, double value)
public HeightmapLookupValue(ushort index, float value)
{
Index = index;
Value = value;
@ -62,7 +62,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders
{
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);
@ -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 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)
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);
}
// 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);
}

View File

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

View File

@ -1332,7 +1332,8 @@ if (m_shape != null) {
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
if (!isPhantom && !IsAttachment)
// or flexible
if (!isPhantom && !IsAttachment && !(Shape.PathCurve == (byte) Extrusion.Flexible))
{
PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape(
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);
if (PhysActor != null)

View File

@ -172,7 +172,7 @@ namespace OpenSim.Region.Framework.Scenes
public string SaveToXmlString()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Encoding = Util.UTF8;
using (StringWriter sw = new StringWriter())
{
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);
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);
}
@ -109,7 +109,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
byte[] buf = new byte[8]; // RFC1459 defines max message size as 512.
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;

View File

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

View File

@ -539,7 +539,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
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;
xs.Serialize(writer, obj);

View File

@ -224,6 +224,14 @@ namespace OpenSim.Region.Physics.Meshing
for (int i = 0; i < lodBytes.Length; 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;
}
@ -389,7 +397,7 @@ namespace OpenSim.Region.Physics.Meshing
primMesh.pathCutBegin = pathBegin;
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.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)
{
Mesh mesh = null;
ulong key = 0;
// 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
ulong key = GetMeshKey(primShape, size, lod);
Mesh mesh = null;
if (m_uniqueMeshes.TryGetValue(key, out mesh))
return mesh;
if (! primShape.SculptEntry)
{
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.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
mesh.TrimExcess();
}
m_uniqueMeshes.Add(key, mesh);
if (!primShape.SculptEntry)
m_uniqueMeshes.Add(key, mesh);
return mesh;
}
}

View File

@ -7080,7 +7080,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
try
{
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);
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 "
+ textLength.ToString() + "\n" + notecardData + "}\n";
asset.Data = Encoding.UTF8.GetBytes(notecardData);
asset.Data = Util.UTF8.GetBytes(notecardData);
World.AssetService.Store(asset);
// Create Task Entry

View File

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

View File

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

Binary file not shown.

View File

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

View File

@ -957,75 +957,6 @@
</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">
<Configuration name="Debug">
<Options>
@ -1230,6 +1161,78 @@
</Files>
</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">
<Configuration name="Debug">
<Options>