Skip to content

Instantly share code, notes, and snippets.

@maxkoshevoi
Created October 28, 2026 09:55
Show Gist options
  • Select an option

  • Save maxkoshevoi/a0981ff6393f7f3e9f25723a1d439de7 to your computer and use it in GitHub Desktop.

Select an option

Save maxkoshevoi/a0981ff6393f7f3e9f25723a1d439de7 to your computer and use it in GitHub Desktop.
Code review
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
namespace InterviewQuestions
{
class Program
{
/// <summary>
/// Method parses file and saves all records to DB
/// </summary>
/// <param name="args">1st argument - path to the file. File can be up to 5GB. 2nd argument - number of threads</param>
/// <exception cref="Exception"></exception>
static void Main(string[] args)
{
// path to the file with many records to save
string FilePath = args[0];
int ThreadsCount = Int32.Parse(args[1]);
var allRecords = File.ReadAllLines(FilePath);
int batchSize = allRecords.Length / ThreadsCount;
for (int i = 0; i < ThreadsCount; i++)
{
var q = allRecords[i..(i * batchSize)];
var Result = false;
var t = new Task(o =>
{
try
{
Result = CalculateHashAndSaveToDb(q).Result;
}
catch (SQLException e)
{
Console.WriteLine(e);
}
}, new CancellationToken());
t.Start();
t.Wait();
if (!Result) { throw new Exception(); }
}
}
private static async Task<bool> CalculateHashAndSaveToDb(string[] records)
{
RecordHash[] recordsWithHashes = new RecordHash[records.Length];
int i = 0;
foreach (var record in records)
{
var hash = GetHashCode(record);
if (hash == 0)
throw new HashcodeException();
recordsWithHashes[i] = new RecordHash(record, hash);
i++;
}
return await SaveToDb(recordsWithHashes);
}
private static int GetHashCode(string str)
{
HttpClient client = new HttpClient();
var mess = client.GetAsync("https://get-hash.io/get/" + str);
return Int32.Parse(mess.Result.Content.ReadAsStringAsync().Result);
}
private static async Task<bool> SaveToDb(RecordHash[] records)
{
string connectionString = CONFIGURATION.ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.OpenAsync().Wait();
foreach (var record in records)
{
int r = await connection.ExecuteAsync("insert into RecordsTable ('" + record.Record + "', '" + record.Hash + "')");
if (r == 0)
throw new SQLException();
}
return true;
}
}
internal struct RecordHash
{
public string Record { get; }
public ulong Hash { get; }
public RecordHash(string record, ulong hash)
{
Record = record;
Hash = hash;
}
}
internal class SQLException : Exception
{
}
internal class HashcodeException : Exception
{
}
internal static class CONFIGURATION
{
public static string ConnectionString => "DB connection string from config";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment