Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace BotSharp.Abstraction.Utilities
{
public static class ObjectExtensions
{
private static readonly JsonSerializerOptions DefaultOptions = new()
{
ReferenceHandler = ReferenceHandler.IgnoreCycles
};
private static JsonSerializerSettings DefaultSettings = new()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

public static T DeepClone<T>(this T obj) where T : class
{
if (obj == null) return null;

try
{
var json = JsonSerializer.Serialize(obj, DefaultOptions);
return JsonSerializer.Deserialize<T>(json, DefaultOptions);
}
catch(Exception ex)
{
Console.WriteLine($"DeepClone Error:{ex}");
return DeepCloneWithNewtonsoft(obj);
}
}

private static T DeepCloneWithNewtonsoft<T>(this T obj) where T : class
{
if (obj == null) return null;

try
{
var json = JsonConvert.SerializeObject(obj, DefaultSettings);
return JsonConvert.DeserializeObject<T>(json, DefaultSettings);
}
catch(Exception ex)
{
Console.WriteLine($"DeepClone Error:{ex}");
return obj;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public async Task<Agent> LoadAgent(string id, bool loadUtility = true)

HookEmitter.Emit<IAgentHook>(_services, hook => hook.OnAgentLoading(ref id), id);

var agent = await GetAgent(id);
var agent = (await GetAgent(id)).DeepClone();
if (agent == null) return null;

agent.TemplateDict = [];
Expand Down
Loading