Skip to content
Open
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
17 changes: 17 additions & 0 deletions MD5/MD5.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

</Project>
31 changes: 31 additions & 0 deletions MD5/MD5.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MD5", "MD5.csproj", "{689A667D-B18B-4FD4-9F85-EEB5D9F7EF3A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{6C21EBF4-F0F4-43DE-AD6F-D725A5B27C63}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{689A667D-B18B-4FD4-9F85-EEB5D9F7EF3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{689A667D-B18B-4FD4-9F85-EEB5D9F7EF3A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{689A667D-B18B-4FD4-9F85-EEB5D9F7EF3A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{689A667D-B18B-4FD4-9F85-EEB5D9F7EF3A}.Release|Any CPU.Build.0 = Release|Any CPU
{6C21EBF4-F0F4-43DE-AD6F-D725A5B27C63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C21EBF4-F0F4-43DE-AD6F-D725A5B27C63}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C21EBF4-F0F4-43DE-AD6F-D725A5B27C63}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C21EBF4-F0F4-43DE-AD6F-D725A5B27C63}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8477A042-C89E-496B-83CB-5D610932F07A}
EndGlobalSection
EndGlobal
78 changes: 78 additions & 0 deletions MD5/MD5Async.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
namespace Test1;

using System.Security.Cryptography;
using System.Text;

/// <summary>
/// Class that computes check sum of the directory in multiple threads.
/// </summary>
public static class MD5Async

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Есть асинхронный код и есть параллельный код, и это разные вещи (причём ортогональные, одно другому не мешает). Тут, наверное, имелось в виду MD5Parallel.

{
/// <summary>
/// Computes check sum for directory or file by the path.
/// </summary>
/// <param name="path">Path to the directory or file.</param>
/// <returns>Task, that computes the check sum for directory or file.</returns>
public static async Task<byte[]> ComputeSum(string path)
{
if (Path.HasExtension(path))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Линуксоиды слегка напуганы таким способом отличать файл от директории

{
return await MD5Async.ComputeFile(path);
}

return await MD5Async.ComputeDirectory(path);
}
Comment on lines +16 to +24

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested change
public static async Task<byte[]> ComputeSum(string path)
{
if (Path.HasExtension(path))
{
return await MD5Async.ComputeFile(path);
}
return await MD5Async.ComputeDirectory(path);
}
public static async Task<byte[]> ComputeSum(string path)
=> Path.HasExtension(path) ?
await MD5Async.ComputeFile(path)
: await MD5Async.ComputeDirectory(path);


private static async Task<byte[]> ComputeDirectory(string path)
{
var files = Directory.GetFiles(path);
var direcoties = Directory.GetDirectories(path);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Опечатка

Array.Sort(files);
Array.Sort(direcoties);
List<Task<byte[]>> computingHashes = new ();
foreach (var dirPath in direcoties)
{
var bytes = ComputeDirectory(dirPath);
computingHashes.Add(bytes);
}

foreach (var filePath in files)
{
var bytes = ComputeFile(filePath);
computingHashes.Add(bytes);
}

int size = 0;

List<byte[]> hashes = new ();
foreach (var computingHash in computingHashes)
{
var hash = await computingHash;
size += hash.Length;
hashes.Add(hash);
}

var fileInfo = new FileInfo(path);
var MD5Hash = MD5.Create();
var computedHash = MD5Hash.ComputeHash(Encoding.ASCII.GetBytes(fileInfo.Name));
size += computedHash.Length;

var toHash = new byte[size];

Buffer.BlockCopy(computedHash, 0, toHash, 0, computedHash.Length);
int offset = computedHash.Length;
foreach (var hash in hashes)
{
Buffer.BlockCopy(hash, 0, toHash, offset, hash.Length);
offset += hash.Length;
}

return MD5Hash.ComputeHash(toHash);
}

private static async Task<byte[]> ComputeFile(string path)
{
var hash = MD5.Create();
return await hash.ComputeHashAsync(File.OpenRead(path));
}
}
71 changes: 71 additions & 0 deletions MD5/MD5Sequential.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
namespace Test1;

using System.Security.Cryptography;
using System.Text;

/// <summary>
/// Class that computes check sum of the directory in single thread.
/// </summary>
public static class MD5Sequential
{
/// <summary>
/// Computes check sum for directory or file by the path.
/// </summary>
/// <param name="path">Path to the directory or file.</param>
/// <returns>Task, that computes the check sum for directory or file.</returns>
public static byte[] ComputeSum(string path)
{
if (Path.HasExtension(path))
{
return MD5Sequential.ComputeFile(path);
}

return MD5Sequential.ComputeDirectory(path);
}

private static byte[] ComputeDirectory(string path)
{
var files = Directory.GetFiles(path);
var direcoties = Directory.GetDirectories(path);
Array.Sort(files);
Array.Sort(direcoties);
List<byte[]> hashes = new ();
int size = 0;
foreach (var dirPath in direcoties)
{
var bytes = ComputeDirectory(dirPath);
size += bytes.Length;
hashes.Add(bytes);
}

foreach (var filePath in files)
{
var bytes = ComputeFile(filePath);
size += bytes.Length;
hashes.Add(bytes);
}

var fileInfo = new FileInfo(path);
var MD5Hash = MD5.Create();
var computedHash = MD5Hash.ComputeHash(Encoding.ASCII.GetBytes(fileInfo.Name));
size += computedHash.Length;

var toHash = new byte[size];

Buffer.BlockCopy(computedHash, 0, toHash, 0, computedHash.Length);
int offset = computedHash.Length;
foreach (var hash in hashes)
{
Buffer.BlockCopy(hash, 0, toHash, offset, hash.Length);
offset += hash.Length;
}

return MD5Hash.ComputeHash(toHash);
}

private static byte[] ComputeFile(string path)
{
var hash = MD5.Create();
return hash.ComputeHash(File.OpenRead(path));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вот, например, это тоже вполне могло бы быть асинхронно. Но не параллельно, просто последовательно вызывались бы асинхронные методы

}
32 changes: 32 additions & 0 deletions MD5/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Diagnostics;
using System.Text;
using Test1;

Console.WriteLine("Enter path to the directory or file, or type Benchmark to start a benchmark");

string? path = Console.ReadLine();
if (path == "Benchmark")
{
Console.WriteLine("Benchmarking...");
path = "testFolder/testBecnhmark";
}

try
{
var watch = Stopwatch.GetTimestamp();
var sequentialResult = MD5Sequential.ComputeSum(path);
var sequentialTime = Stopwatch.GetElapsedTime(watch);
watch = Stopwatch.GetTimestamp();
var parallelResult = MD5Async.ComputeSum(path).Result;
var parallelTime = Stopwatch.GetElapsedTime(watch);
Console.WriteLine(
"Check sum = (parallel calculations){0} = (sequential calculations){1}, time for sequential MD5 = {2}, time for parallel MD5 = {3}.",
Encoding.UTF8.GetString(parallelResult),
Encoding.UTF8.GetString(sequentialResult),
sequentialTime,
parallelTime);
Comment on lines +22 to +27

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут явно не хватает отступов при переносе строки, и ещё можно было бы интерполированные строки использовать, не зря же их в язык завезли давно.

}
catch (Exception e)
{
Console.WriteLine("Error occured, probably incorrect path. Error = {0}", e);
}
1 change: 1 addition & 0 deletions MD5/Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using NUnit.Framework;
25 changes: 25 additions & 0 deletions MD5/Tests/Test.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Tests;

using System.Text;
using Test1;

public class Tests
{
[Test]
public void TestOneDirectory()
{
Assert.That(Encoding.UTF8.GetString(MD5Sequential.ComputeSum("../testFolder/test1")), Is.EqualTo(Encoding.UTF8.GetString(MD5Async.ComputeSum("../testFolder/test1").Result)));
}
Comment on lines +9 to +12

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Однострочники лучше через => писать


[Test]
public void TestOneFile()
{
Assert.That(Encoding.UTF8.GetString(MD5Sequential.ComputeSum("../testFolder/test1.txt")), Is.EqualTo(Encoding.UTF8.GetString(MD5Async.ComputeSum("../testFolder/test1.txt").Result)));
}

[Test]
public void TestManyDirectories()
{
Assert.That(Encoding.UTF8.GetString(MD5Sequential.ComputeSum("../testFolder/testBenchmark")), Is.EqualTo(Encoding.UTF8.GetString(MD5Async.ComputeSum("../testFolder/testBenchmark").Result)));
}
}
24 changes: 24 additions & 0 deletions MD5/Tests/Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\MD5.csproj" />
</ItemGroup>

</Project>
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
22 changes: 22 additions & 0 deletions MD5/Tests/obj/Debug/net8.0/Tests.AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Reflection;

[assembly: System.Reflection.AssemblyCompanyAttribute("Tests")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+8fe3a37c1e2ca4efdc392f7b5a0f463a8c5c8098")]
[assembly: System.Reflection.AssemblyProductAttribute("Tests")]
[assembly: System.Reflection.AssemblyTitleAttribute("Tests")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

// Generated by the MSBuild WriteCodeFragment class.

1 change: 1 addition & 0 deletions MD5/Tests/obj/Debug/net8.0/Tests.AssemblyInfoInputs.cache
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
85ea1e134dd59f21c16bfdda5e740e55a6886cd984822a0e949192b1cacec71d
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
is_global = true
build_property.TargetFramework = net8.0
build_property.TargetPlatformMinVersion =
build_property.UsingMicrosoftNETSdkWeb =
build_property.ProjectTypeGuids =
build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property.EnforceExtendedAnalyzerRules =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = Tests
build_property.ProjectDir = /home/kamen/HomeWorkThirdSemester/MD5/Tests/
build_property.EnableComHosting =
build_property.EnableGeneratedComInterfaceComImportInterop =
8 changes: 8 additions & 0 deletions MD5/Tests/obj/Debug/net8.0/Tests.GlobalUsings.g.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;
Binary file added MD5/Tests/obj/Debug/net8.0/Tests.assets.cache
Binary file not shown.
Binary file not shown.
Loading