Laservall_solidworks_inject/Extension/SWDocWriter.cs

119 lines
4.1 KiB
C#
Raw Permalink Normal View History

using Laservall.Solidworks.Common;
using SolidWorks.Interop.sldworks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laservall.Solidworks.Extension
{
public static class SWDocWriter
{
private static readonly HashSet<string> SkipWriteProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"材质", "MATERIAL",
"重量", "MASS"
};
public static void WriteDocProperties(IModelDoc2 doc, Model.PartPropModel partPropModel)
{
if (doc == null) return;
Configuration activeConfig = doc.ConfigurationManager?.ActiveConfiguration;
CustomPropertyManager configPropMgr = activeConfig?.CustomPropertyManager;
CustomPropertyManager filePropMgr = null;
try
{
filePropMgr = doc.Extension?.get_CustomPropertyManager("");
}
catch { }
string[] configNames = null;
try
{
configNames = configPropMgr?.GetNames() as string[];
}
catch { }
partPropModel.GetType().GetProperties().ToList().ForEach(p =>
{
p.CustomAttributes.ToList().ForEach(attr =>
{
if (attr.AttributeType == typeof(System.ComponentModel.DisplayNameAttribute))
{
var displayName = attr.ConstructorArguments[0].Value.ToString();
// ReadOnly属性使用ReadOnlyTextPropertyEditor的不写入
bool isReadOnly = p.CustomAttributes.Any(a =>
a.AttributeType == typeof(System.ComponentModel.EditorAttribute) &&
a.ConstructorArguments.Any(c =>
c.Value?.ToString()?.Contains(nameof(ReadOnlyTextPropertyEditor)) == true));
if (isReadOnly) return;
// 内置特殊属性不通过自定义属性写入
if (SkipWriteProperties.Contains(displayName)) return;
var val = p.GetValue(partPropModel);
string strVal = val?.ToString() ?? "";
SetPropertyValue(configPropMgr, filePropMgr, configNames, displayName, strVal);
}
});
});
}
/// <summary>
/// 写入属性值:属性存在于配置级则写配置级,否则写文件级
/// 与SolidWorksBomDataProvider.SaveChanges()保持一致的策略
/// </summary>
private static void SetPropertyValue(
CustomPropertyManager configPropMgr,
CustomPropertyManager filePropMgr,
string[] configNames,
string propertyName,
string val)
{
bool writtenToConfig = false;
if (configPropMgr != null && configNames != null && configNames.Contains(propertyName))
{
try
{
configPropMgr.Set2(propertyName, val);
writtenToConfig = true;
}
catch (Exception ex)
{
Debug.WriteLine($"SetPropertyValue config({propertyName}) failed: {ex.Message}");
}
}
if (!writtenToConfig && filePropMgr != null)
{
try
{
filePropMgr.Set2(propertyName, val);
}
catch (Exception ex)
{
Debug.WriteLine($"SetPropertyValue file({propertyName}) failed: {ex.Message}");
}
}
else if (!writtenToConfig && configPropMgr != null)
{
try
{
configPropMgr.Set2(propertyName, val);
}
catch (Exception ex)
{
Debug.WriteLine($"SetPropertyValue config-fallback({propertyName}) failed: {ex.Message}");
}
}
}
}
}