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
54 changes: 29 additions & 25 deletions csharp/delegates-and-events/FileLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,38 @@

namespace DelegatesAndEvents
{
public class FileLogger
{
private readonly string logPath;
public FileLogger(string path)
{
logPath = path;
Logger.WriteMessage += LogMessage;
}

public void DetachLog() => Logger.WriteMessage -= LogMessage;
// make sure this can't throw.
private void LogMessage(string msg)
// <SnippetFileLogger>
public class FileLogger
{
try {
using (var log = File.AppendText(logPath))
private readonly string logPath;
public FileLogger(string path)
{
logPath = path;
Logger.WriteMessage += LogMessage;
}

public void DetachLog() => Logger.WriteMessage -= LogMessage;
// make sure this can't throw.
private void LogMessage(string msg)
{
try
{
log.WriteLine(msg);
log.Flush();
using (var log = File.AppendText(logPath))
{
log.WriteLine(msg);
log.Flush();
}
}
catch (Exception)
{
// Hmm. We caught an exception while

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: since comments aren't localized, this might be better if it were in the example explanation rather than an inline comment.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is explanatory text in the article as well. I'll leave the comment for those that just download the code.

// logging. We can't really log the
// problem (since it's the log that's failing).
// So, while normally, catching an exception
// and doing nothing isn't wise, it's really the
// only reasonable option here.
}
} catch (Exception)
{
// Hmm. We caught an exception while
// logging. We can't really log the
// problem (since it's the log that's failing).
// So, while normally, catching an exception
// and doing nothing isn't wise, it's really the
// only reasonable option here.
}
}
// </SnippetFileLogger>
}
}
44 changes: 39 additions & 5 deletions csharp/delegates-and-events/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace DelegatesAndEvents
{

// Logger implementation two
// <SnippetSeverity>
public enum Severity
{
Verbose,
Expand All @@ -13,7 +14,9 @@ public enum Severity
Error,
Critical
}
// </SnippetSeverity>

// <SnippetLoggerFinal>
public static class Logger
{
public static Action<string> WriteMessage;
Expand All @@ -26,11 +29,42 @@ public static void LogMessage(Severity s, string component, string msg)
return;

var outputMsg = $"{DateTime.Now}\t{s}\t{component}\t{msg}";
// Assumes that the WriteMessage delegate must not be null:
WriteMessage(outputMsg);
// Alternative invoke syntax, for when the delegate
// may not have any methods attached:
WriteMessage?.Invoke(outputMsg);
}
}
}
// </SnippetLoggerFinal>
}

namespace ImplementationOne
{
// <SnippetFirstImplementation>
public static class Logger
{
public static Action<string> WriteMessage;

public static void LogMessage(string msg)
{
WriteMessage(msg);
}
}
// </SnippetFirstImplementation>

}

namespace ImplementationTwo
{
using DelegatesAndEvents;

// <SnippetLoggerTwo>
public static class Logger
{
public static Action<string> WriteMessage;

public static void LogMessage(Severity s, string component, string msg)
{
var outputMsg = $"{DateTime.Now}\t{s}\t{component}\t{msg}";
WriteMessage(outputMsg);
}
}
// </SnippetLoggerTwo>
}
6 changes: 6 additions & 0 deletions csharp/delegates-and-events/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,21 @@ namespace DelegatesAndEvents
{
public class Program
{
// <SnippetLogToConsole>
public static void LogToConsole(string message)
{
Console.Error.WriteLine(message);
}
// </SnippetLogToConsole>

public static void Main(string[] args)
{
// <SnippetConnectDelegate>
Logger.WriteMessage += LogToConsole;
// </SnippetConnectDelegate>
// <SnippetFileLogger>
var file = new FileLogger("log.txt");
// </SnippetFileLogger>

Logger.LogMessage(Severity.Warning, "Console", "This is a warning message");

Expand Down
13 changes: 13 additions & 0 deletions csharp/delegates-and-events/delegates-and-events.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<DebugType>portable</DebugType>
<AssemblyName>delegates-and-events</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>delegates-and-events</PackageId>
<PackageTargetFallback>$(PackageTargetFallback);dnxcore50</PackageTargetFallback>
<RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion>
</PropertyGroup>

</Project>
4 changes: 0 additions & 4 deletions csharp/delegates-and-events/log.txt

This file was deleted.

19 changes: 0 additions & 19 deletions csharp/delegates-and-events/project.json

This file was deleted.

50 changes: 49 additions & 1 deletion csharp/events/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,33 @@ static void Main(string[] args)
var lister = new FileSearcher();
int filesFound = 0;

// <SnippetDeclareEventHandler>
EventHandler<FileFoundArgs> onFileFound = (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.FoundFile);
filesFound++;
//eventArgs.CancelRequested = true;
};

lister.FileFound += onFileFound;
// </SnippetDeclareEventHandler>

// <SnippetSearch>
lister.DirectoryChanged += (sender, eventArgs) =>
{
Console.Write($"Entering '{eventArgs.CurrentSearchDirectory}'.");
Console.WriteLine($" {eventArgs.CompletedDirs} of {eventArgs.TotalDirs} completed...");
};
// </SnippetSearch>

lister.Search(".", "*.dll", true);

// <SnippetRemoveHandler>
lister.FileFound -= onFileFound;
// </SnippetRemoveHandler>
}
}

// <SnippetEventArgs>
public class FileFoundArgs : EventArgs
{
public string FoundFile { get; }
Expand All @@ -46,7 +52,9 @@ public FileFoundArgs(string fileName)
FoundFile = fileName;
}
}
// </SnippetEventArg>

// <SnippetSearchDirEventArgs>
internal struct SearchDirectoryArgs
{
internal string CurrentSearchDirectory { get; }
Expand All @@ -60,16 +68,23 @@ internal SearchDirectoryArgs(string dir, int totalDirs, int completedDirs)
CompletedDirs = completedDirs;
}
}
// </SnippetSearchDirEventArgs>

public class FileSearcher
{
// <SnippetDeclareEvent>
public event EventHandler<FileFoundArgs> FileFound;
// </SnippetDeclareEvent>
// <SnippetDeclareSearchEvent>
internal event EventHandler<SearchDirectoryArgs> DirectoryChanged
{
add { directoryChanged += value; }
remove { directoryChanged -= value; }
}
private EventHandler<SearchDirectoryArgs> directoryChanged;
// </SnippetDeclareSearchEvent>

// <SnippetFinalImplementation>
public void Search(string directory, string searchPattern, bool searchSubDirs = false)
{
if (searchSubDirs)
Expand Down Expand Up @@ -105,5 +120,38 @@ private void SearchDirectory(string directory, string searchPattern)
break;
}
}
// </SnippetFinalImplementation>
}
}

namespace VersionOne
{
// <SnippetEventArgsV1>
public class FileFoundArgs : EventArgs
{
public string FoundFile { get; }
public bool CancelRequested { get; set; }

public FileFoundArgs(string fileName)
{
FoundFile = fileName;
}
}
// </SnippetEventArgV1>

// <SnippetFileSearcherV1>
public class FileSearcher
{
public event EventHandler<FileFoundArgs> FileFound;

public void Search(string directory, string searchPattern)
{
foreach (var file in Directory.EnumerateFiles(directory, searchPattern))
{
FileFound?.Invoke(this, new FileFoundArgs(file));
}
}
}
// </SnippetFileSearcherV1>

}
13 changes: 13 additions & 0 deletions csharp/events/events.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<DebugType>portable</DebugType>
<AssemblyName>events</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>events</PackageId>
<PackageTargetFallback>$(PackageTargetFallback);dnxcore50</PackageTargetFallback>
<RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion>
</PropertyGroup>

</Project>
18 changes: 0 additions & 18 deletions csharp/events/events.xproj

This file was deleted.

19 changes: 0 additions & 19 deletions csharp/events/project.json

This file was deleted.