using System.Data.SQLite;
using System;
using System.IO;
namespace URL {
class UrlShortener {
private readonly string connectionString = "Data Source=UrlDB.sqlite;Version=3;";
public string Shorten(string url)
{
CreateDbIfNotExist();
Guid id = Guid.NewGuid();
string surl = $"http://localhost:3000/{id}";
InsertIntoDb(url, surl);
return surl;
}
// make sure connections are closed before opening them again !
private async Task<object?> ExecuteQuery(string query)
{
try
{
SQLiteConnection udb_con = new SQLiteConnection(this.connectionString);
await udb_con.OpenAsync();
SQLiteCommand command = new SQLiteCommand(query, udb_con);
object? temp = await command.ExecuteScalarAsync();
await udb_con.CloseAsync();
return temp;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return null;
}
private async void InsertIntoDb(string url, string shortened)
{
string record = $"INSERT INTO urls (dest, short) VALUES ('{url}', '{shortened}')";
var result = await ExecuteQuery(record);
if (result == null)
{
return;
}
return;
}
private string CreateDbIfNotExist()
{
var file = File.Exists("UrlDB.sqlite");
if (!file)
{
SQLiteConnection.CreateFile("UrlDB.sqlite");
SQLiteConnection udb_con = new SQLiteConnection(this.connectionString);
udb_con.Open();
string sql = "CREATE TABLE urls (dest varchar(512), short varchar(256))";
SQLiteCommand command = new SQLiteCommand(sql, udb_con);
command.ExecuteNonQueryAsync();
udb_con.Close();
return "Db has been correctly crated !";
}
return "Db already existed";
}
}
}