├── .gitignore
├── .vscode
├── launch.json
└── tasks.json
├── LICENSE
├── README.md
└── src
├── AppDomainAlternative.Tests
├── AppDomainAlternative.Tests.csproj
├── Ipc
│ ├── Channels
│ │ ├── ChannelListenerTest.cs
│ │ ├── ChannelStartTest.cs
│ │ └── MockChannel.cs
│ ├── ConnectionTests.cs
│ └── ReadWriteBufferTests.cs
├── Proxy
│ ├── ConstructorsTests.cs
│ ├── MethodsWithArgumentsTests.cs
│ ├── MockInterceptor.cs
│ ├── MockSerializer.cs
│ ├── PropertiesTests.cs
│ ├── ProxyOptionsTests.cs
│ ├── ReturnValueMethodsTests.cs
│ └── VoidMethodsTests.cs
└── Serializer
│ ├── ArrayTests.cs
│ ├── DateTimeTests.cs
│ ├── EnumTests.cs
│ ├── GuidTests.cs
│ ├── MockResolveProxyIds.cs
│ ├── NullTests.cs
│ ├── PrimitiveTypesTests.cs
│ ├── ProxyInstanceTests.cs
│ ├── SerializableTests.cs
│ ├── StringTests.cs
│ ├── TimeSpanTests.cs
│ └── TypeTests.cs
├── AppDomainAlternative.VsCode.sln
├── AppDomainAlternative.sln
├── AppDomainAlternative
├── AppDomainAlternative.csproj
├── ChildDomain.cs
├── CurrentDomain.cs
├── DomainConfiguration.cs
├── Domains.cs
├── Extensions
│ ├── ChannelListensExtensions.cs
│ └── ChannelStartExtensions.cs
├── Ipc
│ ├── Channel.cs
│ ├── Connection.cs
│ └── ReadWriteBuffer.cs
├── Properties
│ └── AssemblyInfo.cs
├── Proxy
│ ├── DefaultProxyFactory.cs
│ ├── IGenerateProxies.cs
│ ├── IInterceptor.cs
│ └── ProxyAttribute.cs
└── Serializer
│ ├── Default
│ ├── ArrayReaderWriter.cs
│ ├── DateTimeReaderWrite.cs
│ ├── DefaultSerializer.cs
│ ├── EnumReaderWriter.cs
│ ├── GuidReaderWriter.cs
│ ├── ObjectReaderWriter.cs
│ ├── SerializableReaderWriter.cs
│ ├── TimeSpanReaderWriter.cs
│ └── TypeReaderWriter.cs
│ ├── IAmASerializer.cs
│ └── IResolveProxyIds.cs
├── ClientApp
├── ClientApp.csproj
└── ClientProgram.cs
├── Common
├── ChatRoom.cs
└── Common.csproj
├── HostApp
├── HostApp.csproj
└── HostProgram.cs
└── VsDebugger
├── Program.cs
└── VsDebugger.csproj
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "Debug HostApp",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | "program": "${workspaceFolder}/src/HostApp/bin/Debug/netcoreapp2.0/HostApp.dll",
13 | "args": [],
14 | "cwd": "${workspaceFolder}",
15 | "stopAtEntry": false,
16 | "console": "externalTerminal"
17 | }
18 | ]
19 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | // See https://go.microsoft.com/fwlink/?LinkId=733558
3 | // for the documentation about the tasks.json format
4 | "version": "2.0.0",
5 | "tasks": [
6 | {
7 | "label": "build",
8 | "command": "dotnet",
9 | "type": "shell",
10 | "args": [
11 | "build",
12 | "src/AppDomainAlternative.VsCode.sln",
13 | "/property:GenerateFullPaths=true",
14 | "/consoleloggerparameters:NoSummary"
15 | ],
16 | "group": "build",
17 | "presentation": {
18 | "reveal": "silent"
19 | },
20 | "problemMatcher": "$msCompile"
21 | }
22 | ]
23 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Cy Scott
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AppDomainAlternative
2 |
3 | The [AppDomain](https://docs.microsoft.com/en-us/dotnet/api/system.appdomain) SandBox features were intentionally left out of .Net Core for several [technical and security reasons](https://devblogs.microsoft.com/dotnet/porting-to-net-core/). Microsoft's recommendation for .Net Core SandBoxing is to use [process](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process) isolation instead of AppDomain isolation and to use [inter-process communication (IPC)](https://docs.microsoft.com/en-us/windows/desktop/ipc/interprocess-communications) classes (ie pipes, sockets, etc.) instead of remoting classes like the [MarshalByRefObject](https://docs.microsoft.com/en-us/dotnet/api/system.marshalbyrefobject) class for data communication between those processes. AppDomainAlternative is a .Net Core friendly alternative to using AppDomains as SandBoxes and uses the recommended solution of process isolation and supports object remoting over [Anonymous Pipes](https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication).
4 |
5 | ### Important Differences between AppDomains and Processes
6 |
7 | 1) All AppDomains exist under one process so unhandled exceptions from any AppDomain terminates the entire process and all AppDomains within it. However, processes do not work like that and if one process has an unhandled exception only that process terminates and not the parent or child processes. Although it is possible to replicate this feature between processes, AppDomainAlternative does not replicate this feature because it is not a desired feature for proper SandBoxing.
8 |
9 | 2) AppDomains do not have a “main” method (like processes) that is executed when the AppDomain is created. A process’s “main” method always executes immediately when the process is created and is intrinsic to how processes work. It is possible to support this feature by creating a generic launcher assembly that executes its “main” method when the process starts and waits for instructions from the parent process to do work like AppDomains do. However, this is a complex feature that will be developed in a later release of AppDomainAlternative.
10 |
11 | 3) AppDomains can load [Dynamic Assemblies](https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/emitting-dynamic-methods-and-assemblies) generated during run time by another AppDomain. Dynamic assembly run time generation via Emit is still supported in .Net Core but the [assembly serialization features are not](https://github.com/dotnet/corefx/issues/4491#issuecomment-189756092). Since those assemblies cannot be serialized, they cannot be passed from one process to another for execution. [ILPack](https://github.com/Lokad/ILPack) looks like a good choice to fill in the feature gap, but it has not been released yet.
12 |
13 | ### Remoting Alternative
14 |
15 | Remoting was an important feature for AppDomains and [is no longer supported](https://docs.microsoft.com/en-us/dotnet/core/porting/net-framework-tech-unavailable#remoting) in .Net Core. Which means classes that inherit from [MarshalByRefObject](https://docs.microsoft.com/en-us/dotnet/api/system.marshalbyrefobject) can no longer be used for remoting from one domain to another. Classes that inherit from MarshalByRefObject work by creating a proxy instance on a remote domain and all calls to that proxy instance are serialized and passed to the original domain for execution. Here is an example class that can be proxied across the domain barrier:
16 |
17 | ```
18 | public class ChatRoom : MarshalByRefObject
19 | {
20 | public void SendMessage(string message)
21 | {
22 | Console.WriteLine(message);
23 | }
24 | }
25 | ```
26 |
27 | AppDomainAlternative takes a similar approach to remoting across the process barrier. However, there is no need to inherit from a special class. Here is an example class that can be proxied across the process barrier:
28 |
29 | ```
30 | public class ChatRoom
31 | {
32 | public virtual void SendMessage(string message)
33 | {
34 | Console.WriteLine(message);
35 | }
36 | }
37 | ```
38 |
39 | The difference is the methods and properties need to be marked as [virtual](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual). This allows AppDomainAlternative to create a proxy instance of the class by overriding those methods and properties. The override of those methods and properties handle the remoting responsibilities, include exceptions thrown by the remote call.
40 |
41 | #### AppDomain Alternative
42 |
43 | Creating a child AppDomain is similar to starting a child process with AppDomainAlternative. Below is an example on how to create a child AppDomain and using the `ChatRoom` class for remoting:
44 |
45 | ```
46 | var domain = AppDomain.CreateDomain("Some Name");
47 | var chatRoom = (ChatRoom)domain.CreateInstanceAndUnwrap(typeof(ChatRoom).Assembly.FullName, typeof(ChatRoom).FullName);
48 | chatRoom.SendMessage("Hello World");
49 | ```
50 |
51 | That example creates an instance on the child domain and returns a proxied instance of that class to the parent domain for remoting. Below is an example of how to do the same thing with AppDomainAlternative:
52 |
53 | ```
54 | var domain = Domains.Current.AddChildDomain(new ProcessStartInfo("dotnet", "path to .Net Core assembly"));
55 | var chatRoom = (ChatRoom)await childDomain.Channels.CreateInstance(typeof(ChatRoom).GetConstructors().First(), hostInstance: false).ConfigureAwait(false);
56 | chatRoom.SendMessage("Hello World");
57 | ```
58 |
59 | You may notice that AppDomainAlternative does offer additional features that are not included in remoting for AppDomains. One of those features is it supports constructors when creating remote objects.
60 |
--------------------------------------------------------------------------------
/src/AppDomainAlternative.Tests/AppDomainAlternative.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.0
5 |
6 | false
7 |
8 | AppDomainAlternative
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/AppDomainAlternative.Tests/Ipc/Channels/ChannelListenerTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Diagnostics;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 | using AppDomainAlternative.Extensions;
9 | using AppDomainAlternative.Proxy;
10 | using NUnit.Framework;
11 |
12 | // ReSharper disable AccessToDisposedClosure
13 |
14 | namespace AppDomainAlternative.Ipc.Channels
15 | {
16 | [TestFixture]
17 | public class ChannelListenerTest
18 | {
19 | public const string ArgumentNullMsg = "The GUID value was null.";
20 |
21 | public class DummyClass
22 | {
23 | public ConcurrentBag Values { get; } = new ConcurrentBag();
24 | public virtual Task SetValue(Guid? value)
25 | {
26 | if (value == null)
27 | {
28 | throw new ArgumentNullException(ArgumentNullMsg);
29 | }
30 |
31 | Values.Add(value.Value);
32 |
33 | return Task.FromResult(value.ToString());
34 | }
35 | }
36 |
37 | internal class MockConnectionLayer : MockConnection
38 | {
39 | private ManualResetEventSlim signal;
40 | private readonly ConcurrentQueue<(long id, Stream data)> queue = new ConcurrentQueue<(long id, Stream data)>();
41 | private int disposed;
42 |
43 | public async void Start(MockChannel channel, CancellationTokenSource cancel)
44 | {
45 | await Task.Yield();
46 |
47 | signal = new ManualResetEventSlim(false);
48 |
49 | while (!cancel.IsCancellationRequested && disposed == 0)
50 | {
51 | signal.Wait(cancel.Token);
52 |
53 | while (queue.TryDequeue(out var request) && !cancel.IsCancellationRequested && disposed == 0)
54 | {
55 | await channel.Buffer.Fill(request.data, (int)request.data.Length, cancel.Token).ConfigureAwait(false);
56 | }
57 | }
58 |
59 | signal.Dispose();
60 | }
61 | public override void Terminate(IInternalChannel channel)
62 | {
63 | Dispose();
64 | base.Terminate(channel);
65 | }
66 | public override void Write(long channelId, Stream stream)
67 | {
68 | queue.Enqueue((channelId, stream));
69 | signal.Set();
70 | base.Write(channelId, stream);
71 | }
72 | public override void Dispose()
73 | {
74 | Interlocked.CompareExchange(ref disposed, 1, 0);
75 | signal.Set();
76 | }
77 | }
78 |
79 | #region Stress Test
80 |
81 | public async void ThreadTest(
82 | CancellationToken cancel,
83 | DummyClass remoteInstance,
84 | ConcurrentBag values,
85 | TaskCompletionSource onFinish)
86 | {
87 | try
88 | {
89 | await Task.Yield();
90 |
91 | var cancelTask = new TaskCompletionSource();
92 | var ids = Enumerable.Range(0, 1000).Select(_ => Guid.NewGuid()).ToArray();
93 | var rnd = new Random();
94 |
95 | cancel.Register(() => cancelTask.TrySetResult(true));
96 |
97 | foreach (var value in ids.TakeWhile(_ => !cancel.IsCancellationRequested))
98 | {
99 | await Task.Yield();
100 |
101 | Thread.SpinWait(rnd.Next(1, 1000));
102 |
103 | if (cancel.IsCancellationRequested)
104 | {
105 | break;
106 | }
107 |
108 | values.Add(value);
109 |
110 | var task = remoteInstance.SetValue(value);
111 |
112 | await Task.WhenAny(cancelTask.Task, task).ConfigureAwait(false);
113 | }
114 |
115 | onFinish.TrySetResult(true);
116 | }
117 | catch (Exception error)
118 | {
119 | onFinish.TrySetException(error);
120 | }
121 | }
122 |
123 | [Test]
124 | public async Task StressTest()
125 | {
126 | var proxyGenerator = new DefaultProxyFactory();
127 |
128 | using (var cancel = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(5)))
129 | using (var localConnectionLayer = new MockConnectionLayer())
130 | using (var remoteConnectionLayer = new MockConnectionLayer())
131 | using (var localChannel = new MockChannel(localConnectionLayer))
132 | using (var remoteChannel = new MockChannel(remoteConnectionLayer))
133 | {
134 | localConnectionLayer.Start(remoteChannel, cancel);
135 | remoteConnectionLayer.Start(localChannel, cancel);
136 |
137 | var localStart = localChannel.LocalStart(cancel, proxyGenerator,
138 | typeof(DummyClass).GetConstructors().First(),
139 | true);
140 | var remoteStart = remoteChannel.RemoteStart(cancel, proxyGenerator);
141 |
142 | await Task.WhenAll(localStart, remoteStart).ConfigureAwait(false);
143 |
144 | var localInstance = (DummyClass)localStart.Result;
145 | var remoteInstance = (DummyClass)remoteStart.Result.instance;
146 |
147 | localChannel.Instance = localInstance;
148 | localChannel.IsHost = true;
149 | localChannel.StartListening(cancel, localChannel.RemoteRequests);
150 | remoteChannel.Instance = remoteInstance;
151 | remoteChannel.IsHost = false;
152 | remoteChannel.StartListening(cancel, remoteChannel.RemoteRequests);
153 |
154 | //stress test
155 | const int threadCount = 10;
156 | var tasks = new TaskCompletionSource[threadCount];
157 | var values = new ConcurrentBag();
158 | for (var index = 0; index < threadCount; index++)
159 | {
160 | ThreadTest(cancel.Token, remoteInstance, values, tasks[index] = new TaskCompletionSource());
161 | }
162 | await Task.WhenAll(tasks.Select(item => item.Task)).ConfigureAwait(false);
163 |
164 | //validate state
165 | Assert.AreEqual(values.Count, localInstance.Values.Count);
166 | Assert.AreEqual(values.Count, values.Count(id => localInstance.Values.Contains(id)));
167 | }
168 | }
169 |
170 | #endregion
171 |
172 | [Test]
173 | public async Task IntegrationTestExceptionCall()
174 | {
175 | var proxyGenerator = new DefaultProxyFactory();
176 |
177 | using (var cancel = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(1)))
178 | using (var localConnectionLayer = new MockConnectionLayer())
179 | using (var remoteConnectionLayer = new MockConnectionLayer())
180 | using (var localChannel = new MockChannel(localConnectionLayer))
181 | using (var remoteChannel = new MockChannel(remoteConnectionLayer))
182 | {
183 | localConnectionLayer.Start(remoteChannel, cancel);
184 | remoteConnectionLayer.Start(localChannel, cancel);
185 |
186 | var localStart = localChannel.LocalStart(cancel, proxyGenerator,
187 | typeof(DummyClass).GetConstructors().First(),
188 | true);
189 | var remoteStart = remoteChannel.RemoteStart(cancel, proxyGenerator);
190 |
191 | await Task.WhenAll(localStart, remoteStart).ConfigureAwait(false);
192 |
193 | var localInstance = (DummyClass)localStart.Result;
194 | var remoteInstance = (DummyClass)remoteStart.Result.instance;
195 |
196 | localChannel.Instance = localInstance;
197 | localChannel.IsHost = true;
198 | localChannel.StartListening(cancel, localChannel.RemoteRequests);
199 | remoteChannel.Instance = remoteInstance;
200 | remoteChannel.IsHost = false;
201 | remoteChannel.StartListening(cancel, remoteChannel.RemoteRequests);
202 |
203 | //test exception case
204 | Assert.ThrowsAsync(() => remoteInstance.SetValue(null), ArgumentNullMsg);
205 | Assert.AreEqual(0, localInstance.Values.Count);
206 | }
207 | }
208 |
209 | [Test]
210 | public async Task IntegrationTestExceptionFreeCall()
211 | {
212 | var proxyGenerator = new DefaultProxyFactory();
213 |
214 | using (var cancel = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(1)))
215 | using (var localConnectionLayer = new MockConnectionLayer())
216 | using (var remoteConnectionLayer = new MockConnectionLayer())
217 | using (var localChannel = new MockChannel(localConnectionLayer))
218 | using (var remoteChannel = new MockChannel(remoteConnectionLayer))
219 | {
220 | localConnectionLayer.Start(remoteChannel, cancel);
221 | remoteConnectionLayer.Start(localChannel, cancel);
222 |
223 | var localStart = localChannel.LocalStart(cancel, proxyGenerator,
224 | typeof(DummyClass).GetConstructors().First(),
225 | true);
226 | var remoteStart = remoteChannel.RemoteStart(cancel, proxyGenerator);
227 |
228 | await Task.WhenAll(localStart, remoteStart).ConfigureAwait(false);
229 |
230 | var localInstance = (DummyClass)localStart.Result;
231 | var remoteInstance = (DummyClass)remoteStart.Result.instance;
232 |
233 | localChannel.Instance = localInstance;
234 | localChannel.IsHost = true;
235 | localChannel.StartListening(cancel, localChannel.RemoteRequests);
236 | remoteChannel.Instance = remoteInstance;
237 | remoteChannel.IsHost = false;
238 | remoteChannel.StartListening(cancel, remoteChannel.RemoteRequests);
239 |
240 | //test exception free case
241 | var value = Guid.NewGuid();
242 | await remoteInstance.SetValue(value).ConfigureAwait(false);
243 | Assert.AreEqual(1, localInstance.Values.Count);
244 | Assert.AreEqual(value, localInstance.Values.First());
245 |
246 | localInstance.Values.Clear();
247 | }
248 | }
249 | }
250 | }
251 |
--------------------------------------------------------------------------------
/src/AppDomainAlternative.Tests/Ipc/Channels/ChannelStartTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 | using AppDomainAlternative.Extensions;
8 | using AppDomainAlternative.Proxy;
9 | using NUnit.Framework;
10 |
11 | // ReSharper disable AccessToModifiedClosure
12 |
13 | namespace AppDomainAlternative.Ipc.Channels
14 | {
15 | [TestFixture]
16 | public class ChannelStartTest
17 | {
18 | private static async Task test(bool hostInstance, params object[] arguments)
19 | {
20 | var proxyGenerator = new DefaultProxyFactory();
21 |
22 | using (var cancel = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.FromDays(1) : TimeSpan.FromMinutes(1)))
23 | using (var localChannel = new MockChannel())
24 | using (var remoteChannel = new MockChannel())
25 | {
26 | var writeTask = new TaskCompletionSource<(long id, Stream data)>();
27 | cancel.Token.Register(() => writeTask.TrySetCanceled());
28 | localChannel.MockConnection.Writes += (id, data) => writeTask.TrySetResult((id, data));
29 | remoteChannel.MockConnection.Writes += (id, data) => writeTask.TrySetResult((id, data));
30 |
31 | //make a local start on another thread
32 | var localStart = localChannel.LocalStart(cancel, proxyGenerator,
33 | typeof(DummyClass).GetConstructors()
34 | .FirstOrDefault(ctor => ctor.GetParameters().Length == arguments.Length) ??
35 | typeof(DummyClass).GetConstructors()
36 | .First(ctor => ctor.GetParameters().Length != arguments.Length),
37 | hostInstance,
38 | arguments);
39 | if (localStart.IsCompleted)
40 | {
41 | //this usually means an error happened so lets throw it now
42 | await localStart.ConfigureAwait(false);
43 | }
44 |
45 | //wait for local start to start the waiting step for a response
46 | await writeTask.Task.ConfigureAwait(false);
47 |
48 | //read the write request from the local channel
49 | var writeRequest = writeTask.Task.Result;
50 | Assert.AreEqual(localChannel.Id, writeRequest.id);
51 | Assert.IsNotNull(writeRequest.data);
52 | writeTask = new TaskCompletionSource<(long id, Stream data)>();
53 |
54 | //send the request to the remote channel
55 | await remoteChannel.Buffer.Fill(writeRequest.data, (int)writeRequest.data.Length, cancel.Token).ConfigureAwait(false);
56 |
57 | var remoteStart = await remoteChannel.RemoteStart(cancel, proxyGenerator).ConfigureAwait(false);
58 | await writeTask.Task.ConfigureAwait(false);
59 |
60 | //read the write request from the remote channel
61 | writeRequest = writeTask.Task.Result;
62 | Assert.AreEqual(remoteChannel.Id, writeRequest.id);
63 | Assert.IsNotNull(writeRequest.data);
64 |
65 | //send the request to the local channel
66 | await localChannel.Buffer.Fill(writeRequest.data, (int)writeRequest.data.Length, cancel.Token).ConfigureAwait(false);
67 |
68 | //wait for all start tasks to finish
69 | await localStart.ConfigureAwait(false);
70 |
71 | //validate local instance
72 | var localInstance = localStart.Result as DummyClass;
73 | Assert.IsNotNull(localInstance);
74 |
75 | Assert.AreEqual(localInstance.Arg1, arguments.Skip(0).FirstOrDefault());
76 | Assert.AreEqual(localInstance.Arg2, arguments.Skip(1).FirstOrDefault());
77 | Assert.AreEqual(localInstance.Arg3, arguments.Skip(2).FirstOrDefault());
78 |
79 | //validate remote instance
80 | var remoteInstance = remoteStart.instance as DummyClass;
81 | Assert.IsNotNull(remoteInstance);
82 |
83 | Assert.AreEqual(remoteInstance.Arg1, arguments.Skip(0).FirstOrDefault());
84 | Assert.AreEqual(remoteInstance.Arg2, arguments.Skip(1).FirstOrDefault());
85 | Assert.AreEqual(remoteInstance.Arg3, arguments.Skip(2).FirstOrDefault());
86 |
87 | //validate proxy was generated correctly
88 | if (hostInstance)
89 | {
90 | Assert.IsFalse(remoteStart.isHost);
91 |
92 | Assert.AreEqual(typeof(DummyClass), localInstance.GetType());
93 | Assert.AreNotEqual(typeof(DummyClass), remoteInstance.GetType());
94 | }
95 | else
96 | {
97 | Assert.IsTrue(remoteStart.isHost);
98 |
99 | Assert.AreNotEqual(typeof(DummyClass), localInstance.GetType());
100 | Assert.AreEqual(typeof(DummyClass), remoteInstance.GetType());
101 | }
102 | }
103 | }
104 |
105 | public class DummyClass
106 | {
107 | public DummyClass()
108 | {
109 | }
110 | public DummyClass(Guid arg1) => Arg1 = arg1;
111 | public DummyClass(Guid arg1, DateTime arg2)
112 | {
113 | Arg1 = arg1;
114 | Arg2 = arg2;
115 | }
116 | public DummyClass(Guid arg1, DateTime arg2, int arg3)
117 | {
118 | Arg1 = arg1;
119 | Arg2 = arg2;
120 | Arg3 = arg3;
121 | }
122 |
123 | public readonly Guid? Arg1;
124 | public readonly DateTime? Arg2;
125 | public readonly int? Arg3;
126 | public virtual void EnabledMethod() => throw new NotSupportedException();
127 | }
128 |
129 | [Test]
130 | public async Task IntegrationTest()
131 | {
132 | await test(true,
133 | Guid.NewGuid()).ConfigureAwait(false);
134 |
135 | await test(true,
136 | Guid.NewGuid(),
137 | DateTime.UtcNow).ConfigureAwait(false);
138 |
139 | await test(true,
140 | Guid.NewGuid(),
141 | DateTime.UtcNow,
142 | 13).ConfigureAwait(false);
143 |
144 | await test(false,
145 | Guid.NewGuid()).ConfigureAwait(false);
146 |
147 | await test(false,
148 | Guid.NewGuid(),
149 | DateTime.UtcNow).ConfigureAwait(false);
150 |
151 | await test(false,
152 | Guid.NewGuid(),
153 | DateTime.UtcNow,
154 | 17).ConfigureAwait(false);
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/src/AppDomainAlternative.Tests/Ipc/Channels/MockChannel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Concurrent;
4 | using System.Collections.Generic;
5 | using System.IO;
6 | using System.Reflection;
7 | using System.Text;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 | using AppDomainAlternative.Extensions;
11 | using AppDomainAlternative.Proxy;
12 | using AppDomainAlternative.Serializer;
13 | using AppDomainAlternative.Serializer.Default;
14 |
15 | namespace AppDomainAlternative.Ipc.Channels
16 | {
17 | internal class MockChannel : IInternalChannel
18 | {
19 | public MockChannel(MockConnection connection = null)
20 | {
21 | MockConnection = connection ?? new MockConnection();
22 | Buffer = new ReadWriteBuffer(Id = 7);
23 | Reader = new BinaryReader(Buffer, Encoding.UTF8);
24 | }
25 |
26 | public BinaryReader Reader { get; }
27 | public ConcurrentDictionary> RemoteRequests { get; } = new ConcurrentDictionary>();
28 | public IAmASerializer Serializer { get; } = new DefaultSerializer();
29 | public IConnection Connection => MockConnection;
30 | public MockConnection MockConnection { get; }
31 | public ReadWriteBuffer Buffer { get; }
32 | public Task RemoteInvoke(bool fireAndForget, string methodName, params Tuple[] args) =>
33 | this.RemoteInvoke(RemoteRequests, () => Interlocked.Increment(ref RequestCounter), fireAndForget, methodName, args);
34 | public Task LocalStart(IGenerateProxies proxyGenerator, ConstructorInfo ctor, bool hostInstance, params object[] arguments) => throw new NotSupportedException();
35 | public Task LocalStart(T instance)
36 | where T : class, new() => throw new NotSupportedException();
37 | public Task RemoteStart(IGenerateProxies proxyGenerator) => throw new NotSupportedException();
38 | public bool IsDisposed { get; } = false;
39 | public bool IsHost { get; set; }
40 | public int RequestCounter;
41 | public long Id { get; }
42 | public object Instance { get; set; }
43 | public void Dispose()
44 | {
45 | }
46 | }
47 |
48 | internal class MockConnection : IConnection
49 | {
50 | IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException();
51 | IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException();
52 | Task