Git Product home page Git Product logo

essentialcsharp's Introduction

Install Instructions

  1. Add package to project from nuget.org. More instructions to get started with consuming nuget packages can be found on learn.microsoft.com
  2. All tools are under the IntelliTect.Multitool namespace.
  3. That's it! Please open an issue if you have any problems with any of these steps or have other questions.

ReleaseDateAttribute - Gets an UTC DateTime of compile time. Allows us to determine the build date/time

Blog Post/Additional Information: How To Display the Build Date of a .NET Application

Samples:

  • Assignment of GetReleaseDate() to a local variable

    DateTime? date = IntelliTect.Multitool.ReleaseDateAttribute.GetReleaseDate(); // Returns a datetime in UTC to date
  • Displaying GetReleaseDate() on a cshtml page

    // This example is in cshtml.
    @IntelliTect.Multitool.ReleaseDateAttribute.GetReleaseDate() // Returns a datetime in UTC
  • Converting and displaying GetReleaseDate() on a cshtml page

    // convert this UTC DateTime object into one for my local timezone that is formatted in a “d MMM, yyyy h:mm:ss tt” (ex: 8 Feb, 2023 11:36:31 AM).
    // The following code will format the date and convert it to my local time zone of Pacific Standard Time. 
    Build: @if (IntelliTect.Multitool.ReleaseDateAttribute.GetReleaseDate() is DateTime date)
    {
      @TimeZoneInfo.ConvertTimeFromUtc(date, TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")).ToString("d MMM, yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
    }
    // Result is "Build: 8 Feb, 2023 11:36:31 AM"

RepositoryPaths - Provides consistent environment-independent normalized pathing within a git repository

Samples:

  • Get file path from the root of a repository

    // In this case, the GetDefaultRepoRoot() method can be used to get the root of a repository.
    string fullPathToTheFile = Path.Combine(IntelliTect.Multitool.RepositoryPaths.GetDefaultRepoRoot(), "TheFile.txt");

Security

  • ClaimsPrincipalExtensions: Extension methods to get a user ID and roles.
    • GetUserId
    • GetRoles

Extensions

  • StringExtensions: Extension methods for System.String
    • ValidateUrlString: Extension method to validate a URL string by checking to make sure the string is formatted correctly.
    • CreateUrlSlug: Extension method modify a string so that it is URL compatible
  • HttpExtensions: Extension methods for System.Net.Http.HttpClient ValidateUri: Extension methods to validate a Uri by attempting to make a GET request to it.
  • SystemLinqExtensions
    • WhereNotNull: Extension method to allow return of non-null value from a null object.
      • Sample:

        List<string?> listWithSomeNullValues = ["this", null, "is", null, "my", null, "favorite", null];
        List<string> listWithoutNullValues = listWithSomeNullValues.WhereNotNull().ToList();
        // returns ["this", "is", "my", "favorite"]
      • On:

        • System.Linq.Generic.IEnumerable<T>

Contributing

See the CONTRIBUTING.md file here.

If you have any problems, please feel free to check for existing issues or open a new issue.

essentialcsharp's People

Contributors

a-tanner avatar adcombs avatar andralee avatar ascott18 avatar atheaven avatar benjaminmichaelis avatar cosborn2 avatar danointellitect avatar dependabot[bot] avatar elizabeth-pauley avatar espence2003 avatar finlaysonchris avatar grantdwoods avatar hannamichaelis avatar jaspet avatar jenny-curry avatar kamonson avatar keboo avatar kodybrown avatar markmichaelis avatar mocanu-razvan avatar nlundby avatar peter-intellitect avatar salimgangji avatar twofingerrightclick avatar zackbward avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

essentialcsharp's Issues

Listing 9.18 Occasionally Fails with UnauthorizedAccessException

Occasionally, listing 9.18 fails with an System.UnauthorizedAccessException. The exception occurs on the last line of the following snippet:

string fileName = @"enumtest.txt";
FileInfo file = new FileInfo(fileName);
file.Open(FileMode.OpenOrCreate).Dispose();

It isn't clear what is different between when it succeeds and doesn't succeed making it exceptionally problematic to figure out.

Below is the error output from the test:

Test Name:	Main_FileAttributes_UseFlagsAttribute 
Test FullName:	Chapter09.Tests.AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_18.Tests.ProgramTests.Main_FileAttributes_UseFlagsAttribute
Test Source:	C:\Data\EssentialCSharp\YogaX1\1\SCC\src\Chapter09.Tests\Listing09.18.UsingFlagsAttribute.cs : line 11
Test Outcome:	Failed
Test Duration:	0:00:00

Test Name:	Main_FileAttributes_UseFlagsAttribute
Test Outcome:	Failed
Result StackTrace:	
at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.FileInfo.Open(FileMode mode)
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_18.Program.Main() in C:\Data\EssentialCSharp\YogaX1\1\SCC\src\Chapter09\Listing09.18.UsingFlagsAttribute.cs:line 13
   at IntelliTect.TestTools.Console.ConsoleAssert.Execute(String givenInput, Action action)
   at IntelliTect.TestTools.Console.ConsoleAssert.Execute(String givenInput, String expectedOutput, Action action, Func`3 areEquivalentOperator, Boolean normalizeLineEndings, String equivalentOperatorErrorMessage)
   at IntelliTect.TestTools.Console.ConsoleAssert.Expect(String expected, Action action, Func`3 comparisonOperator, Boolean normalizeLineEndings, String equivalentOperatorErrorMessage)
   at IntelliTect.TestTools.Console.ConsoleAssert.Expect(String expected, Action action, Boolean normalizeLineEndings)
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_18.Tests.ProgramTests.Main_FileAttributes_UseFlagsAttribute() in C:\Data\EssentialCSharp\YogaX1\1\SCC\src\Chapter09.Tests\Listing09.18.UsingFlagsAttribute.cs:line 19
Result Message:	
Test method AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_18.Tests.ProgramTests.Main_FileAttributes_UseFlagsAttribute threw exception: 
System.UnauthorizedAccessException: Access to the path 'C:\Data\EssentialCSharp\YogaX1\1\SCC\src\Chapter09.Tests\bin\Debug\netcoreapp3.0\enumtest.txt' is denied.
``

Run the .NET Portability Analyzer Against the Code

Thanks to @jaspet, we are compiling and executing the tests on Linux (and almost on Mac), I doubt there are any issues but it would be great if we could run the .NET Portability Analyzer against the entire code base and see what shows up.

Ideally, this task would include adding execution of this analyzer to the build.

Switch batch testing instruction to dotnet test?

In readme it says

Batch Testing
Use one of the following scripts to execute a batch test on all the projects.

/EssentialCSharp/RunTests.ps1 (Windows)
/EssentialCSharp/RunTests.sh (Linux/Mac)
If running on Linux you may need to give the script execution permission. From the /EssentialCSharp/ directory:

$ chmod +x ./RunTests.sh
$ ./RunTests.sh

should we just say run
dotnet test in the essentialCSharp directory on your computer instead?

Listing05.19.CountingLinesUsingOverloading had a test error

DirectoryCountLines(subdirectory) called the DirectoryCountLines(string directory),this method will counting lines with ".cs" extension,but if i called DirectoryCountLines(string directory, string extension) ,it's mean i want to counting lines with the string "extension" rather than "*.cs"
uTools_1609746006521

Switch Listing 9.16 to be cross-platform

Listing 9.16 uses a FileAttributes.Hidden enum which doesn't work on Linux. Update the sample to work on Linux.

Proposals on what change to make are welcome.

Provide Implementation of Listing 20.20 that works on MAC and/or Linux

Unfortunately, Listing 20.20 only works on Windows. It would be great to have the equivalent code on Linux and Mac.

I have marked it as "High Priority" in the hopes that we can have an implementation before we publish the book so that I still have time to modify the text.

If you take this on, create an issue for the platform you are implementing and modify this issue to refer to the remaining one.

Listing 2.30: out variable still avaiable out of the if block

P.75 "The result is that the number variable is available from both the true and false consequence of the if statement but not outside the if statement."

In fact, the variable is still in scope outside of the if block.

            // double number;
            string input;
            System.Console.Write("Enter a number: ");
            input = System.Console.ReadLine();
            if (double.TryParse(input, out double number))
            {
                System.Console.WriteLine($"input was parsed successfully to {number}.");
            }
            else
            {
                // Note: number scope is here too (although not assigned)
                System.Console.WriteLine("The text entered was not a valid number.");
            }

            System.Console.Write($"the value of number is {number}.");

temp

How do I modify the statement of the text?

Zip file download from github doesn't build due to missing submodule

After downloading the source code zip from github (not using a clone), the project fails to build with the following error:
C:\Program Files\dotnet\sdk\2.1.202\NuGet.targets(239,5): error MSB3202: not found project file“C:\Users\...\Documents\EC\submodules\TestTools\IntelliTect.TestTools.Console\IntelliTect.TestTools.Console.csproj”。 [C:\Users\...\Documents\EC\EssentialCSharp.sln]

Wrong statement about operator precedence

Hi,

At page 121, there's the following statement:

if ((hourOfTheDay > 23) || (hourOfTheDay < 0))

[...]
Note that the parentheses are not necessary here; the logical operators are of higher precedence than the relational operators

Actually logical operators have a lower precedence than relational operators, because otherwise hourOfTheDay > 23 || hourOfTheDay < 0 would be equivalent to hourOfTheDay > (23 || hourOfTheDay) < 0, which obviously results in a compile error.

Transfer over Azure pipelines to Github Actions

  • Create all pipelines for all branches between devops and github for coverage
  • Create github actions for v8.0 and v9.0
  • Schedule builds as well as on push/PRs
  • Check collectors and report generators
  • update readme status badges

Incorrectly invoking Async methods from Shares\Program.cs

When running Shared\Program.cs from any project (the launcher that calls each source file, the invocation doesn't wait for an async method to complete.

Line Shared\Program.cs (93) checks for an STAThreadAttribute but neglects to check for the System.Runtime.CompilerServices.AsyncStateMachineAttribute. When this attribute exists, the InvokeMethodUsingReflection() method needs to wait for the result (handling Task, Task<T>, ValueTask<T>, and IAsyncEnumerable<T> returns. See line 67

Tests missing

We are missing quite a few tests and it would be great to get the remainder in place. Rather than one person take this issue, please create a new issue titled something like "Tests missing in Chapter X' and then assign it to yourself so we know which chapters are being investigated.

If there are chapters where there are no missing tests, please still create the issue but mark it as done. :)

Investigate Listing 19.17: AsyncVoidReturnTest which failed in test run

Listing 19.17: AsyncVoidReturnTest failed.

Test Name:	AsyncVoidReturnTest
Test FullName:	AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.Tests.ProgramTests.AsyncVoidReturnTest
Test Source:	C:\Dropbox\EssentialCSharp\1\SCC\src\Chapter19.Tests\Listing19.17.Tests.cs : line 21
Test Outcome:	Failed
Test Duration:	0:00:00.2601871

Result StackTrace:	
at IntelliTect.TestTools.Console.ConsoleAssert.AssertExpectation(String expectedOutput, String output, Func`3 areEquivalentOperator) in C:\Dropbox\EssentialCSharp\1\SCC\submodules\TestTools\IntelliTect.TestTools.Console\ConsoleAssert.cs:line 164
   at IntelliTect.TestTools.Console.ConsoleAssert.Execute(String givenInput, String expectedOutput, Action action, Func`3 areEquivalentOperator, Boolean replaceCRLF) in C:\Dropbox\EssentialCSharp\1\SCC\submodules\TestTools\IntelliTect.TestTools.Console\ConsoleAssert.cs:line 148
   at IntelliTect.TestTools.Console.ConsoleAssert.Expect(String expected, Action action, Func`3 comparisonOperator, Boolean replaceCRLF) in C:\Dropbox\EssentialCSharp\1\SCC\submodules\TestTools\IntelliTect.TestTools.Console\ConsoleAssert.cs:line 77
   at IntelliTect.TestTools.Console.ConsoleAssert.ExpectLike(String expected, Action action) in C:\Dropbox\EssentialCSharp\1\SCC\submodules\TestTools\IntelliTect.TestTools.Console\ConsoleAssert.cs:line 94
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.Tests.ProgramTests.AsyncVoidReturnTest() in C:\Dropbox\EssentialCSharp\1\SCC\src\Chapter19.Tests\Listing19.17.Tests.cs:line 31
Result Message:	
Test method AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.Tests.ProgramTests.AsyncVoidReturnTest threw exception: 
System.Exception: expected: 4241
actual: 5541
NOTE: The expected string contains wildcard charaters: [,],?,*,#
AreEqual failed:

Expected:
-----------------------------------
Invoking Task.Run...(Thread ID: *)
Running task... (Thread ID: *)
Post notification invoked...(Thread ID: *)
Post notification invoked...(Thread ID: *)
Throwing expected exception....(Thread ID: *)
System.Exception: Expected Exception
   *(Thread ID: *)
-----------------------------------
Actual: 
-----------------------------------
Invoking Task.Run...(Thread ID: 7)
Running task... (Thread ID: 8)
Post notification invoked...(Thread ID: 7)
Throwing expected exception....(Thread ID: 7)
System.Exception: Expected Exception
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.Program.<>c.<OnEvent>b__6_0() in C:\Dropbox\EssentialCSharp\1\SCC\src\Chapter19\Listing19.17.AsyncVoidReturn.cs:line 94
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.Program.<OnEvent>d__6.MoveNext() in C:\Dropbox\EssentialCSharp\1\SCC\src\Chapter19\Listing19.17.AsyncVoidReturn.cs:line 90
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.AsyncSynchronizationContext.Post(SendOrPostCallback callback, Object state) in C:\Dropbox\EssentialCSharp\1\SCC\src\Chapter19\Listing19.17.AsyncVoidReturn.cs:line 36
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_17.Program.Main() in C:\Dropbox\EssentialCSharp\1\SCC\src\Chapter19\Listing19.17.AsyncVoidReturn.cs:line 75 thrown as expected.(Thread ID: 7)
-----------------------------------
The expected length of 259 does not match the output length of 1821.

Chapter 11 Typos/Errors

(Page numbers are obtained from the kindle edition.)

Page 467:
"One important characteristic of the argument exception types (including ArgumentNullException, ArgumentNullException, and ArgumentOutOfRangeException) is that..."

The issue is that "ArgumentNullException" is listed twice.

Page 472:
"With the ExeptionDispatchInfo.Throw() method..."

The class "ExceptionDispatchInfo" is missing a c. It is spelled correctly many times earlier in the chapter.

Page 473:
"C# requires that any object that code throws must derive from System.Exception. However, this requirement is not universal to all languages. C and C++, for example, allow any object type to be thrown, including managed exceptions that don’t derive from System.Exception."

Although C++ supports exception handling and throwing, C has no standardized support or special syntax for either of them. The closest things to exception throwing in C that I can think of are setting function pointers, jumping, and dealing with errno.

Put back code analysis

It seems that in the conversion we lost code analysis. It would be great to get this back up and running but it is not the highest priority by any means.

page 93

page 93: The assignment syntax shown in Listing 3.6 is available only if you declare and assign the value within one statement.
should be Listing 3.7

msbuild fails on command line

Although 'dotnet.exe build' works correctly, it appears that running 'msbuild.exe' fails to build the project. Ideally, this should work (or at least we should understand why it doesn't). :)

What about last version support?

It seems, that both book site and this code support only previous edition of the book.
Also, not sure it is the right place, but some supplemental on Span and Memory would be nice.

Update Listing16_14 Test: SelectingAnonymousTypeFollowingGroupClause()

Once TestTools.ConsoleAssert appropriately normalizes \r\n, remove the following line from the AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_14.Tests.ProgramTests.SelectingAnonymousTypeFollowingGroupClause method:

expected = IntelliTect.TestTools.Console.ConsoleAssert.ReplaceCRLF(expected);

NOTE: Make the change in v7.0, merge to master, and then merge to v8.0.

page xxvi

page xxvi: The formatting is as follows. • Comments are shown in italics.
This is not true.

Chapter 19 Fix Migration Issues

In 2018 off a chapter split from 18, chapter 19 code got moved, but is off by .02 and also needs to be updated to match the book for v08 since it is out of date.

Restructuring to Eliminate "ChapterMain()"

Somewhere in the conversion, each listing was changed so that:

  • the listing files used ChapterMain rather than Main
  • Referenced a new project Called SharedCode rather than just linking to the necessary files in the Shared folder when required

At the time this was done (during project.json), I suspect it wasnt possible to have two static Mainmethods and be able to disambiguate which ones to use as the entry point via theStartupObject` property element. Going forward, this is not a satisfactory solution, however.

I would like to request a restructuring as follows:

  • - Remove the reference to the "SharedCode" project
  • - Delete the SharedCode project
  • - Add "linked" files that point to the Program.cs file in the Shared directory
  • - Add "liked" files that point to the other files in the Shared directory as needed (i.e. PI Calculator in the threading listings.
  • - Add the following to CSProj tiles to disambiguate which Main to use in startup.
    <PropertyGroup> <StartupObject>AddisonWesley.Michaelis.EssentialCSharp.Shared.Program</StartupObject> </PropertyGroup>
  • - Rename all ChapterMain methods to Main (consider doing this via a mass search and replace.
  • - Verify dotnet build and dotnet test work from the command line
  • - Verify dotnet test works from the command line.
  • - Verify build/test works from VS2017
  • - If a mass/automated search and replace is performed, please verify that all files stay recognizable to Git as UTF8 files.

It is acceptable if this is done one project at a time rather than with a PowerShell/batch file just as long as it is clearly recorded which projects are done and which need work.

Thoughts? Questions? Volunteers? :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.