public async Task IPAddressDAO_UpdateAsync_SuccessfulUpdate(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); // Prepare a new data to update. IPAddressRecord updatedRecord = new IPAddressRecord(ip, 1, 1, 1); // Act // Update the data of the IP. await ipDAO.UpdateAsync(updatedRecord); // Read the IP. IPAddressObject ipObject = (IPAddressObject)await ipDAO.ReadByIdAsync(ip); // Check if the IP was updated correctly and set the result to true. bool result = DataEquals(updatedRecord, ipObject); // Assert // The result should be true. Assert.IsTrue(result); // Clean up // Delete the IP. await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
public async Task IPAddressDAO_ReadByIdAsync_UnsuccessfulRead(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); bool result = false; // Act try { // Read a non-existing IP. IPAddressObject ipObject = (IPAddressObject)await ipDAO.ReadByIdAsync(NonExistingIP).ConfigureAwait(false); } catch (ArgumentException) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); // Clean up await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
public void IPAddressDAO_DeleteByIds_SuccessfulDeletion(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create an IP address. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); // Act // Delete the IP address. ipDAO.DeleteByIds(new List <string>() { ip }); // Check if the IP exists and set the result accordingly. bool result = ipDAO.CheckIPExistence(ip); // Assert // The result should be false. Assert.IsFalse(result); }
private bool DataEquals(IPAddressRecord ipRecord, IPAddressObject ipObject) { IDictionary <string, object> recordData = ipRecord.GetData(); Console.WriteLine(recordData[Constants.AnonymousUserDAOIPColumn]); Console.WriteLine(recordData[Constants.AnonymousUserDAOtimestampLockedColumn]); Console.WriteLine(recordData[Constants.AnonymousUserDAOregistrationFailuresColumn]); Console.WriteLine(recordData[Constants.AnonymousUserDAOlastRegFailTimestampColumn]); Console.WriteLine(ipObject.IP); Console.WriteLine(ipObject.TimestampLocked); Console.WriteLine(ipObject.RegistrationFailures); Console.WriteLine(ipObject.LastRegFailTimestamp); if (((string)recordData[Constants.AnonymousUserDAOIPColumn]).Equals(ipObject.IP) && ((long)recordData[Constants.AnonymousUserDAOtimestampLockedColumn]).Equals(ipObject.TimestampLocked) && ((int)recordData[Constants.AnonymousUserDAOregistrationFailuresColumn]).Equals(ipObject.RegistrationFailures) && ((long)recordData[Constants.AnonymousUserDAOlastRegFailTimestampColumn]).Equals(ipObject.LastRegFailTimestamp)) { return(true); } else { return(false); } }
public void IPAddressDAO_ReadById_UnsuccessfulRead(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); bool result = false; // Act try { // Read a non-existing IP. IPAddressObject ipObject = (IPAddressObject)ipDAO.ReadById(NonExistingIP); } catch (ArgumentException) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); }
public async Task IPAddressDAO_CheckIPExistenceAsync_IPNonExists(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); // Act // Check if the IP exists and set the result accordingly. bool result = await ipDAO.CheckIPExistenceAsync(NonExistingIP).ConfigureAwait(false); // Assert // The result should be false. Assert.IsFalse(result); // Clean up // Delete the IP. await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
public async Task IPAddressDAO_ReadByIdAsync_SuccessfulRead(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); // Act // Read the IP. IPAddressObject ipObject = (IPAddressObject)await ipDAO.ReadByIdAsync(ip).ConfigureAwait(false); // Check if the read IP is correct and set the result accordingly. bool result = DataEquals(ipRecord, ipObject); // Assert // The result should be true. Assert.IsTrue(result); // Clean up // Delete the IP. await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
/// <summary> /// Updates an entry in the IP Address data store using the <paramref name="ipRecord"/>. /// </summary> /// <param name="ipRecord">The unmasked record conveying the data to update.</param> /// <returns>Task (bool) whether the function completed without exception</returns> public async Task <bool> UpdateIPAsync(IPAddressRecord ipRecord) { // Record must be unmasked. if (ipRecord.IsMasked()) { throw new ArgumentException(Constants.UpdateIPRecordMasked); } // If the column is masked, mask the ip. string id = ipRecord.GetData()[Constants.AnonymousUserDAOIPColumn] as string; if (Constants.AnonymousUserDAOIsColumnMasked[Constants.AnonymousUserDAOIPColumn]) { id = _maskingService.MaskString(id); } IPAddressRecord maskedRecord = await _maskingService.MaskAsync(ipRecord, false).ConfigureAwait(false) as IPAddressRecord; // Get the masked object from the ipDAO and decrement its mapping before updating. IPAddressObject maskedObj = await _anonymousUserDAO.ReadByIdAsync(id).ConfigureAwait(false) as IPAddressObject; await _maskingService.DecrementMappingForUpdateAsync(maskedRecord, maskedObj).ConfigureAwait(false); return(await _anonymousUserDAO.UpdateAsync(maskedRecord).ConfigureAwait(false)); }
public void IPAddressDAO_Update_UnsuccessfulUpdate(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create the IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); // Prepare a new data to update but with a wrong IP address. IPAddressRecord updatedRecord = new IPAddressRecord(NonExistingIP, 1, 1, 1); bool result = false; // Act try { // Update the IP address. ipDAO.Update(updatedRecord); } catch (Exception) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); }
public async Task IPAddressDAO_CreateAsync_UnsuccessfulCreation(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); bool result = false; // Act try { // Create the same IP Address twice. await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); } catch (Exception) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); // Clean up // Delete the IP. await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
public void IPAddressDAO_Create_UnsuccessfulCreation(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); bool result = false; // Act try { // Create the same IP Address twice. ipDAO.Create(ipRecord); ipDAO.Create(ipRecord); } catch (ArgumentException) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); }
public async Task IPAddressDAO_CreateAsync_SuccessfulCreation(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); // Act // Create IP Address. await ipDAO.CreateAsync(ipRecord); IPAddressObject ipObject = (IPAddressObject)await ipDAO.ReadByIdAsync(ip).ConfigureAwait(false); // Check if the data created is correct. bool correctDataResult = DataEquals(ipRecord, ipObject); // Assert // The data should be correct. Assert.IsTrue(correctDataResult); // Clean up // Delete the IP. await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
public void IPAddressDAO_Update_SuccessfulUpdate(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); // Prepare a new data to update. IPAddressRecord updatedRecord = new IPAddressRecord(ip, 1, 1, 1); // Act // Update the data of the IP. ipDAO.Update(updatedRecord); // Read the IP. IPAddressObject ipObject = (IPAddressObject)ipDAO.ReadById(ip); // Check if the IP was updated correctly and set the result to true. bool result = DataEquals(ipRecord, ipObject); // Assert // The result should be true. Assert.IsTrue(result); }
public void IPAddressDAO_DeleteByIds_UnsuccessfulDeletion(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create an IP address. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); bool result = false; // Act try { // Delete an non-existing IP. ipDAO.DeleteByIds(new List <string>() { NonExistingIP }); } catch (ArgumentException) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); }
/// <summary> /// Creates a record in the data store with the <paramref name="ipAddress"/>. /// </summary> /// <param name="ipAddress">ip address to insert into the data store (string)</param> /// <returns>Task (bool) whether the function completed without exception</returns> public static bool CreateIP(string ipAddress) { // Initialize the locked time and registration failures to initially have no value. IPAddressRecord record = new IPAddressRecord(ipAddress, Constants.NoValueLong, Constants.NoValueInt, Constants.NoValueLong); // Call the create method via the IP DAO with the record. return(_ipDAO.Create(record)); }
/// <summary> /// Unlock the <paramref name="ipAddress"/>. /// </summary> /// <param name="ipAddress">The ip address to unlock (string)</param> /// <returns>Task (bool) wheter the function completed without exception</returns> public static bool UnlockIP(string ipAddress) { // Make the timestamp locked and registration failures have no value. IPAddressRecord record = new IPAddressRecord(ipAddress, timestampLocked: Constants.NoValueLong, registrationFailures: Constants.NoValueInt); // Call the update funciton of the IP DAO with the record. return(_ipDAO.Update(record)); }
/// <summary> /// Asynchronously unlock the <paramref name="ipAddress"/>. /// </summary> /// <param name="ipAddress">The ip address to unlock (string)</param> /// <returns>Task (bool) wheter the function completed without exception</returns> public async Task <bool> UnlockIPAsync(string ipAddress) { // Make the timestamp locked and registration failures have no value. IPAddressRecord record = new IPAddressRecord(ipAddress, timestampLocked: Constants.NoValueLong, registrationFailures: Constants.NoValueInt); // Asynchronously call the update funciton of the IP DAO with the record. return(await UpdateIPAsync(record).ConfigureAwait(false)); }
/// <summary> /// Asynchronously creates a record in the data store with the <paramref name="ipAddress"/>. /// </summary> /// <param name="ipAddress">ip address to insert into the data store (string)</param> /// <returns>Task (bool) whether the function completed without exception</returns> public async Task <bool> CreateIPAsync(string ipAddress) { // Initialize the locked time and registration failures to initially have no value. IPAddressRecord record = new IPAddressRecord(ipAddress, Constants.NoValueLong, Constants.NoValueInt, Constants.NoValueLong); IPAddressRecord resultRecord = await _maskingService.MaskAsync(record, true).ConfigureAwait(false) as IPAddressRecord; // Asynchronously call the create method via the IP DAO with the record. return(await _anonymousUserDAO.CreateAsync(resultRecord).ConfigureAwait(false)); }
protected ArrayList InitRemoteIPs() { NatHistory.Filter f = delegate(NatDataPoint p) { TransportAddress ta = p.PeerViewOfLocalTA; IPAddress a = null; if (ta != null) { try { a = ((IPTransportAddress)ta).GetIPAddress(); } catch (Exception x) { BU.ProtocolLog.WriteIf(BU.ProtocolLog.Exceptions, String.Format( "{0}", x)); } } return(a); }; IEnumerable all_ips = _hist.FilteredEnumerator(f); Hashtable ht = new Hashtable(); foreach (IPAddress a in all_ips) { if (false == ht.Contains(a)) { IPAddressRecord r = new IPAddressRecord(); r.IP = a; r.Count = 1; ht[a] = r; } else { IPAddressRecord r = (IPAddressRecord)ht[a]; r.Count++; } } ArrayList rips = new ArrayList(); IDictionaryEnumerator de = ht.GetEnumerator(); while (de.MoveNext()) { IPAddressRecord r = (IPAddressRecord)de.Value; rips.Add(r); } //Now we have a list of the most used to least used IPs rips.Sort(); return(rips); }
/// <summary> /// Increment the registration failures of the anonymous user defined by the <paramref name="ipAddress"/>. /// </summary> /// <param name="ipAddress">The ip address to increment the registration failures of (string)</param> /// <param name="maxTimeBeforeFailureReset">The time before their failures reset (TimeSpan)</param> /// <param name="maxNumberOfTries">The max number of registration tries before they get locked (int)</param> /// <returns>Task (bool) whether the funciton executed without exception</returns> public async Task <bool> IncrementRegistrationFailuresAsync(string ipAddress, TimeSpan maxTimeBeforeFailureReset, int maxNumberOfTries) { IPAddressObject ip = await GetIPAddressInfoAsync(ipAddress).ConfigureAwait(false); IPAddressRecord record; // Need to check if the maxtime + lastTime is less than now. // if it is then reset the failure long lastRegFailTimestamp = ip.LastRegFailTimestamp; long maxSeconds = TimeUtilityService.TimespanToSeconds(maxTimeBeforeFailureReset); long currentUnix = TimeUtilityService.CurrentUnixTime(); bool reset = false; // If the time has passed their max time before reset, reset their failures. Don't reset // if they have no last registration fail timestamp. if (lastRegFailTimestamp + maxSeconds < currentUnix && lastRegFailTimestamp != Constants.NoValueLong) { reset = true; record = new IPAddressRecord(ipAddress, registrationFailures: 0); await UpdateIPAsync(record).ConfigureAwait(false); } // Increment the user's login Failure count. int updatedRegistrationFailures = reset ? 1 : ip.RegistrationFailures + 1; // Lock the ip if they have reached the max number of tries. // Update the last reg fail time. if (updatedRegistrationFailures >= maxNumberOfTries) { record = new IPAddressRecord(ipAddress, timestampLocked: currentUnix, registrationFailures: updatedRegistrationFailures, lastRegFailTimestamp: currentUnix); // Asynchronously notify the system admin if an ip address was locked during registration. await SystemUtilityService.NotifySystemAdminAsync($"{ipAddress} was locked at {currentUnix}", Constants.SystemAdminEmailAddress).ConfigureAwait(false); } else { record = new IPAddressRecord(ipAddress, registrationFailures: updatedRegistrationFailures, lastRegFailTimestamp: currentUnix); } return(await UpdateIPAsync(record).ConfigureAwait(false)); }
public async Task MaskingService_MaskAsync_WorksWithDifferentRecords() { LogRecord lrecord = new LogRecord("test", "test", "test", "test", "test"); IPAddressRecord irecord = new IPAddressRecord("test"); LogRecord lrecordMasked = (LogRecord)await _maskingService.MaskAsync(lrecord, false).ConfigureAwait(false); IPAddressRecord irecordMasked = (IPAddressRecord)await _maskingService.MaskAsync(irecord, false).ConfigureAwait(false); Assert.IsTrue(lrecordMasked.IsMasked()); Assert.IsTrue(irecordMasked.IsMasked()); try { await _mapDAO.DeleteByIdsAsync(new List <string>() { _maskingService.MaskString("test") }).ConfigureAwait(false); } catch { } }
public void IPAddressDAO_Create_SuccessfulCreation(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); // Act // Create IP Address. ipDAO.Create(ipRecord); IPAddressObject ipObject = (IPAddressObject)ipDAO.ReadById(ip); // Check if the data created is correct. bool correctDataResult = DataEquals(ipRecord, ipObject); // Assert // The data should be correct. Assert.IsTrue(correctDataResult); }
/** * Sort them from largest count to least count */ public int CompareTo(object o) { if (this == o) { return(0); } IPAddressRecord other = (IPAddressRecord)o; if (Count > other.Count) { return(-1); } else if (Count < other.Count) { return(1); } else { return(0); } }
public void IPAddressDAO_CheckIPExistence_IPNonExists(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); // Act // Check if the IP exists and set the result accordingly. bool result = ipDAO.CheckIPExistence(NonExistingIP); // Assert // The result should be false. Assert.IsFalse(result); }
public async Task IPAddressDAO_UpdateAsync_UnsuccessfulUpdate(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange // Create the IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); await ipDAO.CreateAsync(ipRecord).ConfigureAwait(false); // Prepare a new data to update but with a wrong IP address. IPAddressRecord updatedRecord = new IPAddressRecord(NonExistingIP, 1, 1, 1); bool result = false; // Act try { // Update the IP address. await ipDAO.UpdateAsync(updatedRecord).ConfigureAwait(false); } catch (Exception) { // Catch the exception and set the result to true. result = true; } // Assert // The result should be true. Assert.IsTrue(result); // Clean up // Delete the IP. await ipDAO.DeleteByIdsAsync(new List <string>() { ip }).ConfigureAwait(false); }
public void IPAddressDAO_ReadById_SuccessfulRead(string ip, long timestampLocked, int registrationFailures, long lastRegFailTimestamp) { // Arrange UnitTestIPAddressDAO ipDAO = new UnitTestIPAddressDAO(); // Create an IP. IPAddressRecord ipRecord = new IPAddressRecord(ip, timestampLocked, registrationFailures, lastRegFailTimestamp); ipDAO.Create(ipRecord); // Act // Read the IP. IPAddressObject ipObject = (IPAddressObject)ipDAO.ReadById(ip); // Check if the read IP is correct and set the result accordingly. bool result = DataEquals(ipRecord, ipObject); // Assert // The result should be true. Assert.IsTrue(result); }
/// <summary> /// Update the <paramref name="record"/> in the data store based on the values that are not null inside it. /// </summary> /// <param name="record">The record containing the information to update (ISQLRecord)</param> /// <returns>Task (bool) whether the function executed without exception</returns> public async Task <bool> UpdateAsync(ISQLRecord record) { // Try casting the record to an IPAddressRecord, throw an argument exception if it fails. try { IPAddressRecord temp = (IPAddressRecord)record; } catch { throw new ArgumentException(Constants.IPUpdateInvalidArgument); } // Get the record data. IPAddressRecord ipRecord = (IPAddressRecord)record; IDictionary <string, object> recordData = ipRecord.GetData(); // Get the connection inside a using statement to properly dispose/close. using (MySqlConnection connection = new MySqlConnection(SQLConnection)) { // Open the connection. connection.Open(); // Construct the sql string to update the table name where.. string sqlString = $"UPDATE {Constants.AnonymousUserDAOTableName} SET "; // Loop through the record data. int count = 0; foreach (KeyValuePair <string, object> pair in recordData) { // Check if the value at the ip column is contained within the table, throw an argument // exception if it doesn't exist. if (pair.Key == Constants.AnonymousUserDAOIPColumn) { if (!await CheckIPExistenceAsync((string)pair.Value).ConfigureAwait(false)) { throw new ArgumentException(Constants.IPUpdateDNE); } } // Update only the values where the record value is not null (string == null, numeric == -1). // Again, use parameters to prevent against sql injections. if (pair.Key != Constants.AnonymousUserDAOIPColumn) { if (pair.Value is int) { if ((int)pair.Value != -1) { sqlString += $"{pair.Key} = @PARAM{count},"; } } if (pair.Value is string) { if (pair.Value != null) { sqlString += $"{pair.Key} = @PARAM{count},"; } } if (pair.Value is long) { if ((long)pair.Value != -1) { sqlString += $"{pair.Key} = @PARAM{count},"; } } } count++; } // Remove the last comma and identify the record by its ip column. sqlString = sqlString.Remove(sqlString.Length - 1); sqlString += $" WHERE {Constants.AnonymousUserDAOIPColumn} = '{recordData[Constants.AnonymousUserDAOIPColumn]}';"; // Get the command inside a using statement to properly dispose/close. using (MySqlCommand command = new MySqlCommand(sqlString, connection)) { // Loop through the record data again to add values to the parameters. count = 0; foreach (KeyValuePair <string, object> pair in recordData) { if (pair.Key != Constants.AnonymousUserDAOIPColumn) { if (pair.Value is int) { if ((int)pair.Value != -1) { command.Parameters.AddWithValue($"@PARAM{count}", pair.Value); } } if (pair.Value is string) { if (pair.Value != null) { command.Parameters.AddWithValue($"@PARAM{count}", pair.Value); } } if (pair.Value is long) { if ((long)pair.Value != -1) { command.Parameters.AddWithValue($"@PARAM{count}", pair.Value); } } } count++; } // Execute the non query asynchronously. await command.ExecuteNonQueryAsync().ConfigureAwait(false); } return(true); } }
/// <summary> /// Asynchronously creates the <paramref name="record"/> in the data store. /// </summary> /// <param name="record">The record to insert (ISQLRecord)</param> /// <returns>Task(bool) whether the function executed without exception.</returns> public async Task <bool> CreateAsync(ISQLRecord record) { // Try casting the record to an IPAddressRecord, throw an argument exception if it fails. try { IPAddressRecord temp = (IPAddressRecord)record; } catch { throw new ArgumentException(Constants.IPCreateInvalidArgument); } // Get the data stored in the record. IPAddressRecord ipRecord = (IPAddressRecord)record; IDictionary <string, object> recordData = ipRecord.GetData(); // Get the connection inside a using statement to properly dispose/close. using (MySqlConnection connection = new MySqlConnection(SQLConnection)) { // Open the connection connection.Open(); // Construct the sql string .. start by inserting into the table name string sqlString = $"INSERT INTO {Constants.AnonymousUserDAOTableName} ("; // Loop through the data. foreach (KeyValuePair <string, object> pair in recordData) { // Check for null values in the data (string == null, numeric == -1), and throw a NoNullAllowedException // if one is found. if (pair.Value is int) { if ((int)pair.Value == -1) { throw new NoNullAllowedException(Constants.IPRecordNoNull); } } if (pair.Value is string) { if (pair.Value == null) { throw new NoNullAllowedException(Constants.IPRecordNoNull); } } if (pair.Value is long) { if ((long)pair.Value == -1) { throw new NoNullAllowedException(Constants.IPRecordNoNull); } } // Otherwise add the key to the string (column name). sqlString += $"{pair.Key},"; } // Remove the last comma, add the VALUES keyword sqlString = sqlString.Remove(sqlString.Length - 1); sqlString += ") VALUES ("; // Loop through the data once again, but instead of constructing the string with user input, use // @PARAM0, @PARAM1 parameters to prevent against sql injections from user input. int count = 0; foreach (KeyValuePair <string, object> pair in recordData) { sqlString += $"@PARAM{count},"; count++; } // Remove the last comma and add the last ) and ; sqlString = sqlString.Remove(sqlString.Length - 1); sqlString += ");"; // Get the command object inside a using statement to properly dispose/close. using (MySqlCommand command = new MySqlCommand(sqlString, connection)) { count = 0; // Loop through the data again to add the parameter values to the corresponding @PARAMs in the string. foreach (KeyValuePair <string, object> pair in recordData) { command.Parameters.AddWithValue($"@PARAM{count}", pair.Value); count++; } // Asynchronously execute the non query. await command.ExecuteNonQueryAsync().ConfigureAwait(false); } return(true); } }