/// <summary>Creates (or finds if pre-existing) a shortening for the specified URL, returning its key</summary> /// <param name="url">The URL to shorten</param> /// <returns>The key for the specified URL</returns> public async Task <string> CreateUrlShortening(string url) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentException("Invalid (null or whitespace) URL"); } else if (url.Length > _settings.MaxUrlLength) { throw new ArgumentException("Invalid URL (max supported length is " + _settings.MaxUrlLength + ")"); } url = url.ToLower(); int urlHashCode = url.GetStableHashCode(); if (_settings.ValidateUrls && !UrlUtility.IsUrlValid(url)) { throw new ArgumentException("Invalid URL"); } object returnValue = null; using (var connection = new NpgsqlConnection(_settings.RepositoryConnectionString)) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = $@"SELECT urls.""CreateUrlShortening""(@url, @urlHashCode);"; command.Parameters.Add(new NpgsqlParameter("url", NpgsqlDbType.Text) { Value = url }); command.Parameters.Add(new NpgsqlParameter("urlHashCode", NpgsqlDbType.Integer) { Value = urlHashCode }); returnValue = await command.ExecuteScalarAsync(); } } if (returnValue == DBNull.Value) { return(null); } return(UrlUtility.ConvertIdToKey((long)returnValue)); }