Replace string field values
This example shows how to force replace a specific character in all string fields. It gets all models in the project and returns the string if the field type is string.
public void ReplaceStrings(ICommandContext c, ICommandParams p)
{
//Get all models
var models = c.App.Workspace.CurrentProject.GetAllChildren();
//Process each model
foreach(var model in models)
{
//Get metaclass field information
var fields = model.Metaclass.GetFields();
//Process only string type
var strFields = fields.Where(f => f.Type == "String");
foreach(var field in strFields)
{
//Exclude system fields
if (field.Name.StartsWith("___") || field.Name.StartsWith("$") || field.HasTags("System,System.Core")) continue;
//Get string
var currentString = model.GetFieldString(field.Name);
//Replace a string
var replacedString = currentString.Replace("\v", "\r\n");
if(currentString != replacedString)
{
model.SetField(field.Name, replacedString);
}
}
}
}
The following example masks all string fields with ***
.
public void MaskStrings(ICommandContext c, ICommandParams p)
{
var models = c.App.Workspace.CurrentProject.GetAllChildren();
//Process all models
foreach ( var model in models)
{
//Get metaclass field information
var fields = model.Metaclass.GetFields();
if ( fields == null ) continue;
foreach(var field in fields)
{
//Exclude system fields
if (field.Name.StartsWith("___") || field.Name.StartsWith("$") || field.HasTags("System,System.Core")) continue;
//Ignore non-string types
if ( field.Type != "String" ) continue;
//Mask strings
model.SetField(field,"***");
}
}
}
Hint
You can determine if a field is a system field by the following conditions:
- If the field name starts with
___
or$
. - If the field tag is set to
System
orSystem.Core
See the code below for reference.
IField field;
//...
//Exclude system fields
if (field.Name.StartsWith("___") || field.Name.StartsWith("$") || field.HasTags("System,System.Core")) continue;