How to implement a robust plugin system in c# .NET? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How can I prevent the host application from crashing, due to any uncaught exceptions in the instances of a dynamically loaded external DLL?
Right now I have something like the following setup, please note that this is not the exact implementation:
internal class ExtensionManager
{
private static Type mExtension;
public static GetExtension() { return mExtension; }
ExtensionManager()
{
FileInfo[] fis = null;
fis = directory.GetFiles("*.dll");
foreach (FileInfo file in fis)
{
Assembly assembly = Assembly.LoadFrom(file.FullName);
if(some condition)
{
mExtension = Assembly.GetTypes().FirstOrDefault(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(BaseExtension)));
break;
}
}
}
}
internal class Room
{
public Room()
{
StartExtensions();
}
private BaseExtension CreateInstance(Type classType)
{
BaseExtension instance = null;
try
{
instance = (BaseExtension)Activator.CreateInstance(classType, new object[] { this });
}
catch (Exception error)
{
LogException("[Room][CreateInstance()]", error);
}
return instance;
}
private void StartExtensions()
{
if (!mExtensionInitialised)
{
Type classType = ExtensionManager.GetExtension();
if (classType == null) return;
if (classType.BaseType != typeof(BaseExtension)) return;
Task<BaseExtension> task = Task<BaseExtension>.Factory.StartNew(() => CreateInstance(classType), TaskCreationOptions.LongRunning);
try
{
task.Wait();
}
catch (Exception error)
{
//
}
}
}
}
class Program
{
static List<Room> mRooms = new List<Room>();
static void Main(string[] args)
{
for(int i = 0; i < 100; i++)
{
Room room = new Room();
mRooms.Add(room);
}
}
}
So I need to figure out if there is a uncaught exception, at run-time in the instance created by BaseExtension CreateInstance(Type classType).
P.S .NET Plugin framework is not an option, at the moment for me.

Related

JsonSerializer.Deserialize won't work in class C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I am trying everything I can but the object is not getting deserialized, I tried almost all the possible solutions to the problem but nothing is working, if someone can help that would be great.
please see below is the code snippet for the code
it always returns a null value to me.
using System;
using System.Text.Json;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
var a = "{\"enrollmentType\":\"draft\",\"emrName\":\"accuro\",\"emrVersion\":\"v1\",\"workflowType\":\"coordinator\"}";
var x = "{\"enrollmentType\":\"draft\",\"emrName\":\"accuro\",\"emrVersion\":\"v1\",\"workflowType\":\"coordinator\"}";
string json = #"{""id"":10,""name"":""Name"",""revisionDate"":1390293827000}";
var ed = JsonSerializer.Deserialize<EnrollmentExtension>(x);
//.Replace("'", "\"")
if (!string.IsNullOrWhiteSpace(ed.emrName))
{ }
}
}
public class EnrollmentExtension
{
#region MyRegion
private string _emrName;
private string _emrVersion;
private string _workflowType;
private string _enrollmentType; public bool IsDraft()
{
return (string.Compare(_enrollmentType, "draft", true) == 0);
}
#endregion
public string enrollmentType
{
get { return _enrollmentType; }
private set { _enrollmentType = value; }
}
public string workflowType
{
get { return _workflowType; }
private set { _workflowType = value; }
}
public string emrVersion
{
get { return _emrVersion; }
private set { _emrVersion = value; }
}
public string emrName
{
get { return _emrName; }
private set { _emrName = value; }
}
public void SetWorkflowType(string workFlowType)
{
_workflowType = workFlowType;
}
}
public class Test
{
public EnrollmentExtension myprop { get; set; }
}
}
you have a bug in your classes, all your setters are private, but should be public. all properties should be like this
public string enrollmentType
{
get { return _enrollmentType; }
set { _enrollmentType = value; }
}
or you can keep the private setters but create a constructor
public EnrollmentExtension(string enrollmentType, ... and so on, string workflowType)
{
_enrollmentType=enrollmentType;
_workflowType=workflowType;
... and so on
}

How can I modularize this C# code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've been working with .NET table adapters and data tables and I've been wrestling with how to modularize this code but I just can't "see" it.
Here's what I have but there's gotta be a way to combine into a one-liner that handles both cases.
class What_I_have
{
public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
{
try
{
TableAdapter.Fill(DataTable);
}
catch (SystemException sex)
{
GenericExcHandler(sex, DataTable.TableName);
}
}
public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
{
try
{
TableAdapter.Fill(DataTable);
}
catch (SystemException sex)
{
GenericExcHandler(sex, DataTable.TableName);
}
}
}
This is an idea of what I'm trying to do (The type 'HowToTypeThis' presents my quandary):
class What_Id_like
{
public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
{
IsolatedMethod(TableAdapter, DataTable);
}
public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
{
IsolatedMethod(TableAdapter, DataTable);
}
void IsolatedMethod(HowToTypeThis tabAdapter,
HowToTypeThis DataTable)
{
try
{
TableAdapter.Fill(DataTable);
}
catch (SystemException sex)
{
GenericExcHandler(sex, DataTable.TableName);
}
}
}
Add interfaces:
public interface ITableAdapter
{
Fill(IdataTable dt);
}
public interface IDataTable { }
Update your classes
public class TSNKF30_STRUCT_ELMNTTableAdapter : ITableAdapter {}
public class TSNKF30_STRUCT_ELMNTDataTable : IDataTable {}
Write an extension method
public static class TableAdapterExtensions
{
public static void FillWith(this ITableAdapter adapter, IDataTable dataTable)
{
try
{
adapter.Fill(dataTable);
}
catch(SystemException sex)
{
GenericExcHandler(sex, DataTable.TableName);
}
}
}
Then usage:
var ta = new TSNKF30_STRUCT_ELMNTTableAdapter();
var dt = new dsGrids.TSNKF30_STRUCT_ELMNTDataTable();
ta.FillWith(dt);

How to visually print a n-ary tree in c#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I made a basic n-ary tree in c#:
Tree:
public class Tree<T>
{
private Node<T> root;
public Tree()
{
root = null;
}
public Node<T> Root
{
get
{
return root;
}
set
{
root = value;
}
}
public T search (T data)
{
return (root != null) ? raiz.search(data) : default(T);
}
}
Node:
public class Node<T>
{
private T data;
private List<Node<T>> childs;
public Node(T data)
{
this.data = data;
this.childs = null;
}
public T Data
{
get
{
return data;
}
set
{
data = value;
}
}
public List<NodoArbol<T>> Childs
{
get
{
return childs;
}
set
{
childs = value;
}
}
public void addChild(Node node)
{
if (child == null)
{
childs = new List<Node<T>>();
}
childs.Add(node);
}
public T search(T data)
{
if (this.data.Equals(data))
{
return this.data;
}else
{
for (int i = 0; i < childs.Count; i++)
{
T aux = childs.ElementAt(i).search(data);
if (aux != null)
{
return aux;
}
}
return default(T);
}
}
}
I'd like a visual representation of the tree so that I can quickly test to see if the children and nodes are in the right place and test my traversals (pre order/in order/post order) something like this
If is enough for you to output it to console:
public void PrintTree(Node node, int indentSize, int currentLevel)
{
var currentNode = string.Format("{0}{1}", new string(" ",indentSize*currentLevel, node.Data);
Console.WriteLine(currentNode)
foreach(var child in node.Children)
{
PrintTree(child, indentSize, currentLevel+1);
}
}
And then call it like this
PrintTree(yourTreeInstance.Root,4,0);
You also can use Debug.WriteLine to output to debug console instead of main console

Type Comparison Performance: TryCast vs GetType [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What I'm wondering is what would be the best performance for determining what child class was actually passed into the function.
Here are the 3 different ways I am going between for what would be the best performance:
(ACHData, CCData, and DC Data all Inherit from BaseData)
public BaseProcessor GetProcessor(BaseData paymentInfo)
{
if (paymentInfo.GetType() == typeof(ACHData))
{
return GetACHProcessor((ACHData)paymentInfo);
}
else if (paymentInfo.GetType() == typeof(CCData))
{
return GetCCProcessor((CCData)paymentInfo);
}
else if (paymentInfo.GetType() == typeof(DCData))
{
return GetDCProcessor((DCData)paymentInfo);
}
else
{
throw new Exception(ExceptionMessage);
}
}
public BaseProcessor GetProcessor(BaseData paymentInfo)
{
if (paymentInfo is ACHData)
{
return GetACHProcessor((ACHData)paymentInfo);
}
else if (paymentInfo is CCData)
{
return GetCCProcessor((CCData)paymentInfo);
}
else if (paymentInfo is DCData)
{
return GetDCProcessor((DCData)paymentInfo);
}
else
{
throw new Exception(ExceptionMessage);
}
}
public BaseProcessor GetProcessor(BaseData paymentInfo)
{
var achInfo = paymentInfo as ACHData;
if (achInfo != null)
{
return GetACHProcessor(achInfo);
}
var ccInfo = paymentInfo as CCData;
if (ccInfo != null)
{
return GetCCProcessor(ccInfo);
}
var dcInfo = paymentInfo as DCData;
if (dcInfo != null)
{
return GetDCProcessor(dcInfo);
}
throw new Exception(ExceptionMessage);
}
I would re-think your entire design. Have your classes implement an interface that forces them to choose what to provide as a processor:
public interface IKnowWhatProcessorIWant {
IProcessor CreateProcessor();
}
public class ACHData : BaseData, IKnowWhatProcessorIWant {
public IProcessor CreateProcessor() {
return new GetACHProcessor(this);
}
}
Then your GetProcessor code becomes:
public BaseProcessor GetProcessor(IKnowWhatProcessorIWant obj) {
return obj.CreateProcessor();
}
...or, you could omit that method entirely then.

How to write interceptor for methods returning IEnumerable

I wrote simple interceptor (with Castle.DynamicProxy) to handle database connection life cycle. I.e. all services have Connection property which opens new one on first use. Connection is being closed automatically after each method call:
class CloseConnectionInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
finally
{
var hasConnection = invocation.InvocationTarget as IHasConnection;
if (hasConnection.IsConnectionOpen)
{
hasConnection.Connection.Dispose();
hasConnection.Connection = null;
}
}
}
}
interface IHasConnection
{
bool IsConnectionOpen { get; }
Connection Connection { get; set; }
}
It works well except for methods returning iterator:
[Test]
public void ConnectionClosedByProxy()
{
// arrange
var service = new MyService();
var proxy = new ProxyGenerator()
.CreateInterfaceProxyWithTarget<IMyService>(
service, new CloseConnectionInterceptor());
// act
proxy.GetList();
// assert: works!!!
Assert.IsFalse(service.IsConnectionOpen);
}
[Test]
public void IteratorLeavesOpenConnection()
{
// arrange
var service = new MyService();
var proxy = new ProxyGenerator()
.CreateInterfaceProxyWithTarget<IMyService>(
service, new CloseConnectionInterceptor());
// act
proxy.GetEnumerable().ToList();
// assert: bad, bad, bad!
Assert.IsTrue(service.IsConnectionOpen);
}
See full example here: https://gist.github.com/4087483
If there is "using (new Connection())" statement inside my GetEnumerable method then it works as expected - connection is being closed after last access to iterator. Is it possible to catch this moment in interceptor? Or should I proxy not only method but also resulting IEnumerable?
I put seed of the answer in my question :). Here is modified interceptor which proxies also resulting IEnumerable:
class CloseConnectionInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Type genericType = invocation.Method.ReturnType.IsGenericType
? invocation.Method.ReturnType.GetGenericTypeDefinition()
: null;
if (genericType == typeof(IEnumerable<>))
{
invocation.Proceed();
var method = GetType()
.GetMethod("HandleIteratorInvocation")
.MakeGenericMethod(
invocation.Method.ReturnType.GetGenericArguments()[0]);
invocation.ReturnValue = method.Invoke(
null,
new[] { invocation.InvocationTarget, invocation.ReturnValue });
}
else
{
HandleNonIteratorInvocation(invocation);
}
}
public static IEnumerable<T> HandleIteratorInvocation<T>(
IHasConnection hasConnection, IEnumerable enumerable)
{
try
{
foreach (var element in enumerable)
yield return (T)element;
}
finally
{
CloseOpenConnection(hasConnection);
}
}
private static void HandleNonIteratorInvocation(IInvocation invocation)
{
try
{
invocation.Proceed();
}
finally
{
CloseOpenConnection(invocation.InvocationTarget as IHasConnection);
}
}
private static void CloseOpenConnection(IHasConnection hasConnection)
{
if (hasConnection.IsConnectionOpen)
{
hasConnection.Connection.Dispose();
hasConnection.Connection = null;
}
}
}

Categories