/// <summary>
/// Writes given Xdata to the obj given, keeping existing xData. If the given registered app exists,
/// the existing xData for that registered app is replaced with the new xData
/// </summary>
/// <param name="objID">The id of the DBObject to write the xdata to.</param>
/// <param name="newXData">The xdata, can only contain xdata for a single registered app</param>
public static bool WriteXData(ObjectId objID, ResultBuffer newXData)
{
if (newXData.AsArray().Length < 1) return false;
if (objID.IsNull) return false;
TypedValue v = newXData.AsArray()[0];
if (v.TypeCode!=CODE_APPNAME) return false;
string appName=v.Value.ToString();
AddRegAppTableRecord(appName);
ResultBuffer updatedXdata
= new ResultBuffer
(); using (LockedTransaction tr = Active.Document.TransactionManager.StartLockedTransaction())
{
// remove any xdata for the given appname
DBObject obj = tr.GetObject(objID, OpenMode.ForWrite);
ResultBuffer existingData = obj.XData;
if (existingData!=null)
{
bool included = true;
// Get all values NOT with our Registered App
foreach (TypedValue tv in existingData)
{
if (tv.TypeCode == CODE_APPNAME)
{
if (appName.Equals(tv.Value.ToString()))
{
included = false;
}
else
{
included = true;
}
}
if (included)
{
updatedXdata.Add(tv);
}
}
}
foreach (TypedValue tv in newXData)
{
updatedXdata.Add(tv);
}
RegisterApps(updatedXdata);
obj.XData = updatedXdata;
tr.Commit();
}
return true;
}
/// <summary>
/// Registers all appnames in the given xdata.
/// </summary>
/// <param name="xData">The XData.</param>
public static void RegisterApps(ResultBuffer xData)
{
foreach (TypedValue val in xData)
{
if (val.TypeCode==CODE_APPNAME)
{
AddRegAppTableRecord(val.Value.ToString());
}
}
}
/// <summary>
/// Adds the given appname to the RegisteredAppTable if it's not there
/// </summary>
/// <param name="regAppName">appname to register</param>
private static void AddRegAppTableRecord(string regAppName)
{
using (LockedTransaction tr = Active.Document.TransactionManager.StartLockedTransaction())
{
RegAppTable rat = (RegAppTable)tr.GetObject(Active.Database.RegAppTableId, OpenMode.ForRead, false);
if (!rat.Has(regAppName))
{
// add the registered app
rat.UpgradeOpen();
RegAppTableRecord ratr
= new RegAppTableRecord
(); ratr.Name = regAppName;
tr.AddNewlyCreatedDBObject(ratr, true);
rat.Add(ratr);
}
tr.Commit();
}
}