Skip to content

Commit

Permalink
Merge pull request #52 from IntelliTect/fix-v8-listing-runner
Browse files Browse the repository at this point in the history
Fix v8 listing runner
  • Loading branch information
COsborn2 authored Jun 25, 2019
2 parents 1338448 + a5663c4 commit 3f3f09b
Show file tree
Hide file tree
Showing 8 changed files with 727 additions and 1,350 deletions.
616 changes: 0 additions & 616 deletions Build.sln

This file was deleted.

1,264 changes: 616 additions & 648 deletions EssentialCSharp.sln

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@ Ensure one of the following frameworks is installed at the latest version.

Open a console and change the working directory to the desired project location.
```
$ git clone --recursive https://github.com/IntelliTect/EssentialCSharp.git
$ git clone https://github.com/IntelliTect/EssentialCSharp.git
$ cd ./EssentialCSharp/
```

**Note:** `--recursive` is used to ensure that the submodules, specifically `IntelliTect.TestTools` (which includes a testing framework for .NET console applications).

The source code associated with the `master` is the most recently published edition of the book and this is the default branch following the clone command. However, you can switch to a different branch, v6.0 for example, with the command:
The source code is the most recently published edition of the book and this is the default branch following the clone command. However, you can switch to a different branch, v6.0 for example, with the command:
```
$ git checkout v6.0
```
Expand All @@ -41,10 +38,13 @@ $ dotnet build EssentialCSharp.sln

Navigate to an individual project in the /EssentialCSharp/src/(project)/ directory and run the code. The example below is for Chapter01 with the user entering _1.1_ to execute the listing number.

To run a listing you must run the the project that contains it. For example, to run Listing 1.1 you must navigate to Chapter01 in the
_Solution Explorer_ and set Chapter01 as the startup project. In Rider this can be done by locating the desired project in the _Explorer_ tab, right clicking on the project and clicking _run_.

```
$ cd ./src/Chapter01/
$ dotnet run
Enter the listing number to execute (e.g. For Listing 18.1 enter "18.1"): 1.1
Enter the listing number to execute (e.g. For Listing 1.1 enter "1.1"): 1.1
____________________________
Expand Down
1 change: 0 additions & 1 deletion src/Chapter10.Tests/Chapter10.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
<Import Project="..\Versioning.targets" />
<Import Project="..\ChapterTests.targets" />
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0-preview-20190606-02" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0-beta4" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0-beta4" />
Expand Down
38 changes: 19 additions & 19 deletions src/Chapter11.Tests/Chapter11.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<ProductName>Chapter11.Tests</ProductName>
<Nullable>enable</Nullable>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<Import Project="..\Versioning.targets" />
<Import Project="..\ChapterTests.targets" />
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0-preview-20190606-02" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0-beta4" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0-beta4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Chapter11\Chapter11.csproj" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<ProductName>Chapter11.Tests</ProductName>
<Nullable>enable</Nullable>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<Import Project="..\Versioning.targets" />
<Import Project="..\ChapterTests.targets" />
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0-preview-20190606-02" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0-beta4" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0-beta4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Chapter11\Chapter11.csproj" />
</ItemGroup>
</Project>
34 changes: 17 additions & 17 deletions src/Chapter11/Chapter11.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<ProductName>Chapter11</ProductName>
<StartupObject>AddisonWesley.Michaelis.EssentialCSharp.Shared.Program</StartupObject>
<Nullable>enable</Nullable>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<Import Project="..\Versioning.targets" />
<ItemGroup>
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
<ProjectReference Include="..\Chapter07\Chapter07.csproj" />
<Compile Include="..\Shared\Program.cs">
<Link>Program.cs</Link>
</Compile>
</ItemGroup>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<ProductName>Chapter11</ProductName>
<StartupObject>AddisonWesley.Michaelis.EssentialCSharp.Shared.Program</StartupObject>
<Nullable>enable</Nullable>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<Import Project="..\Versioning.targets" />
<ItemGroup>
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
<ProjectReference Include="..\Chapter07\Chapter07.csproj" />
<Compile Include="..\Shared\Program.cs">
<Link>Program.cs</Link>
</Compile>
</ItemGroup>
</Project>
4 changes: 3 additions & 1 deletion src/ChapterTests.targets
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<Project>
<ItemGroup>
<PackageReference Include="IntelliTect.TestTools.Console" Version="0.6.0-*" Condition="!Exists('..\submodules\TestTools\IntelliTect.TestTools.Console\IntelliTect.TestTools.Console.csproj')" />
<!--
<ProjectReference Include="..\submodules\TestTools\IntelliTect.TestTools.Console\IntelliTect.TestTools.Console.csproj" Condition="Exists('..\submodules\TestTools\IntelliTect.TestTools.Console\IntelliTect.TestTools.Console.csproj')" />
-->
<PackageReference Include="IntelliTect.TestTools.Console" Version="0.6.0-*" />
</ItemGroup>
</Project>
108 changes: 66 additions & 42 deletions src/Shared/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#nullable enable
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
using System.Threading;

namespace AddisonWesley.Michaelis.EssentialCSharp.Shared
Expand All @@ -14,9 +14,15 @@ public static void Main(string[] args)
{
string input;
IEnumerable<string> stringArguments = new string[0];
var assembly = Assembly.GetEntryAssembly();

string regexMatch = Regex.Match(assembly.GetName().Name, "\\d{1,2}").Value;

int chapterNumber = int.Parse(regexMatch);
if (args.Length == 0)
{
Console.Write("Enter the listing number to execute (e.g. For Listing 18.1 enter \"18.1\"): ");
Console.Write(
$"Enter the listing number to execute (e.g. For Listing {chapterNumber}.1 enter \"{chapterNumber}.1\"): ");
input = Console.ReadLine();
}
else
Expand All @@ -32,58 +38,66 @@ public static void Main(string[] args)

try
{
System.Diagnostics.Debugger.Break();
string chapterName = "";
string listing = ParseListingName(input, out chapterName);
input = ParseListingName(input);

var assembly = Assembly.Load(new AssemblyName(chapterName)); // Throws System.IO.FileNotFound exception if assembly does not exist.

Type? target = assembly.GetTypes().FirstOrDefault(type => type.FullName.Contains(listing + "."));
if(target == null)
{
throw new InvalidOperationException($"There is no listing '{input}'.");
Type? target = assembly.GetTypes().FirstOrDefault(type => type.FullName.Contains(input));
if (target == null)
{
throw new InvalidOperationException($"There is no listing '{input}'.");
}
var method = (MethodInfo)target.GetMember("Main").First();

object[]? arguments;
MethodInfo method = target.GetMethods().First();

string[]? arguments;
if (!method.GetParameters().Any())
{
arguments = null; // If there are no parameters to the method, the arguments parameter should be null.
arguments =
null; // If there are no parameters to the method, the arguments parameter should be null.
}
else
{
if (stringArguments.Count()==0)
if (stringArguments.Count() == 0)
{
arguments = new object[] { GetArguments() };
arguments = GetArguments();
}
else
{
arguments = new object[] { stringArguments.ToArray() };
arguments = stringArguments.ToArray();
}
}

if (method.GetCustomAttributes(typeof(STAThreadAttribute), false).Any())
{
Thread thread = new Thread(() => method.Invoke(null, arguments));
//thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
Thread thread = new Thread(() =>
{
object result = method.Invoke(null, arguments);
if (!(method.ReturnType == typeof(void)))
{
Console.WriteLine($"Result: {result}");
}
});
}
else
{
method.Invoke(null, arguments);
var result = method.Invoke(null, arguments);

if (!(method.ReturnType == typeof(void)))
{
Console.WriteLine($"Result: {result}");
}
}
}
catch (System.IO.FileNotFoundException)
{
}
catch (System.IO.FileNotFoundException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("----Exception----");
Console.WriteLine($"There is no chapter corresponding to listing {input}.");
Console.WriteLine($"There is no chapter corresponding to listing {input}.");
}
catch (TargetParameterCountException exception)
{
throw new InvalidOperationException(
$"Fatal Error invoking Listing '{input}'.\n",
exception);
exception);
}
catch (InvalidOperationException exception)
{
Expand All @@ -101,12 +115,12 @@ public static void Main(string[] args)
// exist in .NET 4.0 or earlier and we want to maintain compatibility
// while still taking advantage of it if it is available.
Type exceptionDispatchInfoType =
Type.GetType(
"System.Runtime.ExceptionServices.ExceptionDispatchInfo");
Type.GetType(
"System.Runtime.ExceptionServices.ExceptionDispatchInfo");
if (exceptionDispatchInfoType != null)
{
dynamic exceptionDispatchInfo = exceptionDispatchInfoType.GetMethod("Capture")
.Invoke(exceptionDispatchInfoType, new object[] { exception.InnerException });
.Invoke(exceptionDispatchInfoType, new object[] {exception.InnerException});
exceptionDispatchInfo.Throw();
}
else
Expand All @@ -115,7 +129,8 @@ public static void Main(string[] args)
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Format("Listing {0} threw an exception of type {1}.", input, exception.GetType()));
Console.WriteLine(string.Format("Listing {0} threw an exception of type {1}.", input,
exception.GetType()));
}
}
finally
Expand Down Expand Up @@ -152,18 +167,19 @@ private static string[] GetArguments()
}
else
{
args = userArguments.Split(new[] { ' ' });
args = userArguments.Split(new[] {' '});
}

return args;
}

private static string ParseListingName(string listing, out string chapterName)
private static string ParseListingName(string listing)
{
var appendices = new List<string> { "A", "B", "C", "D" };
var appendices = new List<string> {"A", "B", "C", "D"};

chapterName = "";
string chapterName = "";

string[] chapterListing = listing.Split('.');
string[] chapterListing = listing.Split('.', '-');
listing = string.Empty;

int startPosition;
Expand All @@ -172,7 +188,8 @@ private static string ParseListingName(string listing, out string chapterName)
{
startPosition = 1;
listing += chapterListing[0].ToUpper() + ".";
chapterName = "Chapter" + (appendices.Contains(chapterListing[0].ToUpper()) ? "App" : "") + chapterListing[0];
chapterName = "Chapter" + (appendices.Contains(chapterListing[0].ToUpper()) ? "App" : "") +
chapterListing[0];
}
else
{
Expand All @@ -181,12 +198,19 @@ private static string ParseListingName(string listing, out string chapterName)

for (int index = startPosition; index < chapterListing.Length; index++)
{
if (index == startPosition && string.IsNullOrEmpty(chapterName)) chapterName = "Chapter" + chapterListing[index].PadLeft(2, '0');
listing += chapterListing[index].PadLeft(2, '0') + ".";
if (index == startPosition && string.IsNullOrEmpty(chapterName))
chapterName = "Chapter" + chapterListing[index].PadLeft(2, '0');
listing += chapterListing[index].PadLeft(2, '0')
+ ((index + 1 != chapterListing.Length) ? "." : "");
}

string[] parts = listing.Split('.'); // 02.01.02.06
if (parts.Length > 2)
{
listing = $"{parts[0]}.{parts[1]}To{string.Join('.', parts.Skip(3))}";
}

listing = listing.Substring(0, listing.Length - 1);
return listing.Replace('.', '_');
}
}
}
}

0 comments on commit 3f3f09b

Please sign in to comment.