This commit is contained in:
2026-04-17 14:55:32 -04:00
commit bc3ac1d4c9
18017 changed files with 4371742 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Groups.GroupList;
using System.Collections.Generic;
using DTS.Common.Interface.Groups;
namespace DbAPI.Groups
{
/// <summary>
/// Group related functions (GetChannels, )
/// </summary>
public interface IGroups
{
/// <summary>
/// Inserts a new record in the Groups table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="group"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IGroupDbRecord group);
/// <summary>
/// Updates a record in the Groups table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="group"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupsUpdate(IUserDbRecord user,
IConnectionDetails connection,
IGroupDbRecord group);
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="id"></param>
/// <param name="serialNumber"></param>
/// <param name="displayName"></param>
/// <param name="embedded"></param>
/// <param name="staticGroupId"></param>
/// <param name="groups"></param>
/// <returns></returns>
ulong GroupsGet(IUserDbRecord user,
IConnectionDetails connection,
int? id,
string serialNumber,
string displayName,
bool? embedded,
int? staticGroupId,
out IGroupDbRecord[] groups);
/// <summary>
/// Deletes an entry in the Groups table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="id">Id in the Groups table</param>
/// <param name="errorString">Error string returned, possibly from sp_GroupsDelete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupsDelete(IUserDbRecord user,
IConnectionDetails connection,
long id,
out string errorString);
}
}

View File

@@ -0,0 +1,103 @@
using DbAPI.Connections;
using DbAPI.User;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.DataRecorders;
namespace DbAPI.DAS
{
/// <summary>
/// DAS functions (Get/Insert/Update/Delete)
/// </summary>
public interface IDataRecorders
{
/// <summary>
/// Deletes all channels related to DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="hardwareId"></param>
/// <returns>0 on success, all other values are errors</returns>
ulong DASChannelsDelete(IUserDbRecord user, IConnectionDetails connection,
string hardwareId);
/// <summary>
/// inserts das channel record into db. modifies record by updating id after insert
/// </summary>
/// <param name="user">user making insert</param>
/// <param name="connection">connection channel is being inserted on</param>
/// <param name="hardwareId">string identifier for hardware (serialnumber_dastype)</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong DASChannelsInsert(IUserDbRecord user, IConnectionDetails connection,
string hardwareId, ref IDASChannelDBRecord record);
/// <summary>
/// returns DASChannels for given DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connetion"></param>
/// <param name="HardwareId">string identifying hardware in the form of DASSerial_DASType (or null for all records)</param>
/// <param name="channels"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong DASChannelsGet(IUserDbRecord user, IConnectionDetails connetion, string HardwareId, out IDASChannelDBRecord[] channels);
/// <summary>
/// returns all the DAS serials associated with a given parent DAS
/// used for discovering which das are associated with a das in the db for encapsulated/compacted DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="dasSerialNumber"></param>
/// <param name="childrenSerialNumbers"></param>
/// <returns>0 on success, all other values are errors</returns>
ulong DASChildrenGet(IUserDbRecord user, IConnectionDetails connection, string dasSerialNumber, out string[] childrenSerialNumbers);
/// <summary>
/// Deletes DAS from Database
/// an Id or a serial number is required
/// will remove record from any test setups
/// will remove from channel assignments (if embedded, otherwise will remove channels as well)
/// will remove das channels and das meta data
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="DASId"></param>
/// <param name="serialNumber"></param>
/// <param name="embedded"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong DASDelete(IUserDbRecord user, IConnectionDetails connection, int DASId, string serialNumber, bool embedded);
/// <summary>
/// returns a specific data recorder or optionally all data recorders
/// Does not check that user has permission to view DAS
/// </summary>
/// <param name="user">DataPRO user requesting data recorders, must be logged in</param>
/// <param name="connection">connection user is logged in on</param>
/// <param name="DASId">Database id of DAS, or null if providing serial or requesting all DAS</param>
/// <param name="DASSerial">Serial number of DAS, or null if providing DASId or requesting all DAS</param>
/// <param name="position"></param>
/// <param name="das">DAS or multiple DAS matching search criteria, Can be null or empty</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_NOACCESS if user is not logged in
/// </returns>
ulong DASGet(IUserDbRecord user, IConnectionDetails connection, int clientDbVersion, string DASSerial,
string position, out IDASDBRecord[] das);
/// <summary>
/// Inserts a DAS record into the db
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="das"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_NOACCESS if user is not logged in</returns>
ulong DASInsert(IUserDbRecord user, IConnectionDetails connection, IDASDBRecord das);
/// <summary>
/// Updates a DAS record in the db
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="das"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_NOACCESS if user is not logged in</returns>
ulong DASUpdate(IUserDbRecord user, IConnectionDetails connection, IDASDBRecord das);
}
}

View File

@@ -0,0 +1,386 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes.Tags;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Tags;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace DbAPI.Tags
{
/// <summary>
/// defines functions to create, retrieve, update, delete tags
/// <inheritdoc cref="ITags"/>
/// </summary>
public class Tags : ITags
{
/// <summary>
/// inserts a tag assignment record into the database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="tagAssignment">assignment to be committed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong TagAssignmentsInsert(IUserDbRecord user,
IConnectionDetails connection,
ITagAssignment tagAssignment)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == tagAssignment)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagAssignmentsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ObjectID", SqlDbType.Int) { Value = tagAssignment.ObjectID });
cmd.Parameters.Add(new SqlParameter("@ObjectType", SqlDbType.SmallInt) { Value = (short)tagAssignment.ObjectType });
cmd.Parameters.Add(new SqlParameter("@TagID", SqlDbType.Int) { Value = tagAssignment.TagID });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
_ = cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagAssignmentsInsert error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagAssignmentsInsert error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// deletes all matching tags.
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="objectId">object tags assigned to</param>
/// <param name="tagType">the object type</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong TagAssignmentsDelete(IUserDbRecord user,
IConnectionDetails connection,
int objectId,
TagTypes tagType)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagAssignmentsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ObjectID", SqlDbType.Int) { Value = objectId });
cmd.Parameters.Add(new SqlParameter("@ObjectType", SqlDbType.SmallInt) { Value = (short)tagType });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags,
$"TagsAssignmentsDelete error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagAssignmentsDelete error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// retrieves all tags that have been assigned to an object type
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="tagType">object type tags are assigned to (use null for all)</param>
/// <param name="tagAssignments">all matching assignments</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong TagAssignmentsGet(IUserDbRecord user,
IConnectionDetails connection,
TagTypes? tagType,
out ITagAssignment[] tagAssignments
)
{
tagAssignments = new ITagAssignment[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagAssignmentsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null == tagType)
{
cmd.Parameters.Add(new SqlParameter("@ObjectType", SqlDbType.SmallInt) { Value = null });
}
else { cmd.Parameters.Add(new SqlParameter("@ObjectType", SqlDbType.SmallInt) { Value = (short)tagType }); }
var reader = cmd.ExecuteReader();
var list = new List<ITagAssignment>();
while (reader.Read())
{
list.Add(new TagAssignment(reader));
}
tagAssignments = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagAssignmentsGet error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// inserts a new tag, modifies tag with new id after insert
/// </summary>
/// <param name="user">user requesting insert</param>
/// <param name="connection">connection tag is being inserted on</param>
/// <param name="tag">tag to insert</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong TagsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref ITag tag)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == tag)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TagText", SqlDbType.NVarChar, 255) { Value = tag.Text });
cmd.Parameters.Add(new SqlParameter("@Obsolete", SqlDbType.Bit) { Value = tag.IsObsolete });
var id = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(id);
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsInsert error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
if (DBNull.Value.Equals(id.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsInsert error - no new id returned");
return ErrorCodes.ERROR_UNKNOWN;
}
else { tag.ID = Convert.ToInt32(id.Value); }
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsInsert error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// returns id for a given tag text
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="tagText">text associated with tag</param>
/// <param name="id">id of tag (or null if not found)</param>
/// <returns>0 on success, all other values are error codes</returns>
public ulong TagsGetId(IUserDbRecord user,
IConnectionDetails connection,
string tagText,
out int? id)
{
id = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagsGetId");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (tagText != null)
{
cmd.Parameters.Add(new SqlParameter("@TagText", SqlDbType.NVarChar, 255) { Value = tagText });
}
var tagId = new SqlParameter("@TagId", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(tagId);
cmd.ExecuteNonQuery();
if (DBNull.Value.Equals(tagId.Value))
{
id = null;
}
else { id = Convert.ToInt32(tagId.Value); }
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsGetId error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// deletes all matching tags
/// </summary>
/// <param name="tagId">id of tag to be deleted</param>
/// <param name="connection">connection tag should be deleted on</param>
/// <param name="user">user requesting delete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong TagsDelete(IUserDbRecord user,
IConnectionDetails connection,
int tagId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TagId", SqlDbType.Int) { Value = tagId });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsDelete error: {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsDelete error : {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// retrieves all tags matching search criteria
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is made on</param>
/// <param name="tagId">id of tag to search for (use null to get all tags)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong TagsGet(IUserDbRecord user,
IConnectionDetails connection,
int? tagId,
out ITag[] records)
{
records = new ITag[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TagsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (tagId != null)
{
cmd.Parameters.Add(new SqlParameter("@TagId", SqlDbType.Int) { Value = (int)tagId });
}
var reader = cmd.ExecuteReader();
var list = new List<ITag>();
while (reader.Read())
{
list.Add(new Tag(reader));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Tags, $"TagsGet error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
}
}

View File

@@ -0,0 +1,68 @@
using DTS.Common.Utilities.Logging;
using System;
using System.Diagnostics;
using System.IO;
using static DTS.Common.Utilities.Logging.APILogger;
namespace DbAPI.Logging
{
internal class LogManager
{
public static Sink DBAPILogWriter;
private static TextLogger _LogWriter;
private static object MyLock = new object();
private static int _MinLog = (int)(TraceEventType.Error | TraceEventType.Warning);
public enum LogEvents
{
Message,
Connections,
Login,
Information,
DataRecorders,
Graphs,
CalculatedChannels,
Sensors,
TestSetups,
RegionsOfInterest,
Tags
}
public static void Initialize(int logSize, string path, int minLog)
{
lock (MyLock)
{
if (null != _LogWriter) { return; }
_MinLog = minLog;
_LogWriter = new TextLogger(Path.Combine(path, "DB.log"), OnWriteException, logSize);
_LogWriter.ReRollLog = true;
_LogWriter.LogStartMessage = GetLogStartMessage();
DBAPILogWriter = LogMsg;
}
}
public static void Log(TraceEventType eventType, LogEvents logEvent, string msg)
{
if ((_MinLog & (int)eventType) != (int)eventType) { return; } //don't log
var dt = DateTime.Now;
LogMsg($"{dt.Year}-{dt.Month:00}-{dt.Day:00} {dt.Hour:00}:{dt.Minute:00}:{dt.Second:00}.{dt.Millisecond:000} {eventType} - {logEvent} - {msg}");
}
public static void OnWriteException(Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
private static void LogMsg(string msg)
{
try
{
_LogWriter.LogMessage(msg);
}
catch (Exception) { }
}
private static string GetLogStartMessage()
{
return string.Format("DB API\r\n" +
$"OS: {Environment.OSVersion}\r\n" +
$"MachineName: {Environment.MachineName}\r\n" +
$"Environment: {Environment.Version} \r\n\n" +
"=====================================\r\n");
}
}
}

View File

@@ -0,0 +1,316 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DbAPI.LabratoryDetails;
using DTS.Common.Interface.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using DTS.Common.Interface.TestMetaData;
using DTS.Common.Classes.LabratoryDetails;
namespace DbAPI.LabratoryDetails
{
/// <summary>
/// Handles Labratory Details functions
/// </summary>
internal class LabratoryDetails : ILabratoryDetails
{
public ulong LabratoryDetailsInsert(IUserDbRecord user,
IConnectionDetails connection,
LabratoryDetailsDbRecord labratoryDetailsDbRecord,
out int newId,
out string errorString)
{
errorString = string.Empty;
newId = -1;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_LabratoryDetailsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@LabratoryName", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryName });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactName", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactName });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactPhone", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactPhone });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactFax", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactFax });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactEmail", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactEmail });
cmd.Parameters.Add(new SqlParameter("@LabratoryTestRefNumber", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryTestRefNumber });
cmd.Parameters.Add(new SqlParameter("@LabratoryProjectRefNumber", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryProjectRefNumber });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = labratoryDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = labratoryDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = labratoryDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
else
{
newId = (int)newIdParam.Value;
}
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong LabratoryDetailsUpdate(IUserDbRecord user,
IConnectionDetails connection,
LabratoryDetailsDbRecord labratoryDetailsDbRecord,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_LabratoryDetailsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@LabratoryName", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryName });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactName", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactName });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactPhone", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactPhone });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactFax", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactFax });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactEmail", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactEmail });
cmd.Parameters.Add(new SqlParameter("@LabratoryTestRefNumber", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryTestRefNumber });
cmd.Parameters.Add(new SqlParameter("@LabratoryProjectRefNumber", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryProjectRefNumber });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = labratoryDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = labratoryDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = labratoryDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong LabratoryDetailsUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
LabratoryDetailsDbRecord labratoryDetailsDbRecord,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_LabratoryDetailsUpdateInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@LabratoryName", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryName });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactName", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactName });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactPhone", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactPhone });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactFax", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactFax });
cmd.Parameters.Add(new SqlParameter("@LabratoryContactEmail", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryContactEmail });
cmd.Parameters.Add(new SqlParameter("@LabratoryTestRefNumber", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryTestRefNumber });
cmd.Parameters.Add(new SqlParameter("@LabratoryProjectRefNumber", SqlDbType.NVarChar, 255) { Value = labratoryDetailsDbRecord.LabratoryProjectRefNumber });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = labratoryDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = labratoryDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = labratoryDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong LabratoryDetailsGet(IUserDbRecord user,
IConnectionDetails connection,
string name,
out ILabratoryDetailsDbRecord[] labratoryDetailsDbRecords)
{
labratoryDetailsDbRecords = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_LabratoryDetailsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
var list = new List<ILabratoryDetailsDbRecord>();
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar) { Value = name });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
var cd = new LabratoryDetailsDbRecord(reader);
if (!cd.IsInvalidBlank())
{
list.Add(cd);
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
labratoryDetailsDbRecords = list.ToArray();
}
}
public ulong LabratoryDetailsDelete(IUserDbRecord user,
IConnectionDetails connection,
string name,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_LabratoryDetailsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
if (string.IsNullOrEmpty(name))
{
cmd.Parameters.Add(new SqlParameter("@LabratoryName", SqlDbType.NVarChar, 255) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@LabratoryName", SqlDbType.NVarChar, 255) { Value = name });
}
//cmd.Parameters.Add(new SqlParameter("@LabratoryName", SqlDbType.NVarChar, 255) { Value = string.IsNullOrEmpty(name) ? DBNull.Value : name });
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
errorString = (string)errorMessageParam.Value;
}
}
finally
{
cmd.Connection.Dispose();
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
}
}

View File

@@ -0,0 +1,58 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.TestSetups;
namespace DbAPI.TestSetups
{
/// <summary>
/// defines functions to create, retrieve, update, delete graphs
/// </summary>
public interface ICalculatedChannels
{
/// <summary>
/// removes calculated channel from database
/// </summary>
/// <param name="user">user committing delete</param>
/// <param name="connection">connection over which to delete</param>
/// <param name="calculatedChannelId">database id of calculated channel to delete</param>
/// <returns></returns>
ulong CalculatedChannelsDelete(IUserDbRecord user,
IConnectionDetails connection,
int calculatedChannelId);
/// <summary>
/// retrieves all CalculatedChannel records matching search criteria
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="calculatedChannelId">database id of calculated channel (can be null)</param>
/// <param name="testSetupName">test setup calculated channel(s) belong to (can be empty)</param>
/// <param name="records">all matching records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CalculatedChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int? calculatedChannelId,
string testSetupName,
out ICalculatedChannelRecord[] records);
/// <summary>
/// inserts a new calculated channel into the database
/// original record is modified with database id after insert is complete
/// </summary>
/// <param name="user">user adding record</param>
/// <param name="connection">connection record is being added on</param>
/// <param name="record">record being added</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CalculatedChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref ICalculatedChannelRecord record);
/// <summary>
/// updates calculated channel in the database
/// </summary>
/// <param name="user">user updating record</param>
/// <param name="connection">connection record is being updated on</param>
/// <param name="record">record to be updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CalculatedChannelsUpdate(IUserDbRecord user,
IConnectionDetails connection,
ICalculatedChannelRecord record);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,418 @@
using System.Collections.Generic;
using DbAPI.Connections;
using DbAPI.Errors;
using DTS.Common.Classes.TestSetups;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.TestSetups;
using System.Data;
using System.Data.SqlClient;
using System;
using DbAPI.Logging;
using System.Diagnostics;
using DTS.Common;
namespace DbAPI.TestSetups
{
/// <summary>
/// Handles RegionsOfInterest functions
/// </summary>
internal class RegionsOfInterest : IRegionsOfInterest
{
/// <summary>
/// Removes records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <returns></returns>
public ulong RegionsOfInterestDelete(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId)
{
return TestSetupROIsDelete(user, connection, testSetupId);
}
/// <summary>
/// Inserts records into the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="regionOfInterest">The class that is split between the TestSetupROIs and ROIPeriodChannels tables</param>
/// <returns></returns>
public ulong RegionsOfInterestInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupId,
DTS.Common.Interface.RegionOfInterest.IRegionOfInterest regionOfInterest)
{
var hResult = TestSetupROIsInsert(user, connection, testSetupId, regionOfInterest, out int testSetupROIId);
if (hResult == ErrorCodes.ERROR_SUCCESS && testSetupROIId > 0)
{
var channelIndex = 0;
foreach (var channelId in regionOfInterest.ChannelIds)
{
if( channelIndex >= regionOfInterest.ChannelNames.Length) { continue; }
var channelName = regionOfInterest.ChannelNames[channelIndex];
hResult = ROIPeriodChannelsInsert(user, connection, clientDbVersion, testSetupROIId, channelName, channelId);
if (hResult != ErrorCodes.ERROR_SUCCESS)
{
return hResult;
}
channelIndex++;
}
return ErrorCodes.ERROR_SUCCESS;
}
else
{
return ErrorCodes.ERROR_UNKNOWN;
}
}
/// <summary>
/// Gets records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="records">The array of records combined from the TetSetupROIs and ROIPeriodChannels tables</param>
/// <returns></returns>
public ulong RegionsOfInterestGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupId,
out DTS.Common.Interface.RegionOfInterest.IRegionOfInterest[] records)
{
records = new DTS.Common.Interface.RegionOfInterest.IRegionOfInterest[0];
var list = new List<DTS.Common.Interface.RegionOfInterest.IRegionOfInterest>();
TestSetupROIsGet(user, connection, testSetupId, out var testSetupROIRecords);
foreach (var testSetupROIRecord in testSetupROIRecords)
{
ROIPeriodChannelsGet(user, connection, clientDbVersion, testSetupROIRecord.TestSetupROIId, out var roiPeriodChannelRecords);
var channelNameList = new List<string>();
var channelIdList = new List<long>();
foreach (var roiPeriodChannelRecord in roiPeriodChannelRecords)
{
var serialNumberIndex = roiPeriodChannelRecord.ChannelName.LastIndexOf("\\");
if (serialNumberIndex > -1)
{
var serialNumber = roiPeriodChannelRecord.ChannelName.Substring(serialNumberIndex + 1);
var hardwareChannelName = roiPeriodChannelRecord.ChannelName.Substring(0, serialNumberIndex);
var newChannelName = RegionOfInterest.GetChanName(serialNumber, hardwareChannelName);
channelNameList.Add(newChannelName);
}
else
{
channelNameList.Add(roiPeriodChannelRecord.ChannelName);
}
channelIdList.Add(roiPeriodChannelRecord.ChannelId);
}
list.Add(new RegionOfInterest()
{
Suffix = testSetupROIRecord.Suffix,
Start = testSetupROIRecord.ROIStart,
End = testSetupROIRecord.ROIEnd,
IsEnabled = testSetupROIRecord.IsEnabled,
IsDefault = testSetupROIRecord.IsDefault,
ChannelNames = channelNameList.ToArray(),
ChannelIds = channelIdList.ToArray()
});
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Removes records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <returns></returns>
public ulong TestSetupROIsDelete(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestSetupROIsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = testSetupId });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
#endregion params
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, $"sp_TestSetupROIsDelete failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, $"sp_TestSetupROIsDelete failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// Inserts records into the TestSetupROIs table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="regionOfInterest">The class that will have a portion stored in the TestSetupROIs table</param>
/// <param name="testSetupROIId">The new value of the Primary key of the TestSetupROIs table</param>
/// <returns></returns>
public ulong TestSetupROIsInsert(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId,
DTS.Common.Interface.RegionOfInterest.IRegionOfInterest regionOfInterest,
out int testSetupROIId)
{
testSetupROIId = 0;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == regionOfInterest)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestSetupROIsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = testSetupId });
cmd.Parameters.Add(new SqlParameter("@Suffix", SqlDbType.NVarChar, 50) { Value = regionOfInterest.Suffix });
cmd.Parameters.Add(new SqlParameter("@ROIStart", SqlDbType.Float) { Value = regionOfInterest.Start });
cmd.Parameters.Add(new SqlParameter("@ROIEnd", SqlDbType.Float) { Value = regionOfInterest.End });
cmd.Parameters.Add(new SqlParameter("@IsEnabled", SqlDbType.Bit) { Value = regionOfInterest.IsEnabled });
cmd.Parameters.Add(new SqlParameter("@IsDefault", SqlDbType.Bit) { Value = regionOfInterest.IsDefault });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, errorMessageParam.Value.ToString());
}
else
{
//Return the new id so that it can be used to enter this ROI period's channels into the ROIPeriodChannels table
testSetupROIId = int.Parse(newIdParam.Value.ToString());
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Gets records from the TestSetupROIs table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="records">The array of records from the TestSetupROIs table</param>
/// <returns></returns>
public ulong TestSetupROIsGet(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId,
out ITestSetupROIRecord[] records)
{
records = new ITestSetupROIRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestSetupROIsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.BigInt) { Value = testSetupId });
var reader = cmd.ExecuteReader();
var list = new List<TestSetupROIsRecord>();
while (reader.Read())
{
list.Add(new TestSetupROIsRecord(reader));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, $"sp_TestSetupROIsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// Inserts records into the ROIPeriodChannels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupROIId">The value of the Primary key of the TestSetupROIs table</param>
/// <param name="channelName">The name of a channel to be stored in the ROIPeriodChannels table</param>
/// <param name="channelId">The id of a channel to be stored in the ROIPeriodChannels table</param>
/// <returns></returns>
public ulong ROIPeriodChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupROIId,
string channelName,
long channelId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (testSetupROIId == 0 || null == channelName)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
SqlCommand cmd;
var storedProcedureVersionToUse = 0;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion,
"sp_ROIPeriodChannelsInsert", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@TestSetupROIId", SqlDbType.Int) { Value = testSetupROIId });
cmd.Parameters.Add(new SqlParameter("@ChannelName", SqlDbType.NVarChar, 4000) { Value = channelName });
if (storedProcedureVersionToUse >= Constants.ROIPERIODCHANNELS_CHANNELID_DB_VERSION)
{
cmd.Parameters.Add(new SqlParameter("@ChannelId", SqlDbType.BigInt) { Value = channelId });
}
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, errorMessageParam.Value.ToString());
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Gets records from the ROIPeriodChannels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupROIId">The value of the Primary key of the TestSetupROIs table</param>
/// <param name="roiPeriodChannelRecords">The array of records from the ROIPeriodChannels table</param>
/// <returns></returns>
public ulong ROIPeriodChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupROIId,
out IROIPeriodChannelRecord[] roiPeriodChannelRecords)
{
roiPeriodChannelRecords = new IROIPeriodChannelRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
SqlCommand cmd;
var storedProcedureVersionToUse = 0;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion,
"sp_ROIPeriodChannelsGet", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TestSetupROIId", SqlDbType.BigInt) { Value = testSetupROIId });
var reader = cmd.ExecuteReader();
var list = new List<ROIPeriodChannelRecord>();
while (reader.Read())
{
var newROIPeriodChannelRecord = new ROIPeriodChannelRecord(reader, storedProcedureVersionToUse);
var cleanROIPeriodChannelName = RegionOfInterest.RemoveAssignedByIDFromHardwareString(newROIPeriodChannelRecord.ChannelName);
cleanROIPeriodChannelName = RegionOfInterest.RemoveParentDASName(cleanROIPeriodChannelName);
newROIPeriodChannelRecord.ChannelName = cleanROIPeriodChannelName;
list.Add(newROIPeriodChannelRecord);
}
roiPeriodChannelRecords = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"sp_TestSetupROIsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
}
}

View File

@@ -0,0 +1,47 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Graphs;
namespace DbAPI.TestSetups
{
/// <summary>
/// defines functions to create, retrieve, update, delete graphs
/// </summary>
public interface IGraphs
{
/// <summary>
/// retrieves all graph records matching search criteria
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="graphId">graph id to retrieve (can be null)</param>
/// <param name="testSetupId">test setup graph belongs to</param>
/// <param name="records">all matching records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GraphsGet(IUserDbRecord user, IConnectionDetails connection, int? graphId, int? testSetupId, out IGraphRecord[] records);
/// <summary>
/// updates a record in the database
/// </summary>
/// <param name="user">user updating record</param>
/// <param name="connection">connection record is being updated on</param>
/// <param name="record">record to update</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GraphsUpdate(IUserDbRecord user, IConnectionDetails connection, IGraphRecord record);
/// <summary>
/// inserts a record into the db, updates GraphId of record after insert with database id
/// </summary>
/// <param name="user">user inserting record</param>
/// <param name="connection">connection record is being inserted on</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GraphsInsert(IUserDbRecord user, IConnectionDetails connection, ref IGraphRecord record);
/// <summary>
/// removes a record from the db
/// </summary>
/// <param name="user">user removing record</param>
/// <param name="connection">connection record is being removed on</param>
/// <param name="graphId">database id of record being removed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GraphsDelete(IUserDbRecord user, IConnectionDetails connection, int graphId);
}
}

View File

@@ -0,0 +1,949 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes.Channels;
using DTS.Common.Interface.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using DTS.Common.Interface.Channels;
using DTS.Common.Classes.Groups.ChannelSettings;
using DTS.Common.Enums.Channels;
using DTS.Common.Interface.Channels.ChannelCodes;
using DTS.Common.Classes.ChannelCodes;
using DTS.Common.Classes;
using DTS.Common;
using DTS.Common.Enums.DASFactory;
namespace DbAPI.Channels
{
/// <summary>
/// Handles channel functions
/// </summary>
internal class Channels : IChannels
{
/// <summary>
/// insert a new channel code, channel code is modified with a new id if successful
/// </summary>
/// <param name="user">user submitting request</param>
/// <param name="connection">connection being submitted on</param>
/// <param name="channelCode">channel code to insert</param>
/// <param name="lookup">mapping of code type to code type integer</param>
/// <param name="id">new id of channel code record inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelCodesInsert(IUserDbRecord user, IConnectionDetails connection,
IReadOnlyDictionary<ChannelEnumsAndConstants.ChannelCodeType, short> lookup, IChannelCode channelCode,
out int id)
{
id = -1;
if (null == channelCode) { return ErrorCodes.ERROR_MISSING_PARAMETER; }
if (string.IsNullOrEmpty(channelCode.Code) || string.IsNullOrEmpty(channelCode.Name))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelCodesInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar, 255) { Value = channelCode.Code });
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = channelCode.Name });
cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.Int) { Value = lookup[channelCode.CodeType] });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessage);
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
_ = cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesInsert - Error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
if (DBNull.Value.Equals(newId.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesInsert - Error, null new id");
return ErrorCodes.ERROR_UNKNOWN;
}
id = Convert.ToInt32(newId.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesInsert - Error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// Update a channel record in the database
/// </summary>
/// <param name="user">user committing change</param>
/// <param name="connection">connection change is committed on</param>
/// <param name="channelCode">channel code being record being updated</param>
/// <param name="lookup">mapping of code type to code type integer</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelCodesUpdate(IUserDbRecord user, IConnectionDetails connection,
IReadOnlyDictionary<ChannelEnumsAndConstants.ChannelCodeType, short> lookup, IChannelCode channelCode)
{
if (null == channelCode) { return ErrorCodes.ERROR_MISSING_PARAMETER; }
if (string.IsNullOrEmpty(channelCode.Code) || string.IsNullOrEmpty(channelCode.Name))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelCodesUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = channelCode.Id });
cmd.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar, 255) { Value = channelCode.Code });
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = channelCode.Name });
cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.Int) { Value = lookup[channelCode.CodeType] });
var errorNumber =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessage);
_ = cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesInsert - Error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesInsert - Error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// deletes matching channel codes
/// </summary>
/// <param name="user">user making deletes</param>
/// <param name="connection">connection to delete on</param>
/// <param name="id">id of channel code</param>
/// <param name="code">code of matching channel codes (can be null)</param>
/// <param name="name">name of matching channel codes (can be null)</param>
/// <param name="codeType">code type of matching channel codes (can be null)</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelCodesDelete(IUserDbRecord user,
IConnectionDetails connection,
int? id,
string code,
string name,
int? codeType)
{
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelCodesDelete");
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null != id)
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = (int)id });
}
else { cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = null }); }
cmd.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar, 255) { Value = code });
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = name });
if (null == codeType)
{
cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.Int) { Value = null });
}
else { cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.Int) { Value = (int)codeType }); }
var errorNumber =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessage);
_ = cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesDelete - Error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelCodesDelete error - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// retrieves all matching channel code types (int identifier and string identifier)
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="codeType">code type (use null for all)</param>
/// <param name="id">id (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelCodeTypesGet(IUserDbRecord user,
IConnectionDetails connection,
short? id,
string codeType,
out Tuple<short, string>[] records)
{
records = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelCodeTypeGet");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null == id)
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.TinyInt) { Value = null });
}
else
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.TinyInt) { Value = (short)id });
}
cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.NVarChar, 50) { Value = codeType });
var reader = cmd.ExecuteReader();
var list = new List<Tuple<short, string>>();
while (reader.Read())
{
var itemId = Utility.GetShort(reader, "Id");
var cType = Utility.GetString(reader, "CodeType");
list.Add(new Tuple<short, string>(itemId, cType));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelCodeTypesGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// retrieves all matching channel codes
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="Id">id of channel code (use null for all)</param>
/// <param name="code">code of channel code (use null for all)</param>
/// <param name="name">name of channel code (use null for all)</param>
/// <param name="codeType">code type of channel code (use null for all)</param>
/// <param name="channelTypeLookup">lookup of a short to a string for a channel code type</param>
/// <param name="records">matching records</param>
/// <returns>0 (ERROR SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelCodesGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string code,
string name,
ChannelEnumsAndConstants.ChannelCodeType? codeType,
IReadOnlyDictionary<short, string> channelTypeLookup,
out IChannelCode[] records
)
{
records = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == channelTypeLookup)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelCodesGet");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null == Id)
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = null });
}
else { cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = (int)Id }); }
cmd.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar, 255) { Value = code });
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = name });
if (null == codeType)
{
cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.SmallInt) { Value = null });
}
else { cmd.Parameters.Add(new SqlParameter("@CodeType", SqlDbType.SmallInt) { Value = (short)codeType }); }
var reader = cmd.ExecuteReader();
var list = new List<IChannelCode>();
while (reader.Read())
{
list.Add(new ChannelCode(reader, channelTypeLookup));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelCodesGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// updates the default value for a channel setting
/// </summary>
/// <param name="user">user making update</param>
/// <param name="connection">connection update is being made on</param>
/// <param name="settingId">setting id to update</param>
/// <param name="defaultValue">new value for setting</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelSettingsUpdate(IUserDbRecord user,
IConnectionDetails connection,
int settingId,
string defaultValue)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelSettingsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = settingId });
cmd.Parameters.Add(new SqlParameter("@DefaultValue", SqlDbType.NVarChar, 255) { Value = defaultValue });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
var reader = cmd.ExecuteReader();
var o = errorNumber.Value;
if (!DBNull.Value.Equals(o) && 0 != Convert.ToInt32(o))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelSettingsUpdate failed: {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsUpdate failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// retrieves all channel settings from the db for a given channel
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="settingId">channel id to match (allows null)</param>
/// <param name="settingName">setting name to match (allows null/empty)</param>
/// <param name="records">matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong ChannelSettingsGet(IUserDbRecord user,
IConnectionDetails connection,
int? settingId,
string settingName,
out IChannelSettingRecord[] records)
{
records = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, Database.Database.GetStoredProcedureVersionCached(connection, "sp_ChannelSettingsGet"));
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null == settingId)
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = null });
}
else
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = (int)settingId });
}
cmd.Parameters.Add(new SqlParameter("@SettingName", SqlDbType.NVarChar, 255) { Value = settingName });
var reader = cmd.ExecuteReader();
var list = new List<IChannelSettingRecord>();
while (reader.Read())
{
list.Add(new ChannelSettingRecord(reader));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// removes group channel settings from the db for a given channel
/// </summary>
/// <param name="user">user requesting changes</param>
/// <param name="connection">connection changes are being made on</param>
/// <param name="channelId">channel settings belong to</param>
/// <param name="settingId">setting which to delete (use null to delete all settings)</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GroupChannelSettingsDelete(IUserDbRecord user,
IConnectionDetails connection,
long channelId,
int? settingId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupChannelSettingsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ChannelId", SqlDbType.BigInt) { Value = channelId });
if (null != settingId)
{
cmd.Parameters.Add(new SqlParameter("@SettingId", SqlDbType.Int) { Value = (int)settingId });
}
else
{
cmd.Parameters.Add(new SqlParameter("@SettingId", SqlDbType.Int) { Value = null });
}
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
var reader = cmd.ExecuteReader();
var o = errorNumber.Value;
if (!DBNull.Value.Equals(o) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsDelete failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsDelete failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// Inserts a new channel setting record into db
/// </summary>
/// <param name="user">user inserting record</param>
/// <param name="connection">connection record is being inserted on</param>
/// <param name="clientDbVersion">connection client db version</param>
/// <param name="channelId">channel setting belongs to</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GroupChannelSettingsInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
long channelId,
IGroupChannelSettingRecord record)
{
SqlCommand cmd;
var storedProcedureVersionToUse = 0;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion,
"sp_GroupChannelSettingsInsert", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ChannelId", SqlDbType.BigInt) { Value = channelId });
cmd.Parameters.Add(new SqlParameter("@SettingId", SqlDbType.Int) { Value = record.SettingId });
cmd.Parameters.Add(new SqlParameter("@SettingValue", SqlDbType.NVarChar, 255) { Value = record.SettingValue });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
var reader = cmd.ExecuteReader();
var o = errorNumber.Value;
if (!DBNull.Value.Equals(o) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsInsert failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsInsert failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// returns all channel settings for a given channel
/// </summary>
/// <param name="user">user making request</param>
/// <param name="clientDbVersion">calling client's database version</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="channelIdList">list of channels for the request</param>
/// <param name="records">all matching channel settings</param>
/// <param name="errors">any errors encountered while retrieving group channel settings</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GroupChannelSettingsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
List<long> channelIdList,
out IGroupChannelSettingRecord[] records,
out string[] errors)
{
errors = new string[0];
records = new IGroupChannelSettingRecord[0];
var storedProcedureVersionToUse = 0;
SqlCommand cmd;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion,
"sp_GroupChannelSettingsGet", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
cmd.CommandType = CommandType.StoredProcedure;
try
{
var list = new List<IGroupChannelSettingRecord>();
if (storedProcedureVersionToUse < Constants.BULK_GROUPCHANNELSETTINGS_GET_DB_VERSION)
{
//Call the old procedure that takes only one channel ID
foreach (var channelId in channelIdList)
{
if (ErrorCodes.ERROR_SUCCESS != ret) { return ret; }
//we can re-enter here, so clear the parameters just for simplicity
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@ChannelId", SqlDbType.Int) { Value = channelId });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new GroupChannelSettingRecord(reader, storedProcedureVersionToUse) { ChannelId = channelId });
}
//http://manuscript.dts.local/f/cases/35503/Unable-to-add-a-test-setup-with-attached-database
//close the reader
reader.Close();
}
}
else
{
//Call the new procedure that takes a table of channel IDs
using (var table = new DataTable())
{
table.Columns.Add("Item", typeof(string));
foreach (var channelId in channelIdList)
{
table.Rows.Add(channelId.ToString());
}
var pList = new SqlParameter("@ChannelIdList", SqlDbType.Structured);
pList.TypeName = "dbo.StringList";
pList.Value = table;
cmd.Parameters.Add(pList);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new GroupChannelSettingRecord(reader, storedProcedureVersionToUse));
}
}
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelSettingsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
public ulong ChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IChannelDbRecord channel)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = channel.GroupId });
cmd.Parameters.Add(new SqlParameter("@IsoCode", SqlDbType.NVarChar, 50) { Value = channel.IsoCode ?? "" });
cmd.Parameters.Add(new SqlParameter("@IsoChannelName", SqlDbType.NVarChar, 255) { Value = channel.IsoChannelName ?? "" });
cmd.Parameters.Add(new SqlParameter("@UserCode", SqlDbType.NVarChar, 50) { Value = channel.UserCode ?? "" });
cmd.Parameters.Add(new SqlParameter("@UserChannelName", SqlDbType.NVarChar, 255) { Value = channel.UserChannelName ?? "" });
object dasId = null;
if (channel.DASId > 0 && channel.DASChannelIndex >= 0)
{
dasId = channel.DASId;
}
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = dasId });
cmd.Parameters.Add(new SqlParameter("@DASChannelIndex", SqlDbType.Int) { Value = channel.DASChannelIndex });
cmd.Parameters.Add(new SqlParameter("@GroupChannelOrder", SqlDbType.Int) { Value = channel.GroupChannelOrder });
cmd.Parameters.Add(new SqlParameter("@TestSetupOrder", SqlDbType.Int) { Value = channel.TestSetupOrder });
object sensorId = null;
if (channel.SensorId > 0)
{
sensorId = channel.SensorId;
}
cmd.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int) { Value = sensorId });
cmd.Parameters.Add(new SqlParameter("@Disabled", SqlDbType.Bit) { Value = channel.Disabled });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = channel.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 255) { Value = channel.LastModifiedBy });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error,
LogManager.LogEvents.TestSetups, $"ChannelsInsert error - {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
channel.Id = Convert.ToInt64(newId.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelsInsert error: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
public ulong ChannelsUpdate(IUserDbRecord user,
IConnectionDetails connection,
IChannelDbRecord channel)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.BigInt) { Value = channel.Id });
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = channel.GroupId });
cmd.Parameters.Add(new SqlParameter("@IsoCode", SqlDbType.NVarChar, 50) { Value = channel.IsoCode });
cmd.Parameters.Add(new SqlParameter("@IsoChannelName", SqlDbType.NVarChar, 255) { Value = channel.IsoChannelName });
cmd.Parameters.Add(new SqlParameter("@UserCode", SqlDbType.NVarChar, 50) { Value = channel.UserCode });
cmd.Parameters.Add(new SqlParameter("@UserChannelName", SqlDbType.NVarChar, 255) { Value = channel.UserChannelName });
object dasId = null;
if (channel.DASId > 0)
{
dasId = channel.DASId;
}
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = dasId });
cmd.Parameters.Add(new SqlParameter("@DASChannelIndex", SqlDbType.Int) { Value = channel.DASChannelIndex });
cmd.Parameters.Add(new SqlParameter("@GroupChannelOrder", SqlDbType.Int) { Value = channel.GroupChannelOrder });
cmd.Parameters.Add(new SqlParameter("@TestSetupOrder", SqlDbType.Int) { Value = channel.TestSetupOrder });
object sensorId = null;
if (channel.SensorId > 0)
{
sensorId = channel.SensorId;
}
cmd.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int) { Value = sensorId });
cmd.Parameters.Add(new SqlParameter("@Disabled", SqlDbType.Bit) { Value = channel.Disabled });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = channel.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 255) { Value = channel.LastModifiedBy });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups,
$"ChannelsUpdate {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
cmd.ExecuteNonQuery();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"ChannelsUpdate {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong ChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
long? channelId,
int? groupId,
int? dasId,
int? sensorId,
int? testSetupId,
string testSetupName,
out IChannelDbRecord[] channels)
{
channels = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var storedProcedureVersionToUse = 0;
SqlCommand cmd;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion, "sp_ChannelsGet", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
var list = new List<IChannelDbRecord>();
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = channelId });
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = groupId });
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = dasId });
cmd.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int) { Value = sensorId });
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = testSetupId });
cmd.Parameters.Add(new SqlParameter("@TestSetupName", SqlDbType.NVarChar, 255) { Value = testSetupName });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
//33192 Hide the TSR AIR Humidity channel
var newDbRecord = new ChannelDbRecord(reader);
if (newDbRecord.UserChannelName.EndsWith(DFConstantsAndEnums.USER_CHANNEL_NAME_HUMIDITY)) { continue; }
list.Add(newDbRecord);
}
channels = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong ChannelsDelete(IUserDbRecord user,
IConnectionDetails connection,
long id,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_ChannelsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.BigInt) { Value = id });
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = null });
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = null });
cmd.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int) { Value = null });
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = null });
cmd.Parameters.Add(new SqlParameter("@TestSetupName", SqlDbType.NVarChar, 255) { Value = null });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value)
{
if (Convert.ToInt32(errorNumber.Value) != 0)
{
errorNumberULong = Convert.ToUInt64(errorNumber.Value);
errorString = (string)errorMessage.Value;
}
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
}
}

View File

@@ -0,0 +1,91 @@
using DbAPI.Connections;
using DTS.Common.Classes;
using DTS.Common.Interface.Database;
using System;
using System.Data;
using System.Data.SqlClient;
namespace DbAPI.User
{
/// <summary>
/// Basic implementation of <see cref="IUser"/>
/// <inheritdoc cref="IUser"/>
/// </summary>
internal class User : IUserDbRecord
{
public int ID { get; set; }
public string UserName { get; set; }
public string DisplayName { get; set; }
public string Password { get; set; }
public short Role { get; set; }
public DateTime LastModified { get; set; }
public string LastModifiedBy { get; set; }
public bool LocalOnly { get; set; }
public User(int id, string user, string display, string pwd, short role, DateTime lastModified, string lastModifiedBy, bool local)
{
ID = id;
UserName = user;
DisplayName = display;
Password = pwd;
Role = role;
LastModified = lastModified;
LastModifiedBy = lastModifiedBy;
LocalOnly = local;
}
internal static ulong GetUser(IConnectionDetails connection, out IUserDbRecord usr, string userName)
{
usr = null;
var res = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_UsersGetId");
if (res != Errors.ErrorCodes.ERROR_SUCCESS)
{
return Errors.ErrorCodes.ERROR_ACCESS_DENIED;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@UserName", SqlDbType.NVarChar, 255) { Value = userName });
var newId = new SqlParameter("@UserId", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
var reader = cmd.ExecuteReader();
if (DBNull.Value.Equals(newId.Value))
{
return Errors.ErrorCodes.ERROR_LOGINFAILED;
}
var id = Convert.ToInt32(newId.Value);
if (0 >= id) { return Errors.ErrorCodes.ERROR_LOGINFAILED; }
reader.Close();
cmd.Parameters.Clear();
cmd.CommandText = "sp_UsersGet";
cmd.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int) { Value = id });
reader = cmd.ExecuteReader();
if (!reader.Read()) { return Errors.ErrorCodes.ERROR_UNKNOWN; }
var thisid = Utility.GetInt(reader, "ID");
var uname = Utility.GetString(reader, "UserName");
var displayName = Utility.GetString(reader, "DisplayName");
var password = Utility.GetString(reader, "password");
var role = Utility.GetShort(reader, "Role");
var lastModified = Utility.GetDateTime(reader, "LastModified", DateTime.MinValue);
var lastModifiedBy = Utility.GetString(reader, "LastModifiedBy");
var local = Utility.GetBool(reader, "LocalOnly");
usr = new User(thisid, uname, displayName, password, role, lastModified, lastModifiedBy, local);
return Errors.ErrorCodes.ERROR_SUCCESS;
}
finally
{
cmd.Connection.Dispose();
}
}
}
}

View File

@@ -0,0 +1,137 @@
{
"version": 3,
"targets": {
".NETFramework,Version=v4.8": {
"DTS.Common/1.0.0": {
"type": "project",
"dependencies": {
"DTS.Common.Licensing": "1.0.0",
"DTS.Common.SharedResource": "1.0.0",
"DTS.Common.Utilities": "1.0.0"
},
"compile": {
"bin/placeholder/DTS.Common.dll": {}
},
"runtime": {
"bin/placeholder/DTS.Common.dll": {}
}
},
"DTS.Common.Licensing/1.0.0": {
"type": "project",
"compile": {
"bin/placeholder/DTS.Common.Licensing.dll": {}
},
"runtime": {
"bin/placeholder/DTS.Common.Licensing.dll": {}
}
},
"DTS.Common.SharedResource/1.0.0": {
"type": "project",
"compile": {
"bin/placeholder/DTS.Common.SharedResource.dll": {}
},
"runtime": {
"bin/placeholder/DTS.Common.SharedResource.dll": {}
}
},
"DTS.Common.Utilities/1.0.0": {
"type": "project",
"compile": {
"bin/placeholder/DTS.Common.Utilities.dll": {}
},
"runtime": {
"bin/placeholder/DTS.Common.Utilities.dll": {}
}
}
}
},
"libraries": {
"DTS.Common/1.0.0": {
"type": "project",
"path": "../../Common/DTS.Common/DTS.Common.csproj",
"msbuildProject": "../../Common/DTS.Common/DTS.Common.csproj"
},
"DTS.Common.Licensing/1.0.0": {
"type": "project",
"path": "../../Common/DTS.Common.Licensing/DTS.Common.Licensing.csproj",
"msbuildProject": "../../Common/DTS.Common.Licensing/DTS.Common.Licensing.csproj"
},
"DTS.Common.SharedResource/1.0.0": {
"type": "project",
"path": "../../Common/DTS.Common.SharedResource/DTS.Common.SharedResource.csproj",
"msbuildProject": "../../Common/DTS.Common.SharedResource/DTS.Common.SharedResource.csproj"
},
"DTS.Common.Utilities/1.0.0": {
"type": "project",
"path": "../../Common/DTS.Common.Utilities/DTS.Common.Utilities.csproj",
"msbuildProject": "../../Common/DTS.Common.Utilities/DTS.Common.Utilities.csproj"
}
},
"projectFileDependencyGroups": {
".NETFramework,Version=v4.8": [
"DTS.Common >= 1.0.0"
]
},
"packageFolders": {
"D:\\Users\\fatashband\\.nuget\\packages\\": {},
"C:\\Program Files (x86)\\ComponentOne\\WPF Edition\\bin\\v5\\": {},
"C:\\Program Files (x86)\\ComponentOne\\WinForms Edition\\bin\\v5\\": {},
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\DTS Projects\\DataPRO\\BRANCH_DEVEL_4_03\\DataPRO\\DbAPI\\DbAPI.csproj",
"projectName": "DbAPI",
"projectPath": "C:\\DTS Projects\\DataPRO\\BRANCH_DEVEL_4_03\\DataPRO\\DbAPI\\DbAPI.csproj",
"packagesPath": "C:\\Users\\john.dowling\\.nuget\\packages\\",
"outputPath": "C:\\DTS Projects\\DataPRO\\BRANCH_DEVEL_4_03\\DataPRO\\DbAPI\\obj\\",
"projectStyle": "PackageReference",
"crossTargeting": true,
"fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
],
"configFilePaths": [
"D:\\Users\\fatashband\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\ComponentOne.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
"net48"
],
"sources": {
"C:\\Program Files (x86)\\ComponentOne\\Packages": {},
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net48": {
"targetAlias": "net48",
"projectReferences": {
"C:\\DTS Projects\\DataPRO\\BRANCH_DEVEL_4_03\\Common\\DTS.Common\\DTS.Common.csproj": {
"projectPath": "C:\\DTS Projects\\DataPRO\\BRANCH_DEVEL_4_03\\Common\\DTS.Common\\DTS.Common.csproj"
}
}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
},
"SdkAnalysisLevel": "9.0.100"
},
"frameworks": {
"net48": {
"targetAlias": "net48",
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\5.0.408\\RuntimeIdentifierGraph.json"
}
}
}
}

View File

@@ -0,0 +1,62 @@
using DbAPI.User;
using DTS.Common.Interface.Database;
using System;
namespace DbAPI.Connections
{
/// <summary>
/// Connection related functions (Connect, Login, GetLoggedInUsers)
/// </summary>
public interface IConnections
{
/// <summary>
/// Used to retrieve all current connections
/// </summary>
/// <returns>all dbs that were successfully connected to</returns>
IConnectionDetails[] GetActiveConnections();
/// <summary>
/// attempts to login user
/// </summary>
/// <param name="connection">Database user belongs to</param>
/// <param name="user">the DataPRO user to log in</param>
/// <param name="hash">the already hashed and salted password value</param>
/// <param name="userObject">[Output]User instance if login was successful</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other returns are errors.
/// ERROR_LOGINFAILED indicates a failed login while ERROR_UNKNOWN indicates an unexpected error</returns>
ulong LoginUserHash(IConnectionDetails connection, string user, string hash, out IUserDbRecord userObject);
/// <summary>
/// attempts to login user
/// </summary>
/// <param name="connection">Database user belongs to</param>
/// <param name="user">the DataPRO user to log in</param>
/// <param name="password">password belonging to user</param>
/// <param name="userObject">[Output]User instance if login was successful</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other returns are errors.
/// ERROR_LOGINFAILED indicates a failed login while ERROR_UNKNOWN indicates an unexpected error</returns>
ulong LoginUser(IConnectionDetails connection, string user, string password, out IUserDbRecord userObject);
/// <summary>
/// Attempts to connect database
/// </summary>
/// <param name="details">connection details for use in connecting database</param>
/// <returns>returns 0 on success (ERROR_SUCCESS), all other values are errors</returns>
ulong ConnectToDb(IConnectionDetails details);
/// <summary>
/// checks whether a user is currently logged in to the given database
/// </summary>
/// <param name="user">user to check</param>
/// <param name="connection">database user should be logged in to</param>
/// <returns>returns true if user is logged in, otherwise false</returns>
bool IsUserLoggedIn(IUserDbRecord user, IConnectionDetails connection);
/// <summary>
/// returns all logged in users on all databases connected
/// </summary>
/// <returns>all logged in users on all databases connected</returns>
Tuple<IUserDbRecord, IConnectionDetails>[] GetLoggedInUsers();
/// <summary>
/// removes all logged in users and all database connections
/// </summary>
void ClearConnections();
}
}

View File

@@ -0,0 +1,62 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Groups.GroupList;
using System.Collections.Generic;
using DTS.Common.Interface.Groups;
using DTS.Common.Classes.Groups;
namespace DbAPI.GroupHardware
{
/// <summary>
/// GroupHardware related functions
/// </summary>
public interface IGroupHardware
{
/// <summary>
/// Inserts a new record in the GroupHardware table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="groupHardware"></param>
/// <param name="newId"></param>
/// <param name="errorMessage"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupHardwareInsert(IUserDbRecord user,
IConnectionDetails connection,
GroupHardwareDbRecord groupHardware,
out int newId,
out string errorMessage);
/// <summary>
/// Gets one or more records from the GroupHardware table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="groupId"></param>
/// <param name="serialNumber"></param>
/// <param name="embedded"></param>
/// <param name="groupHardwareRecords"></param>
/// <returns></returns>
ulong GroupHardwareGet(IUserDbRecord user,
IConnectionDetails connection,
int? groupId,
string serialNumber,
bool? embedded,
out GroupHardwareDbRecord[] groupHardwareRecords);
/// <summary>
/// Deletes an entry in the GroupHardware table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="groupId">Id in the GroupHardware table</param>
/// <param name="dasId">Id in the GroupHardware table</param>
/// <param name="errorString">Error string returned, possibly from sp_GroupsDelete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupHardwareDelete(IUserDbRecord user,
IConnectionDetails connection,
int? groupId,
int? dasId,
out string errorString);
}
}

View File

@@ -0,0 +1,72 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.TestSetups;
namespace DbAPI.TestSetups
{
/// <summary>
/// defines functions to create, retrieve, update, delete graphs
/// </summary>
public interface IRegionsOfInterest
{
/// <summary>
/// Removes records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <returns></returns>
ulong RegionsOfInterestDelete(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId);
/// <summary>
/// Inserts records into the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="regionOfInterest">The class that is split between the TestSetupROIs and ROIPeriodChannels tables</param>
/// <returns></returns>
ulong RegionsOfInterestInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupId,
DTS.Common.Interface.RegionOfInterest.IRegionOfInterest regionOfInterest);
/// <summary>
/// Gets records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="records">The array of records combined from the TetSetupROIs and ROIPeriodChannels tables</param>
/// <returns></returns>
ulong RegionsOfInterestGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupId,
out DTS.Common.Interface.RegionOfInterest.IRegionOfInterest[] records);
ulong TestSetupROIsDelete(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId);
ulong TestSetupROIsInsert(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId,
DTS.Common.Interface.RegionOfInterest.IRegionOfInterest regionOfInterest,
out int testSetupROIId);
ulong TestSetupROIsGet(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId,
out ITestSetupROIRecord[] records);
ulong ROIPeriodChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupROIId,
string channelName,
long channelId);
ulong ROIPeriodChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupROIId,
out IROIPeriodChannelRecord[] roiPeriodChannelRecords);
}
}

View File

@@ -0,0 +1,305 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DbAPI.LabratoryDetails;
using DTS.Common.Interface.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using DTS.Common.Interface.TestMetaData;
using DTS.Common.Classes.TestEngineerDetails;
namespace DbAPI.TestEngineerDetails
{
/// <summary>
/// Handles Test Engineer functions
/// </summary>
internal class TestEngineerDetails : ITestEngineerDetails
{
public ulong TestEngineerDetailsInsert(IUserDbRecord user,
IConnectionDetails connection,
TestEngineerDetailsDbRecord testEngineerDetailsDbRecord,
out int newId,
out string errorString)
{
errorString = string.Empty;
newId = -1;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestEngineerDetailsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@TestEngineerName", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerName });
cmd.Parameters.Add(new SqlParameter("@TestEngineerPhone", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerPhone });
cmd.Parameters.Add(new SqlParameter("@TestEngineerFax", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerFax });
cmd.Parameters.Add(new SqlParameter("@TestEngineerEmail", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerEmail });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = testEngineerDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = testEngineerDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = testEngineerDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
else
{
newId = (int)newIdParam.Value;
}
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong TestEngineerDetailsUpdate(IUserDbRecord user,
IConnectionDetails connection,
TestEngineerDetailsDbRecord testEngineerDetailsDbRecord,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestEngineerDetailsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@TestEngineerName", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerName });
cmd.Parameters.Add(new SqlParameter("@TestEngineerPhone", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerPhone });
cmd.Parameters.Add(new SqlParameter("@TestEngineerFax", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerFax });
cmd.Parameters.Add(new SqlParameter("@TestEngineerEmail", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerEmail });
//cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = testEngineerDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = testEngineerDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = testEngineerDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong TestEngineerDetailsUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
TestEngineerDetailsDbRecord testEngineerDetailsDbRecord,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestEngineerDetailsUpdateInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@TestEngineerName", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerName });
cmd.Parameters.Add(new SqlParameter("@TestEngineerPhone", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerPhone });
cmd.Parameters.Add(new SqlParameter("@TestEngineerFax", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerFax });
cmd.Parameters.Add(new SqlParameter("@TestEngineerEmail", SqlDbType.NVarChar, 255) { Value = testEngineerDetailsDbRecord.TestEngineerEmail });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = testEngineerDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = testEngineerDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = testEngineerDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong TestEngineerDetailsGet(IUserDbRecord user,
IConnectionDetails connection,
string name,
out ITestEngineerDetailsDbRecord[] testEngineerDetailsDbRecords)
{
testEngineerDetailsDbRecords = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestEngineerDetailsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
var list = new List<ITestEngineerDetailsDbRecord>();
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar) { Value = name });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
var cd = new TestEngineerDetailsDbRecord(reader);
if (!cd.IsInvalidBlank())
{
list.Add(cd);
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
testEngineerDetailsDbRecords = list.ToArray();
}
}
public ulong TestEngineerDetailsDelete(IUserDbRecord user,
IConnectionDetails connection,
string name,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestEngineerDetailsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
if (string.IsNullOrEmpty(name))
{
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = name });
}
//cmd.Parameters.Add(new SqlParameter("@TestEngineerName", SqlDbType.NVarChar, 255) { Value = string.IsNullOrEmpty(name) ? null : name });
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
errorString = (string)errorMessageParam.Value;
}
}
finally
{
cmd.Connection.Dispose();
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
}
}

View File

@@ -0,0 +1,68 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using System;
using DTS.Common.Classes.CustomerDetails;
using DTS.Common.Interface.TestMetaData;
namespace DbAPI.CustomerDetails
{
/// <summary>
/// CustomerDetails related functions (GetCustomerDetails, )
/// </summary>
public interface ICustomerDetails
{
/// <summary>
/// Inserts a new record in the CustomerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="customerDetailsDbRecord"></param>
/// <param name="newId">The Id of the new record in the CustomerDetails table</param>
/// <param name="errorString">Error string returned, possibly from sp_CustomerDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CustomerDetailsInsert(IUserDbRecord user,
IConnectionDetails connection,
CustomerDetailsDbRecord customerDetailsDbRecord,
out int newId,
out string errorString);
/// <summary>
/// Updates an existing record in the CustomerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name = "customerDetailsDbRecord"></param>
/// <param name="errorString">Error string returned, possibly from sp_CustomerDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CustomerDetailsUpdate(IUserDbRecord user,
IConnectionDetails connection,
CustomerDetailsDbRecord customerDetailsDbRecord,
out string errorString);
/// <summary>
/// retrieves all customer details matching search criteria
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="name">Name in the CustomerDetails table</param>
/// <param name="customerDetailsDbRecords">null, or records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CustomerDetailsGet(IUserDbRecord user,
IConnectionDetails connection,
string name,
out ICustomerDetailsDbRecord[] customerDetailsDbRecords);
/// <summary>
/// Deletes an entry in the CustomerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="name">Name in the CustomerDetails table</param>
/// <param name="errorString">Error string returned, possibly from sp_CustomerDetailsDelete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong CustomerDetailsDelete(IUserDbRecord user,
IConnectionDetails connection,
string name,
out string errorString);
}
}

View File

@@ -0,0 +1,93 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Tags;
namespace DbAPI.Tags
{
/// <summary>
/// defines functions to create, retrieve, update, delete tags
/// </summary>
public interface ITags
{
/// <summary>
/// inserts a tag assignment record into the database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="tagAssignment">assignment to be committed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TagAssignmentsInsert(IUserDbRecord user,
IConnectionDetails connection,
ITagAssignment tagAssignment);
/// <summary>
/// deletes all matching tags.
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="objectId">object tags assigned to</param>
/// <param name="tagType">the object type</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TagAssignmentsDelete(IUserDbRecord user,
IConnectionDetails connection,
int objectId,
TagTypes tagType);
/// <summary>
/// retrieves all tags that have been assigned to an object type
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="tagType">object type tags are assigned to (use null for all)</param>
/// <param name="tagAssignments">all matching assignments</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TagAssignmentsGet(IUserDbRecord user,
IConnectionDetails connection,
TagTypes? tagType,
out ITagAssignment[] tagAssignments
);
/// <summary>
/// inserts a new tag, modifies tag with new id after insert
/// </summary>
/// <param name="user">user requesting insert</param>
/// <param name="connection">connection tag is being inserted on</param>
/// <param name="tag">tag to insert</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TagsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref ITag tag);
/// <summary>
/// returns id for a given tag text
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="tagText">text associated with tag</param>
/// <param name="id">id of tag (or null if not found)</param>
/// <returns>0 on success, all other values are error codes</returns>
ulong TagsGetId(IUserDbRecord user,
IConnectionDetails connection,
string tagText,
out int? id);
/// <summary>
/// deletes all matching tags
/// </summary>
/// <param name="tagId">id of tag to be deleted</param>
/// <param name="connection">connection tag should be deleted on</param>
/// <param name="user">user requesting delete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TagsDelete(IUserDbRecord user,
IConnectionDetails connection,
int tagId);
/// <summary>
/// retrieves all tags matching search criteria
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is made on</param>
/// <param name="tagId">id of tag to search for (use null to get all tags)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TagsGet(IUserDbRecord user,
IConnectionDetails connection,
int? tagId,
out ITag[] records);
}
}

View File

@@ -0,0 +1,23 @@
namespace DbAPI.SPCaching
{
/// <summary>
/// just a helper class for caching what version of stored procedures to use
/// holds what stored procedure version to use given a client version and a db version
/// once this has been determined we don't need to determine it again ... usually
/// </summary>
public class SPCache
{
/// <summary>
/// application or client version
/// </summary>
public int ClientVersion { get; set; }
/// <summary>
/// database version
/// </summary>
public int DbVersion { get; set; }
/// <summary>
/// version of stored procedure to use
/// </summary>
public int StoredProcedureVersion { get; set; }
}
}

View File

@@ -0,0 +1,43 @@
using DbAPI.Connections;
using DbAPI.User;
using DTS.Common.Interface.Database;
using System;
namespace DbAPI.Database
{
/// <summary>
/// Database related functions (InsertVersion, GetDatabaseVersion)
/// </summary>
public interface IDatabase
{
int GetSQLVersion(IConnectionDetails connection);
/// <summary>
/// retrieves the highest database version for a given database
/// User must be logged into database
/// </summary>
/// <param name="user">DataPRO user retrieving information</param>
/// <param name="connection">Database connection info</param>
/// <param name="version"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_ACCESS_DENIED if user is not logged in</returns>
ulong GetDatabaseVersion(IUserDbRecord user, IConnectionDetails connection, out int version);
/// <summary>
/// inserts a database version record into a given database
/// User must be logged into database
/// does not check if version is already in the database or the relation of the version
/// number to any versions in the database
/// </summary>
/// <param name="user">user inserting new record</param>
/// <param name="connection">database connection details</param>
/// <param name="version">version number to insert</param>
/// <param name="step">step number to insert</param>
/// <param name="date">DateTime to put on the inserted record</param>
/// <param name="remarks">Remarks to record with insert</param>
/// <param name="userField">What user to associate with the insert record (does not have to match any actual users)</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_ACCESS_DENIED if user is not logged in</returns>
ulong InsertDatabaseVersion(IUserDbRecord user, IConnectionDetails connection,
int version, int step, DateTime date, string remarks, string userField);
}
}

View File

@@ -0,0 +1,636 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes.Hardware;
using DTS.Common.Interface.DataRecorders;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using DTS.Common.Interface.Database;
using System.Data.SqlClient;
using DTS.Common.Enums.DASFactory;
using DTS.Common.Classes;
using DTS.Common.Enums.Hardware;
namespace DbAPI.DAS
{
/// <summary>
/// No need to export, this is just an internal implementation of the <see cref="IDataRecorders"/> interface
/// <inheritdoc cref="IDataRecorders"/>
/// </summary>
internal class DataRecorders : IDataRecorders
{
/// <summary>
/// Deletes all channels related to DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="hardwareId"></param>
/// <returns>0 on success, all other values are errors</returns>
public ulong DASChannelsDelete(IUserDbRecord user, IConnectionDetails connection,
string hardwareId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChannelsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@HardwareId", SqlDbType.NVarChar, 50) { Value = hardwareId });
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
var error = Convert.ToInt32(errorNumberParam.Value);
var msg = Convert.ToString(errorMessageParam.Value);
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, $"Failed DASChannelsDelete {error} - {msg}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// inserts das channel record into db. modifies record by updating id after insert
/// </summary>
/// <param name="user">user making insert</param>
/// <param name="connection">connection channel is being inserted on</param>
/// <param name="hardwareId">string identifier for hardware (serialnumber_dastype)</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
public ulong DASChannelsInsert(IUserDbRecord user, IConnectionDetails connection,
string hardwareId,
ref IDASChannelDBRecord record)
{
if (null == record)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (string.IsNullOrWhiteSpace(hardwareId))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChannelsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(
new SqlParameter("@HardwareId", SqlDbType.NVarChar, 50) { Value = hardwareId });
cmd.Parameters.Add(new SqlParameter("@ChannelIdx", SqlDbType.Int) { Value = record.ChannelIdx });
cmd.Parameters.Add(new SqlParameter("@SupportedBridges", SqlDbType.Int) { Value = record.SupportedBridges });
cmd.Parameters.Add(new SqlParameter("@SupportedExcitations", SqlDbType.Int) { Value = record.SupportedExcitations });
cmd.Parameters.Add(new SqlParameter("@DASDisplayOrder", SqlDbType.Int) { Value = record.DASDisplayOrder });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Int) { Value = record.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@SupportedDigitalInputModes", SqlDbType.Int)
{
Value = record.SupportedDigitalInputModes
});
cmd.Parameters.Add(
new SqlParameter("@SupportedSquibFireModes", SqlDbType.Int) { Value = record.SupportedSquibFireModes });
cmd.Parameters.Add(
new SqlParameter("@SupportedDigitalOutputModes", SqlDbType.Int)
{
Value = record.SupportedDigitalOutputModes
});
cmd.Parameters.Add(new SqlParameter("@ModuleSerialNumber", SqlDbType.NVarChar, 16) { Value = record.ModuleSerialNumber });
cmd.Parameters.Add(new SqlParameter("@ModuleArrayIndex", SqlDbType.Int) { Value = record.ModuleArrayIndex });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
var error = Convert.ToInt32(errorNumberParam.Value);
var msg = Convert.ToString(errorMessageParam.Value);
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, $"Failed DASChannelsInsert {error} - {msg}");
return ErrorCodes.ERROR_UNKNOWN;
}
record.DaschannelId = Convert.ToInt32(newIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns DASChannels for given DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="hardwareId">string identifying hardware in the form of DASSerial_DASType
/// (or null for all records)</param>
/// <param name="channels"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
public ulong DASChannelsGet(IUserDbRecord user, IConnectionDetails connection, string hardwareId, out IDASChannelDBRecord[] channels)
{
channels = new IDASChannelDBRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChannelsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
var list = new List<IDASChannelDBRecord>();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@HardwareId", SqlDbType.NVarChar, 50) { Value = hardwareId });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new DASChannelDBRecord(reader));
}
channels = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns all the DAS serials associated with a given parent DAS
/// used for discovering which das are associated with a das in the db for encapsulated/compacted DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="dasSerialNumber"></param>
/// <param name="childrenSerialNumbers"></param>
/// <returns>0 on success, all other values are errors</returns>
public ulong DASChildrenGet(IUserDbRecord user, IConnectionDetails connection, string dasSerialNumber, out string[] childrenSerialNumbers)
{
childrenSerialNumbers = new string[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChildrenGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
var serials = new List<string>();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ParentSerialNumber", SqlDbType.NVarChar) { Value = dasSerialNumber });
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var serial = Utility.GetString(reader, "SerialNumber", string.Empty);
if (!string.IsNullOrWhiteSpace(serial)) { serials.Add(serial); }
}
}
childrenSerialNumbers = serials.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong DASDelete(IUserDbRecord user, IConnectionDetails connection, int DASId, string serialNumber, bool embedded)
{
if (DASId <= 0 && string.IsNullOrEmpty(serialNumber))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
Console.WriteLine($"DASDelete executing sp");
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = DASId });
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = serialNumber });
cmd.Parameters.Add(new SqlParameter("@Embedded", SqlDbType.Bit) { Value = embedded });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
var error = Convert.ToInt32(errorNumber.Value);
var msg = Convert.ToString(errorMessage.Value);
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, $"DeleteDAS failed error: {error} - {msg}");
Console.WriteLine($"DASDelete {error} - {msg}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong DASUpdate(IUserDbRecord user, IConnectionDetails connection, IDASDBRecord das)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = 0 });
cmd.Parameters.Add(
new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = das.SerialNumber });
cmd.Parameters.Add(new SqlParameter("@Type", SqlDbType.Int) { Value = das.DASType });
cmd.Parameters.Add(new SqlParameter("@MaxModules", SqlDbType.Int) { Value = das.MaxModules });
cmd.Parameters.Add(new SqlParameter("@MaxMemory", SqlDbType.BigInt) { Value = das.MaxMemory });
cmd.Parameters.Add(
new SqlParameter("@MaxSampleRate", SqlDbType.Float)
{
Value = Convert.ToDecimal(das.MaxSampleRate)
});
cmd.Parameters.Add(
new SqlParameter("@MinSampleRate", SqlDbType.Float)
{
Value = Convert.ToDecimal(das.MinSampleRate)
});
cmd.Parameters.Add(
new SqlParameter("@FirmwareVersion", SqlDbType.NVarChar, 50) { Value = das.FirmwareVersion });
cmd.Parameters.Add(new SqlParameter("@CalDate", SqlDbType.DateTime) { Value = das.CalDate });
cmd.Parameters.Add(
new SqlParameter("@ProtocolVersion", SqlDbType.Int) { Value = das.ProtocolVersion });
cmd.Parameters.Add(
new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = das.LastModified });
cmd.Parameters.Add(
new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = das.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = das.Version });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = das.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastUsed", SqlDbType.DateTime) { Value = das.LastUsed });
cmd.Parameters.Add(
new SqlParameter("@LastUsedBy", SqlDbType.NVarChar, 50) { Value = das.LastUsedBy });
cmd.Parameters.Add(new SqlParameter("@Connection", SqlDbType.NVarChar, 50) { Value = das.Connection });
cmd.Parameters.Add(new SqlParameter("@Channels", SqlDbType.Int) { Value = das.Channels });
cmd.Parameters.Add(new SqlParameter("@Position", SqlDbType.NVarChar, 50) { Value = das.Position });
cmd.Parameters.Add(
new SqlParameter("@ChannelTypes", SqlDbType.NVarChar, 255)
{
Value = string.Join(",", das.ChannelTypes)
});
cmd.Parameters.Add(new SqlParameter("@Reprogramable", SqlDbType.Bit) { Value = das.IsProgrammable });
cmd.Parameters.Add(
new SqlParameter("@Reconfigurable", SqlDbType.Bit) { Value = das.IsReconfigurable });
cmd.Parameters.Add(new SqlParameter("@IsModule", SqlDbType.Bit) { Value = das.IsModule });
cmd.Parameters.Add(
new SqlParameter("@PositionOnDistributor", SqlDbType.SmallInt)
{
Value = das.PositionOnDistributor
});
cmd.Parameters.Add(
new SqlParameter("@PositionOnChain", SqlDbType.SmallInt) { Value = das.PositionOnChain });
cmd.Parameters.Add(new SqlParameter("@Port", SqlDbType.SmallInt) { Value = das.Port });
cmd.Parameters.Add(new SqlParameter("@ParentDAS", SqlDbType.NVarChar, 50) { Value = null == das.ParentDAS ? string.Empty : das.ParentDAS });
if (das.IsFirstUseValid)
{
if (null == das.FirstUseDate)
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = DFConstantsAndEnums.FIRST_USE_DATE_NOT_SET });
}
else
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = (DateTime)das.FirstUseDate });
}
}
else { cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime) { Value = DBNull.Value }); }
//to avoid confusion, if it's not a stand in it's also not test/group specific
if (null == das.TestId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = (int)das.TestId });
}
if (null == das.GroupId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = (int)das.GroupId });
}
cmd.Parameters.Add(new SqlParameter("@StandIn", SqlDbType.Bit) { Value = das.StandIn });
cmd.Parameters.Add(new SqlParameter("@MaxAAFRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MaxAAFRate) });
SqlParameter newIdParam = null;
newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
throw new Exception((string)errorMessageParam.Value);
}
das.DASId = Convert.ToInt32(newIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// Inserts a DAS record into the db
/// the DASId will be modified before return if insert is successful
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="das"></param>
/// <param name="iDASId">id of das in Db after insert</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_NOACCESS if user is not logged in</returns>
public ulong DASInsert(IUserDbRecord user, IConnectionDetails connection, IDASDBRecord das)
{
if (null == das)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = DbAPI.GetDatabaseVersion(connection, out int serverDbVersion);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
//If we discover DAS that is too new for the version of database being used, don't insert it.
if ((das.DASType == (int)HardwareTypes.SLICE6_AIR_TC) && (serverDbVersion < DTS.Common.Constants.SLICE_TC_DB_VERSION)) { return ErrorCodes.ERROR_UNKNOWN; }
ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(
new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = das.SerialNumber });
cmd.Parameters.Add(new SqlParameter("@Type", SqlDbType.Int) { Value = das.DASType });
cmd.Parameters.Add(new SqlParameter("@MaxModules", SqlDbType.Int) { Value = das.MaxModules });
cmd.Parameters.Add(new SqlParameter("@MaxMemory", SqlDbType.BigInt) { Value = das.MaxMemory });
cmd.Parameters.Add(
new SqlParameter("@MaxSampleRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MaxSampleRate) });
cmd.Parameters.Add(
new SqlParameter("@MinSampleRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MinSampleRate) });
cmd.Parameters.Add(
new SqlParameter("@FirmwareVersion", SqlDbType.NVarChar, 50) { Value = das.FirmwareVersion });
cmd.Parameters.Add(new SqlParameter("@CalDate", SqlDbType.DateTime) { Value = das.CalDate });
cmd.Parameters.Add(new SqlParameter("@ProtocolVersion", SqlDbType.Int) { Value = das.ProtocolVersion });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = das.LastModified });
cmd.Parameters.Add(
new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = das.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = das.Version });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = das.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastUsed", SqlDbType.DateTime) { Value = das.LastUsed });
cmd.Parameters.Add(new SqlParameter("@LastUsedBy", SqlDbType.NVarChar, 50) { Value = null == das.LastUsedBy ? string.Empty : das.LastUsedBy });
cmd.Parameters.Add(new SqlParameter("@Connection", SqlDbType.NVarChar, 50) { Value = das.Connection });
cmd.Parameters.Add(new SqlParameter("@Channels", SqlDbType.Int) { Value = das.Channels });
cmd.Parameters.Add(new SqlParameter("@Position", SqlDbType.NVarChar, 50) { Value = null == das.Position ? string.Empty : das.Position });
cmd.Parameters.Add(
new SqlParameter("@ChannelTypes", SqlDbType.NVarChar, 255)
{
Value = null == das.ChannelTypes ? "" : string.Join(",", das.ChannelTypes)
});
cmd.Parameters.Add(new SqlParameter("@Reprogramable", SqlDbType.Bit) { Value = das.IsProgrammable });
cmd.Parameters.Add(new SqlParameter("@Reconfigurable", SqlDbType.Bit) { Value = das.IsReconfigurable });
cmd.Parameters.Add(new SqlParameter("@IsModule", SqlDbType.Bit) { Value = das.IsModule });
cmd.Parameters.Add(
new SqlParameter("@PositionOnDistributor", SqlDbType.SmallInt) { Value = das.PositionOnDistributor });
cmd.Parameters.Add(
new SqlParameter("@PositionOnChain", SqlDbType.SmallInt) { Value = das.PositionOnChain });
cmd.Parameters.Add(new SqlParameter("@Port", SqlDbType.SmallInt) { Value = das.Port });
cmd.Parameters.Add(new SqlParameter("@ParentDAS", SqlDbType.NVarChar, 50) { Value = null == das.ParentDAS ? string.Empty : das.ParentDAS });
if (das.IsFirstUseValid)
{
if (null == das.FirstUseDate)
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = DFConstantsAndEnums.FIRST_USE_DATE_NOT_SET });
}
else
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = (DateTime)das.FirstUseDate });
}
}
else { cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime) { Value = DBNull.Value }); }
//only standin das are allowed to be test/group specific
if (null == das.TestId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = das.TestId });
}
if (null == das.GroupId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = das.GroupId });
}
cmd.Parameters.Add(new SqlParameter("@StandIn", SqlDbType.Bit) { Value = das.StandIn });
cmd.Parameters.Add(new SqlParameter("@MaxAAFRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MaxAAFRate) });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
throw new Exception((string)errorMessageParam.Value);
}
das.DASId = Convert.ToInt32(newIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns the DAS requested. If no DASId or serial number is specified, returns all DAS
/// user must be logged in
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="DASId">null is allowed, specify an ID or leave null</param>
/// <param name="DASSerial">null and empty string allowed, specify a serial number or leave null</param>
/// <param name="das">das found, can be null or empty</param>
/// <returns></returns>
public ulong DASGet(IUserDbRecord user, IConnectionDetails connection, int clientDbVersion, string DASSerial, string position, out IDASDBRecord[] das)
{
das = null;
var allDAS = new List<IDASDBRecord>();
var storedProcedureVersionToUse = 0;
SqlCommand cmd;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion, "sp_DASGet", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = DASSerial });
cmd.Parameters.Add(new SqlParameter("@Position", SqlDbType.NVarChar, 10) { Value = position });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
allDAS.Add(new DASDBRecord(reader));
}
reader.Close();
das = allDAS.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48</TargetFrameworks>
<Configurations>Debug;Release</Configurations>
<Platforms>AnyCPU;x64;x86</Platforms>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net452|x64'">
<DocumentationFile></DocumentationFile>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\DTS.Common\DTS.Common.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Security" />
<Reference Include="System.Web.Extensions" />
</ItemGroup>
<ItemGroup>
<Folder Include="Channels\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,216 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Channels;
using System;
using DTS.Common.Enums.Channels;
using DTS.Common.Interface.Channels.ChannelCodes;
using System.Collections.Generic;
namespace DbAPI.Channels
{
/// <summary>
/// Channel related functions (GetChannels, )
/// </summary>
public interface IChannels
{
/// <summary>
/// insert a new channel code, channel code is modified with a new id if successful
/// </summary>
/// <param name="user">user submitting request</param>
/// <param name="connection">connection being submitted on</param>
/// <param name="channelCode">channel code to insert</param>
/// <param name="lookup">mapping of code type string to code type integer</param>
/// <param name="id">id of newly inserted database record</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelCodesInsert(IUserDbRecord user, IConnectionDetails connection,
IReadOnlyDictionary<ChannelEnumsAndConstants.ChannelCodeType, short> lookup, IChannelCode channelCode,
out int id);
/// <summary>
/// Update a channel record in the database
/// </summary>
/// <param name="user">user committing change</param>
/// <param name="connection">connection change is committed on</param>
/// <param name="channelCode">channel code being record being updated</param>
/// <param name="lookup">mapping of code type string to code type integer</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelCodesUpdate(IUserDbRecord user, IConnectionDetails connection,
IReadOnlyDictionary<ChannelEnumsAndConstants.ChannelCodeType, short> lookup, IChannelCode channelCode);
/// <summary>
/// deletes matching channel codes
/// </summary>
/// <param name="user">user making deletes</param>
/// <param name="connection">connection to delete on</param>
/// <param name="id">id of channel code</param>
/// <param name="code">code of matching channel codes (can be null)</param>
/// <param name="name">name of matching channel codes (can be null)</param>
/// <param name="codeType">code type of matching channel codes (can be null)</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelCodesDelete(IUserDbRecord user,
IConnectionDetails connection,
int? id,
string code,
string name,
int? codeType);
/// <summary>
/// retrieves all matching channel code types (int identifier and string identifier)
/// </summary>
/// <param name="user">user making request</param>
/// <param name="codeType">code type (use null for all)</param>
/// <param name="id">id (use null for all)</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelCodeTypesGet(IUserDbRecord user,
IConnectionDetails connection,
short? id,
string codeType,
out Tuple<short, string>[] records);
/// <summary>
/// retrieves all matching channel codes
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="Id">id of channel code (use null for all)</param>
/// <param name="code">code of channel code (use null for all)</param>
/// <param name="name">name of channel code (use null for all)</param>
/// <param name="codeType">code type of channel code (use null for all)</param>
/// <param name="channelTypeLookup">matches a channel code type to a short id for that type</param>
/// <param name="records">matching records</param>
/// <returns>0 (ERROR SUCCESS) on success, all other values are error codes</returns>
ulong ChannelCodesGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string code,
string name,
ChannelEnumsAndConstants.ChannelCodeType? codeType,
IReadOnlyDictionary<short, string> channelTypeLookup,
out IChannelCode[] records
);
/// <summary>
/// updates the default value for a channel setting
/// </summary>
/// <param name="user">user making update</param>
/// <param name="connection">connection update is being made on</param>
/// <param name="settingId">setting id to update</param>
/// <param name="defaultValue">new value for setting</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelSettingsUpdate(IUserDbRecord user,
IConnectionDetails connection,
int settingId,
string defaultValue);
/// <summary>
/// retrieves all channel settings from the db for a given channel
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="settingId">channel id to match (allows null)</param>
/// <param name="settingName">setting name to match (allows null/empty)</param>
/// <param name="records">matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelSettingsGet(IUserDbRecord user,
IConnectionDetails connection,
int? settingId,
string settingName,
out IChannelSettingRecord[] records);
/// <summary>
/// removes group channel settings from the db for a given channel
/// </summary>
/// <param name="user">user requesting changes</param>
/// <param name="connection">connection changes are being made on</param>
/// <param name="channelId">channel settings belong to</param>
/// <param name="settingId">setting which to delete (use null to delete all settings)</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupChannelSettingsDelete(IUserDbRecord user,
IConnectionDetails connection,
long channelId,
int? settingId);
/// <summary>
/// Inserts a new channel setting record into db
/// </summary>
/// <param name="user">user inserting record</param>
/// <param name="connection">connection record is being inserted on</param>
/// <param name="channelId">channel setting belongs to</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupChannelSettingsInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
long channelId,
IGroupChannelSettingRecord record);
/// <summary>
/// returns all channel settings for a given channel
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="clientDbVersion">calling client's database version</param>
/// <param name="channelIdList">list of channels for the request</param>
/// <param name="records">all matching channel settings</param>
/// <param name="errors">any errors encountered while retrieving group channel settings</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong GroupChannelSettingsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
List<long> channelIdList,
out IGroupChannelSettingRecord[] records,
out string[] errors);
/// <summary>
/// Inserts a new record in the Channels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="channel">The new values for the record in the Channels table</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IChannelDbRecord channel);
/// <summary>
/// Updates an existing record in the Channels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="channel">The new values for the record in the Channels table</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelsUpdate(IUserDbRecord user,
IConnectionDetails connection,
IChannelDbRecord channel);
/// <summary>
/// retrieves all channels matching search criteria
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="channelId"></param>
/// <param name="groupId"></param>
/// <param name="dasId"></param>
/// <param name="sensorId"></param>
/// <param name="testSetupId"></param>
/// <param name="testSetupName"></param>
/// <param name="channels">null, or calibrations found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
long? channelId,
int? groupId,
int? dasId,
int? sensorId,
int? testSetupId,
string testSetupName,
out IChannelDbRecord[] channels);
/// <summary>
/// Deletes an entry in the Channels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="id">Id in the Channels table</param>
/// <param name="errorString">Error string returned, possibly from sp_ChannelsDelete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong ChannelsDelete(IUserDbRecord user,
IConnectionDetails connection,
long id,
out string errorString);
}
}

View File

@@ -0,0 +1,375 @@
using DbAPI.Connections;
using DbAPI.DAS;
using DbAPI.Database;
using DbAPI.Sensors;
using DbAPI.Channels;
using DbAPI.Groups;
using DbAPI.GroupHardware;
using DbAPI.TestSetups;
using DbAPI.Tags;
using DbAPI.CustomerDetails;
using DbAPI.LabratoryDetails;
using DbAPI.TestEngineerDetails;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using DbAPI.Errors;
using DbAPI.SPCaching;
namespace DbAPI
{
public class DbAPI
{
/// <summary>
///
/// </summary>
/// <param name="connection"></param>
/// <param name="storedProcedure"></param>
/// <param name="clientDbVersion"></param>
/// <param name="storedProcedureVersionToUse"></param>
/// <returns></returns>
public static ulong GetStoredProcedureToUse(IConnectionDetails connection, string storedProcedure, int clientDbVersion, out int storedProcedureVersionToUse)
{
storedProcedureVersionToUse = 0;
var ret = DbAPI.GetDatabaseVersion(connection, out int serverDbVersion);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
var maxSPVersion = Math.Min(clientDbVersion, serverDbVersion);
ret = DbAPI.GetStoredProcedureVersion(connection, storedProcedure, maxSPVersion, out storedProcedureVersionToUse);
return ret;
}
private static object StoredProcedureLock = new object();
private static Dictionary<string, List<SPCache>> _spLookup = new Dictionary<string, List<SPCache>>();
/// <summary>
/// retrieves what version fo stored procedure to use, allows caching
/// </summary>
/// <param name="connection"></param>
/// <param name="storedProcedure"></param>
/// <param name="clientDbVersion"></param>
/// <param name="storedProcedureVersionToUse"></param>
/// <returns></returns>
public static ulong GetStoredProcedureToUseCached(IConnectionDetails connection, string storedProcedure, int clientDbVersion, out int storedProcedureVersionToUse)
{
//step 1, check if we have a cached mapping of client version, connection version to version to use
lock (StoredProcedureLock)
{
if (_spLookup.ContainsKey(storedProcedure))
{
var match = _spLookup[storedProcedure].Find(sp => sp.ClientVersion == clientDbVersion && sp.DbVersion == connection.ConnectionDbVersion);
if (null != match)
{
storedProcedureVersionToUse = match.StoredProcedureVersion;
return ErrorCodes.ERROR_SUCCESS;
}
}
}
//we didn't, so figure out what to use
storedProcedureVersionToUse = 0;
var ret = DbAPI.GetDatabaseVersion(connection, out int serverDbVersion);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
var maxSPVersion = Math.Min(clientDbVersion, serverDbVersion);
ret = DbAPI.GetStoredProcedureVersion(connection, storedProcedure, maxSPVersion, out storedProcedureVersionToUse);
if (ErrorCodes.ERROR_SUCCESS == ret)
{
//store in the cache for future reference
lock (StoredProcedureLock)
{
if (!_spLookup.ContainsKey(storedProcedure))
{
_spLookup[storedProcedure] = new List<SPCache>();
}
_spLookup[storedProcedure].Add(new SPCache()
{ ClientVersion = clientDbVersion, DbVersion = connection.ConnectionDbVersion, StoredProcedureVersion = storedProcedureVersionToUse });
}
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="connection"></param>
/// <param name="serverDbVersion"></param>
/// <returns></returns>
public static ulong GetDatabaseVersion(IConnectionDetails connection, out int serverDbVersion)
{
serverDbVersion = 0;
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DbVersionGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = null });
var reader = cmd.ExecuteReader();
var dbVersionsList = new List<int>();
while (reader.Read())
{
var version = Convert.ToInt32(reader["Version"]);
dbVersionsList.Add(version);
}
reader.Close();
serverDbVersion = dbVersionsList.Max();
Logging.LogManager.DBAPILogWriter("Result of using stored procedure sp_DbVersionGet to get current server db version is " + serverDbVersion);
}
catch (Exception ex)
{
Logging.LogManager.DBAPILogWriter("Exception while getting database version: " + ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Since sp_StoredProcedureVersionsGet returns all of the versions of a
/// stored procedure, less than or equal to the max passed in, this
/// function returns the maximum of these.
/// </summary>
/// <param name="connection"></param>
/// <param name="storedProcedure"></param>
/// <param name="maxSPVersion"></param>
/// <param name="storedProcedureVersionToUse"></param>
/// <returns></returns>
public static ulong GetStoredProcedureVersion(IConnectionDetails connection, string storedProcedure, int maxSPVersion, out int storedProcedureVersionToUse)
{
storedProcedureVersionToUse = 0;
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_StoredProcedureVersionsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
storedProcedureVersionToUse = 0;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@StoredProcedure", SqlDbType.NVarChar) { Value = storedProcedure });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = maxSPVersion });
var reader = cmd.ExecuteReader();
var returnVersion = 0;
var maxVersionFound = 0;
while (reader.Read())
{
var version = Convert.ToInt32(reader["Version"]);
if (version > maxVersionFound)
{
maxVersionFound = version;
returnVersion = version;
}
}
reader.Close();
storedProcedureVersionToUse = returnVersion;
Logging.LogManager.DBAPILogWriter($"Result of using stored procedure sp_StoredProcedureVersionsGet to get Stored Procedure version of {storedProcedure} is {storedProcedureVersionToUse}");
}
catch (Exception ex)
{
Logging.LogManager.DBAPILogWriter($"Exception while getting Stored Procedure version of {storedProcedure}: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// initializes loggers with given directory, size and log types
/// </summary>
/// <param name="logSize"></param>
/// <param name="path"></param>
/// <param name="logTypes">the event types that will be logged
/// This is a BitMask based on TraceEventType
/// Critical - Bit 0
/// Error - Bit 1
/// Warning - Bit 2
/// Information - Bit 3
/// Verbose - Bit 4
/// Start - Bit 8
/// Stop - Bit 9
/// Suspend - Bit 10
/// Resume - Bit 11
/// Transfer - Bit 12
/// </param>
public static bool _loggerInitialized = false;
public static void InitializeLogger(int logSize, string path, int logTypes)
{
Logging.LogManager.Initialize(logSize, path, logTypes);
_loggerInitialized = true;
}
public static void LogDBCaching(string message)
{
Logging.LogManager.Log(System.Diagnostics.TraceEventType.Information, Logging.LogManager.LogEvents.Information, $"{message}");
}
private static readonly DbAPI _instance = new DbAPI();
private readonly ConnectionManager _connectionManager = new ConnectionManager();
/// <summary>
/// Handles connections functions
/// <see cref="IConnections"/>
/// </summary>
public static IConnections Connections
{
get => _instance._connectionManager;
}
private readonly Database.Database _database = new Database.Database();
/// <summary>
/// Handles database functions
/// <see cref="IDatabase"/>
/// </summary>
public static IDatabase Database
{
get => _instance._database;
}
private readonly DataRecorders _das = new DataRecorders();
/// <summary>
/// Handles Data Recorder functions
/// <see cref="IDataRecorders"/>
/// </summary>
public static IDataRecorders DAS
{
get => _instance._das;
}
private readonly Sensors.Sensors _sensors = new Sensors.Sensors();
/// <summary>
/// handles sensor functions
/// <see cref="ISensors"/>
/// </summary>
public static ISensors Sensors
{
get => _instance._sensors;
}
private readonly Graphs _graphs = new Graphs();
/// <summary>
/// Handles graph functions
/// <see cref="IGraphs"/>
/// </summary>
public static IGraphs Graphs
{
get => _instance._graphs;
}
private readonly RegionsOfInterest _regionsOfInterest = new RegionsOfInterest();
/// <summary>
/// Handles ROI functions
/// <see cref="IGraphs"/>
/// </summary>
public static IRegionsOfInterest RegionsOfInterest
{
get => _instance._regionsOfInterest;
}
private readonly CalculatedChannels _calculatedChannels = new CalculatedChannels();
/// <summary>
/// Handles calculated channel functions
/// </summary>
public static ICalculatedChannels CalculatedChannels
{
get => _instance._calculatedChannels;
}
private readonly TestSetups.TestSetups _testSetups = new TestSetups.TestSetups();
/// <summary>
/// handles test setup functions
/// </summary>
public static ITestSetups TestSetups
{
get => _instance._testSetups;
}
private readonly Tags.Tags _tags = new Tags.Tags();
/// <summary>
/// Handles tag functions
/// </summary>
public static ITags Tags
{
get => _instance._tags;
}
private readonly Channels.Channels _channels = new Channels.Channels();
/// <summary>
/// handles channel functions
/// <see cref="IChannels"/>
/// </summary>
public static IChannels Channels
{
get => _instance._channels;
}
private readonly GroupHardware.GroupHardware _groupHardware = new GroupHardware.GroupHardware();
/// <summary>
/// handles GroupHardware functions
/// <see cref="IGroupHardware"/>
/// </summary>
public static IGroupHardware GroupHardware
{
get => _instance._groupHardware;
}
private readonly Groups.Groups _groups = new Groups.Groups();
/// <summary>
/// handles group functions
/// <see cref="IGroups"/>
/// </summary>
public static IGroups Groups
{
get => _instance._groups;
}
private readonly CustomerDetails.CustomerDetails _customerDetails = new CustomerDetails.CustomerDetails();
/// <summary>
/// handles CustomerDetails functions
/// </summary>
public static ICustomerDetails CustomerDetails
{
get => _instance._customerDetails;
}
private readonly LabratoryDetails.LabratoryDetails _labratoryDetails = new LabratoryDetails.LabratoryDetails();
/// <summary>
/// handles LabratoryDetails functions
/// </summary>
public static ILabratoryDetails LabratoryDetails
{
get => _instance._labratoryDetails;
}
private readonly TestEngineerDetails.TestEngineerDetails _testEngineerDetails = new TestEngineerDetails.TestEngineerDetails();
/// <summary>
/// handles TestEngineerDetails functions
/// </summary>
public static ITestEngineerDetails TestEngineerDetails
{
get => _instance._testEngineerDetails;
}
}
}

View File

@@ -0,0 +1,380 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Sensors;
using DTS.Common.Interface.Sensors.AnalogDiagnostics;
using System;
namespace DbAPI.Sensors
{
/// <summary>
/// Sensor related functions (GetAnalogSensors, InsertUpdateSensor, DeleteSensor)
/// </summary>
public interface ISensors
{
/// <summary>
/// returns all matching analog diagnostic records
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection being queried over</param>
/// <param name="Id">id of record, or null for all records</param>
/// <param name="diagnosticRunId">id of diagnostic run, or null for all records</param>
/// <param name="sensorId">sensor id to query for, or null for all</param>
/// <param name="sensorSerialNumber">serial number to query for, or null for all</param>
/// <returns></returns>
ulong SensorsAnalogDiagnosticsGet(IUserDbRecord user, IConnectionDetails connection,
long? Id, long? diagnosticRunId, int? sensorId, string sensorSerialNumber, out IDiagnosticEntry [] records);
/// <summary>
/// retrieves any matching
/// </summary>
/// <param name="user">user making query</param>
/// <param name="Id">diagnostic run id to query for or null for any id</param>
/// <param name="testId">test setup id to query for or null for any id</param>
/// <param name="testName">test setup name to query for or null for any name</param>
/// <param name="connection">connection to query on</param>
/// <param name="records">out records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogDiagnosticRunGet(IUserDbRecord user, IConnectionDetails connection,
long? Id, int? testId, string testName, out IDiagnosticRun [] records);
/// <summary>
/// update or inserts all entries passed in
/// </summary>
/// <param name="user">user committing entries</param>
/// <param name="connection">connection to commit over</param>
/// <param name="entries">entries to insert or update</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogDiagnosticUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IDiagnosticEntry entry);
/// <summary>
/// updates or inserts a Diagnostic run into the database
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection diagnostic run is being committed over</param>
/// <param name="run">the record to insert or update</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogDiagnosticRunUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IDiagnosticRun run);
/// <summary>
/// updates or inserts an input stream record into the database
/// Database id is modified on record on an insert operation
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection record is being committed over</param>
/// <param name="record">record to be inserted or updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsInputStreamUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IStreamInputRecord record);
/// <summary>
/// retrieves matching input streams from database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection over which to look for records</param>
/// <param name="Id">database id of record (use null for all)</param>
/// <param name="SerialNumber">serial number of record (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsInputStreamGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out IStreamInputRecord[] records);
/// <summary>
/// retrieves matching thermocouplers from database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection over which to look for records</param>
/// <param name="Id">database id of record (use null for all)</param>
/// <param name="SerialNumber">serial number of record (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsThermocouplerGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int? Id,
string SerialNumber,
out IThermocouplerRecord[] records);
/// <summary>
/// updates or inserts an output stream record into the database
/// Database id is modified on record on an insert operation
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection record is being committed over</param>
/// <param name="record">record to be inserted or updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsOutputStreamUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IStreamOutputRecord record);
/// <summary>
/// retrieves matching output streams from database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection over which to look for records</param>
/// <param name="Id">database id of record (use null for all)</param>
/// <param name="SerialNumber">serial number of record (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsOutputStreamGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out IStreamOutputRecord[] records);
/// <summary>
/// updates or inserts a new UART record into the database
/// Id is updated if a new record is inserted
/// </summary>
/// <param name="user">user committing UART</param>
/// <param name="connection">connection UART should be committed on</param>
/// <param name="record">record being inserted or updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsUARTUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IUARTRecord record);
/// <summary>
/// retrieves UART settings
/// </summary>
/// <param name="user">user making requests</param>
/// <param name="connection">connection request sh</param>
/// <param name="Id">Id to search for (use null for all)</param>
/// <param name="SerialNumber">serial number to search for (use null or empty for all)</param>
/// <param name="records">matching records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsUARTGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out IUARTRecord[] records);
/// <summary>
/// commits a digital output setting to the db
/// The record will be modified with a new database id if
/// a new record is inserted
/// </summary>
/// <param name="user">user making commit</param>
/// <param name="connection">connection over which to commit</param>
/// <param name="record">the record to commit</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsDigitalOutUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
IDigitalOutDbRecord record);
/// <summary>
/// retrieves all matching digital output settings in the db
/// </summary>
/// <param name="user">user requesting records</param>
/// <param name="connection">connection to query records on</param>
/// <param name="Id">Database id of records (can be null)</param>
/// <param name="serialNumber">serial number/name of setting (can be null)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsDigitalOutGet(
IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string serialNumber,
out IDigitalOutDbRecord[] records);
/// <summary>
/// inserts or updates a digital input record into the db. If a record is inserted
/// then the original record is updated with the database id of the entry
/// </summary>
/// <param name="user">user committing record </param>
/// <param name="connection"></param>
/// <param name="record"></param>
/// <returns></returns>
ulong SensorsDigitalInUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
IDigitalInDbRecord record);
/// <summary>
/// retrieves any digital input settings matching input criteria
/// in the database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection to query over</param>
/// <param name="id">Database Id of digital input setting (can be null)</param>
/// <param name="serialNumber">serial number of setting (can be null)</param>
/// <param name="eId">Electronic id of setting (can be null)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsDigitalInGet(IUserDbRecord user,
IConnectionDetails connection,
int? id,
string serialNumber,
string eId,
out IDigitalInDbRecord[] records);
/// <summary>
/// Inserts or updates a squib setting in the db
/// setting is modified with new db id after execution
/// </summary>
/// <param name="user">user inserting setting</param>
/// <param name="connection">connection for inserting</param>
/// <param name="record">record to be inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsSquibUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ISquibDbRecord record);
/// <summary>
/// retrieves all squib settings matching input criteria
/// </summary>
/// <param name="user">user requesting squib settings</param>
/// <param name="connection">connection for retrieving squib settings</param>
/// <param name="eId">Electronic Id </param>
/// <param name="Id">Database Id for squib setting</param>
/// <param name="serialNumber">serial number/name of squib setting</param>
/// <param name="records">output records discovered</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsSquibGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string serialNumber,
string eId,
out ISquibDbRecord[] records);
/// <summary>
/// Deletes ALL sensors in the db
/// </summary>
/// <param name="user">user deleting sensors</param>
/// <param name="connection">connection sensors to be deleted on</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsDeleteAll(IUserDbRecord user,
IConnectionDetails connection);
/// <summary>
/// retrieves the bridge resistance for a sensor
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="serialNumber">serial number of sensor</param>
/// <param name="bridgeResistance">output bridge resistance of sensor</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogBridgeResistanceGet(IUserDbRecord user,
IConnectionDetails connection,
string serialNumber,
out double bridgeResistance);
/// <summary>
/// deletes all sensor calibrations matching criteria
/// nulls are wild cards, so passing in all nulls will
/// delete all calibrations
/// </summary>
/// <param name="user">user deleting calibrations</param>
/// <param name="connection">connection to use for deletes</param>
/// <param name="sensorSerialNumber">allows null</param>
/// <param name="calibrationDate">allows null</param>
/// <param name="modifyDate">allows null</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorCalibrationsDelete(IUserDbRecord user,
IConnectionDetails connection,
string sensorSerialNumber,
DateTime? calibrationDate,
DateTime? modifyDate
);
/// <summary>
/// inserts a new calibration record
/// </summary>
/// <param name="user">user submitting record</param>
/// <param name="connection">connection record is being submitted on</param>
/// <param name="cal">calibration record</param>
/// <param name="sensorType">type of sensor</param>
/// <param name="setCalibrationId"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorCalibrationsInsert(IUserDbRecord user,
IConnectionDetails connection,
ISensorCalDbRecord cal,
int sensorType,
bool setCalibrationId);
/// <summary>
/// deletes all sensors matching criteria
/// sensor types are defined in table SensorsType
/// 0 - analog
/// 1 - digital in
/// 2 - digital out
/// 3 - squib
/// 4 - UART
/// </summary>
/// <param name="user">user deleting sensors</param>
/// <param name="connection">connection sensors are being deleted on</param>
/// <param name="sensorId">id in database</param>
/// <param name="sensorType">type of sensor</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsDelete(IUserDbRecord user,
IConnectionDetails connection,
int sensorId,
int sensorType);
/// <summary>
/// commits an analog sensor to the db
/// </summary>
/// <param name="user">DataPRO user making commit</param>
/// <param name="connection">connection commit is being made on</param>
/// <param name="record">the record being committed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
IAnalogDbRecord record);
/// <summary>
/// retrieves all calibrations matching search criteria
/// </summary>
/// <param name="user">user querying calibrations</param>
/// <param name="connection">connection user is using</param>
/// <param name="sensorId">sensor id (allows null)</param>
/// <param name="serialNumber">serial number (allows null and empty)</param>
/// <param name="calibrations">any calibrations matching criteria</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorCalibrationsGet(IUserDbRecord user,
IConnectionDetails connection,
int? sensorId,
string serialNumber,
out ISensorCalDbRecord[] calibrations
);
/// <summary>
/// retrieves all analog sensors matching search criteria
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="sensorId">sensor database id (allows null)</param>
/// <param name="serialNumber">sensor serial number (allows null)</param>
/// <param name="eId">electronic Id (DALLAS or TEDS id value)</param>
/// <param name="sensors">any sensors matching criteria</param>
/// <returns>0 (ERROR_SUCCES) on success, all other values are error codes</returns>
ulong SensorsAnalogGet(IUserDbRecord user,
IConnectionDetails connection,
int? sensorId,
string serialNumber,
string eId,
out IAnalogDbRecord[] sensors);
/// <summary>
/// retrieves all analog sensors matching search criteria
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="serialNumber">sensor serial number (allows null)</param>
/// <param name="sensors">any sensors matching criteria</param>
/// <returns>0 (ERROR_SUCCES) on success, all other values are error codes</returns>
ulong SensorsGet(IUserDbRecord user,
IConnectionDetails connection,
string serialNumber,
out ISensorDbRecord[] sensors);
ulong UpdateAssemblySensorUsageCount(IUserDbRecord user,
IConnectionDetails connection,
string assemblyName,
int newUsageCount);
/// <summary>
/// Updates a sensor's (total) usage count
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="sd">The sensor to be updated</param>
/// <returns></returns>
ulong UpdateSensorUsageCount(IUserDbRecord user,
IConnectionDetails connection,
ISensorData sd);
/// <summary>
/// Updates a sensor calibration's usage count
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="sd">The sensor to be updated</param>
/// <returns></returns>
ulong UpdateSensorCalibrationUsageCount(IUserDbRecord user,
IConnectionDetails connection,
int sensorId,
int sensorCalibrationId,
int newUsageCount);
}
}

View File

@@ -0,0 +1,70 @@
namespace DbAPI.Connections
{
public interface IConnectionDetails
{
/// <summary>
/// Whether NTLM Authentication should be used
/// </summary>
bool UseNTLMAuthentication { get; set; }
/// <summary>
/// when connecting to a database with a specific user/pwd, what user to use
/// </summary>
string DbUser { get; set; }
/// <summary>
/// When connecting to a database with a specific user/pwd, what pwd to use
/// </summary>
string DbUserPassword { get; set; }
/// <summary>
/// When connecting to a LocalDB, what the name of the instance should be
/// </summary>
string InstanceName { get; set; }
/// <summary>
/// When connecting to a remote DB, what server the DB is on
/// </summary>
string DbServer { get; set; }
/// <summary>
/// Name of database to connect to
/// </summary>
string DbName { get; set; }
/// <summary>
/// Whether connecting to a LocalDB or a remote DB
/// </summary>
bool UsingCentralizedDb { get; set; }
/// <summary>
/// path to db files if using LocalDB
/// </summary>
string DbFolderPath { get; set; }
/// <summary>
/// path to attach.bat if using LocalDB
/// </summary>
string AttachDbsBatPath { get; set; }
/// <summary>
/// The path to the SQLCMD.EXE that we want to use
/// </summary>
string ODBCToolsPath { get; set; }
/// <summary>
/// a string suitable for SqlClient to connect to
/// </summary>
/// <returns></returns>
string GetConnectionString();
/// <summary>
/// returns a deep copy of connection details
/// </summary>
/// <returns></returns>
IConnectionDetails Clone();
/// <summary>
/// Path to SQL Server when using LocalDB
/// </summary>
string SqlDbPath { get; set; }
/// <summary>
/// holds the code version of the database, what we would use if available
/// </summary>
int ClientDbVersion { get; set; }
/// <summary>
/// holds the version of the database, what we will be using
/// </summary>
int ConnectionDbVersion { get; set; }
}
}

View File

@@ -0,0 +1,612 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v3.1",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v3.1": {
"DbAPI/1.0.0": {
"dependencies": {
"Microsoft.Data.SqlClient": "3.0.0"
},
"runtime": {
"DbAPI.dll": {}
}
},
"Azure.Core/1.6.0": {
"dependencies": {
"Microsoft.Bcl.AsyncInterfaces": "1.0.0",
"System.Buffers": "4.5.0",
"System.Diagnostics.DiagnosticSource": "4.7.0",
"System.Memory": "4.5.3",
"System.Numerics.Vectors": "4.5.0",
"System.Text.Json": "4.6.0",
"System.Threading.Tasks.Extensions": "4.5.2"
},
"runtime": {
"lib/netstandard2.0/Azure.Core.dll": {
"assemblyVersion": "1.6.0.0",
"fileVersion": "1.600.20.52802"
}
}
},
"Azure.Identity/1.3.0": {
"dependencies": {
"Azure.Core": "1.6.0",
"Microsoft.Identity.Client": "4.22.0",
"Microsoft.Identity.Client.Extensions.Msal": "2.16.5",
"System.Memory": "4.5.3",
"System.Security.Cryptography.ProtectedData": "4.7.0",
"System.Text.Json": "4.6.0",
"System.Threading.Tasks.Extensions": "4.5.2"
},
"runtime": {
"lib/netstandard2.0/Azure.Identity.dll": {
"assemblyVersion": "1.3.0.0",
"fileVersion": "1.300.20.56202"
}
}
},
"Microsoft.Bcl.AsyncInterfaces/1.0.0": {
"runtime": {
"lib/netstandard2.1/Microsoft.Bcl.AsyncInterfaces.dll": {
"assemblyVersion": "1.0.0.0",
"fileVersion": "4.700.19.46214"
}
}
},
"Microsoft.CSharp/4.5.0": {},
"Microsoft.Data.SqlClient/3.0.0": {
"dependencies": {
"Azure.Identity": "1.3.0",
"Microsoft.Data.SqlClient.SNI.runtime": "3.0.0",
"Microsoft.Identity.Client": "4.22.0",
"Microsoft.IdentityModel.JsonWebTokens": "6.8.0",
"Microsoft.IdentityModel.Protocols.OpenIdConnect": "6.8.0",
"Microsoft.Win32.Registry": "4.7.0",
"System.Configuration.ConfigurationManager": "4.7.0",
"System.Diagnostics.DiagnosticSource": "4.7.0",
"System.Runtime.Caching": "4.7.0",
"System.Security.Principal.Windows": "4.7.0",
"System.Text.Encoding.CodePages": "4.7.0",
"System.Text.Encodings.Web": "4.7.2"
},
"runtime": {
"lib/netcoreapp3.1/Microsoft.Data.SqlClient.dll": {
"assemblyVersion": "3.0.0.0",
"fileVersion": "3.0.0.0"
}
},
"runtimeTargets": {
"runtimes/unix/lib/netcoreapp3.1/Microsoft.Data.SqlClient.dll": {
"rid": "unix",
"assetType": "runtime",
"assemblyVersion": "3.0.0.0",
"fileVersion": "3.0.0.0"
},
"runtimes/win/lib/netcoreapp3.1/Microsoft.Data.SqlClient.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "3.0.0.0",
"fileVersion": "3.0.0.0"
}
}
},
"Microsoft.Data.SqlClient.SNI.runtime/3.0.0": {
"runtimeTargets": {
"runtimes/win-arm/native/Microsoft.Data.SqlClient.SNI.dll": {
"rid": "win-arm",
"assetType": "native",
"fileVersion": "3.0.0.0"
},
"runtimes/win-arm64/native/Microsoft.Data.SqlClient.SNI.dll": {
"rid": "win-arm64",
"assetType": "native",
"fileVersion": "3.0.0.0"
},
"runtimes/win-x64/native/Microsoft.Data.SqlClient.SNI.dll": {
"rid": "win-x64",
"assetType": "native",
"fileVersion": "3.0.0.0"
},
"runtimes/win-x86/native/Microsoft.Data.SqlClient.SNI.dll": {
"rid": "win-x86",
"assetType": "native",
"fileVersion": "3.0.0.0"
}
}
},
"Microsoft.Identity.Client/4.22.0": {
"runtime": {
"lib/netcoreapp2.1/Microsoft.Identity.Client.dll": {
"assemblyVersion": "4.22.0.0",
"fileVersion": "4.22.0.0"
}
}
},
"Microsoft.Identity.Client.Extensions.Msal/2.16.5": {
"dependencies": {
"Microsoft.Identity.Client": "4.22.0",
"System.Security.Cryptography.ProtectedData": "4.7.0"
},
"runtime": {
"lib/netcoreapp2.1/Microsoft.Identity.Client.Extensions.Msal.dll": {
"assemblyVersion": "2.16.5.0",
"fileVersion": "2.16.5.0"
}
}
},
"Microsoft.IdentityModel.JsonWebTokens/6.8.0": {
"dependencies": {
"Microsoft.IdentityModel.Tokens": "6.8.0"
},
"runtime": {
"lib/netstandard2.0/Microsoft.IdentityModel.JsonWebTokens.dll": {
"assemblyVersion": "6.8.0.0",
"fileVersion": "6.8.0.11012"
}
}
},
"Microsoft.IdentityModel.Logging/6.8.0": {
"runtime": {
"lib/netstandard2.0/Microsoft.IdentityModel.Logging.dll": {
"assemblyVersion": "6.8.0.0",
"fileVersion": "6.8.0.11012"
}
}
},
"Microsoft.IdentityModel.Protocols/6.8.0": {
"dependencies": {
"Microsoft.IdentityModel.Logging": "6.8.0",
"Microsoft.IdentityModel.Tokens": "6.8.0"
},
"runtime": {
"lib/netstandard2.0/Microsoft.IdentityModel.Protocols.dll": {
"assemblyVersion": "6.8.0.0",
"fileVersion": "6.8.0.11012"
}
}
},
"Microsoft.IdentityModel.Protocols.OpenIdConnect/6.8.0": {
"dependencies": {
"Microsoft.IdentityModel.Protocols": "6.8.0",
"System.IdentityModel.Tokens.Jwt": "6.8.0"
},
"runtime": {
"lib/netstandard2.0/Microsoft.IdentityModel.Protocols.OpenIdConnect.dll": {
"assemblyVersion": "6.8.0.0",
"fileVersion": "6.8.0.11012"
}
}
},
"Microsoft.IdentityModel.Tokens/6.8.0": {
"dependencies": {
"Microsoft.CSharp": "4.5.0",
"Microsoft.IdentityModel.Logging": "6.8.0",
"System.Security.Cryptography.Cng": "4.5.0"
},
"runtime": {
"lib/netstandard2.0/Microsoft.IdentityModel.Tokens.dll": {
"assemblyVersion": "6.8.0.0",
"fileVersion": "6.8.0.11012"
}
}
},
"Microsoft.NETCore.Platforms/3.1.0": {},
"Microsoft.Win32.Registry/4.7.0": {
"dependencies": {
"System.Security.AccessControl": "4.7.0",
"System.Security.Principal.Windows": "4.7.0"
}
},
"Microsoft.Win32.SystemEvents/4.7.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "3.1.0"
},
"runtime": {
"lib/netstandard2.0/Microsoft.Win32.SystemEvents.dll": {
"assemblyVersion": "4.0.2.0",
"fileVersion": "4.700.19.56404"
}
},
"runtimeTargets": {
"runtimes/win/lib/netcoreapp3.0/Microsoft.Win32.SystemEvents.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "4.0.2.0",
"fileVersion": "4.700.19.56404"
}
}
},
"System.Buffers/4.5.0": {},
"System.Configuration.ConfigurationManager/4.7.0": {
"dependencies": {
"System.Security.Cryptography.ProtectedData": "4.7.0",
"System.Security.Permissions": "4.7.0"
},
"runtime": {
"lib/netstandard2.0/System.Configuration.ConfigurationManager.dll": {
"assemblyVersion": "4.0.3.0",
"fileVersion": "4.700.19.56404"
}
}
},
"System.Diagnostics.DiagnosticSource/4.7.0": {},
"System.Drawing.Common/4.7.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "3.1.0",
"Microsoft.Win32.SystemEvents": "4.7.0"
},
"runtime": {
"lib/netstandard2.0/System.Drawing.Common.dll": {
"assemblyVersion": "4.0.0.1",
"fileVersion": "4.6.26919.2"
}
},
"runtimeTargets": {
"runtimes/unix/lib/netcoreapp3.0/System.Drawing.Common.dll": {
"rid": "unix",
"assetType": "runtime",
"assemblyVersion": "4.0.2.0",
"fileVersion": "4.700.19.56404"
},
"runtimes/win/lib/netcoreapp3.0/System.Drawing.Common.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "4.0.2.0",
"fileVersion": "4.700.19.56404"
}
}
},
"System.IdentityModel.Tokens.Jwt/6.8.0": {
"dependencies": {
"Microsoft.IdentityModel.JsonWebTokens": "6.8.0",
"Microsoft.IdentityModel.Tokens": "6.8.0"
},
"runtime": {
"lib/netstandard2.0/System.IdentityModel.Tokens.Jwt.dll": {
"assemblyVersion": "6.8.0.0",
"fileVersion": "6.8.0.11012"
}
}
},
"System.Memory/4.5.3": {},
"System.Numerics.Vectors/4.5.0": {},
"System.Runtime.Caching/4.7.0": {
"dependencies": {
"System.Configuration.ConfigurationManager": "4.7.0"
},
"runtime": {
"lib/netstandard2.0/System.Runtime.Caching.dll": {
"assemblyVersion": "4.0.1.0",
"fileVersion": "4.700.19.56404"
}
},
"runtimeTargets": {
"runtimes/win/lib/netstandard2.0/System.Runtime.Caching.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "4.0.1.0",
"fileVersion": "4.700.19.56404"
}
}
},
"System.Security.AccessControl/4.7.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "3.1.0",
"System.Security.Principal.Windows": "4.7.0"
}
},
"System.Security.Cryptography.Cng/4.5.0": {},
"System.Security.Cryptography.ProtectedData/4.7.0": {
"runtime": {
"lib/netstandard2.0/System.Security.Cryptography.ProtectedData.dll": {
"assemblyVersion": "4.0.5.0",
"fileVersion": "4.700.19.56404"
}
},
"runtimeTargets": {
"runtimes/win/lib/netstandard2.0/System.Security.Cryptography.ProtectedData.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "4.0.5.0",
"fileVersion": "4.700.19.56404"
}
}
},
"System.Security.Permissions/4.7.0": {
"dependencies": {
"System.Security.AccessControl": "4.7.0",
"System.Windows.Extensions": "4.7.0"
},
"runtime": {
"lib/netcoreapp3.0/System.Security.Permissions.dll": {
"assemblyVersion": "4.0.3.0",
"fileVersion": "4.700.19.56404"
}
}
},
"System.Security.Principal.Windows/4.7.0": {},
"System.Text.Encoding.CodePages/4.7.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "3.1.0"
}
},
"System.Text.Encodings.Web/4.7.2": {
"runtime": {
"lib/netstandard2.1/System.Text.Encodings.Web.dll": {
"assemblyVersion": "4.0.5.1",
"fileVersion": "4.700.21.11602"
}
}
},
"System.Text.Json/4.6.0": {},
"System.Threading.Tasks.Extensions/4.5.2": {},
"System.Windows.Extensions/4.7.0": {
"dependencies": {
"System.Drawing.Common": "4.7.0"
},
"runtime": {
"lib/netcoreapp3.0/System.Windows.Extensions.dll": {
"assemblyVersion": "4.0.1.0",
"fileVersion": "4.700.19.56404"
}
},
"runtimeTargets": {
"runtimes/win/lib/netcoreapp3.0/System.Windows.Extensions.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "4.0.1.0",
"fileVersion": "4.700.19.56404"
}
}
}
}
},
"libraries": {
"DbAPI/1.0.0": {
"type": "project",
"serviceable": false,
"sha512": ""
},
"Azure.Core/1.6.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-kI4m2NsODPOrxo0OoKjk6B3ADbdovhDQIEmI4039upjjZKRaewVLx/Uz4DfRa/NtnIRZQPUALe1yvdHWAoRt4w==",
"path": "azure.core/1.6.0",
"hashPath": "azure.core.1.6.0.nupkg.sha512"
},
"Azure.Identity/1.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-l1SYfZKOFBuUFG7C2SWHmJcrQQaiXgBdVCycx4vcZQkC6efDVt7mzZ5pfJAFEJDBUq7mjRQ0RPq9ZDGdSswqMg==",
"path": "azure.identity/1.3.0",
"hashPath": "azure.identity.1.3.0.nupkg.sha512"
},
"Microsoft.Bcl.AsyncInterfaces/1.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-K63Y4hORbBcKLWH5wnKgzyn7TOfYzevIEwIedQHBIkmkEBA9SCqgvom+XTuE+fAFGvINGkhFItaZ2dvMGdT5iw==",
"path": "microsoft.bcl.asyncinterfaces/1.0.0",
"hashPath": "microsoft.bcl.asyncinterfaces.1.0.0.nupkg.sha512"
},
"Microsoft.CSharp/4.5.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-kaj6Wb4qoMuH3HySFJhxwQfe8R/sJsNJnANrvv8WdFPMoNbKY5htfNscv+LHCu5ipz+49m2e+WQXpLXr9XYemQ==",
"path": "microsoft.csharp/4.5.0",
"hashPath": "microsoft.csharp.4.5.0.nupkg.sha512"
},
"Microsoft.Data.SqlClient/3.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-MUauWfCLsZQQMUR/wZhec5MH6+NTPmPp9i/OsjIMmIu2ICYUGOVm1x7RTqKxq19UWxXMSG03/O0FyXQJrpDs9A==",
"path": "microsoft.data.sqlclient/3.0.0",
"hashPath": "microsoft.data.sqlclient.3.0.0.nupkg.sha512"
},
"Microsoft.Data.SqlClient.SNI.runtime/3.0.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-n1sNyjJgu2pYWKgw3ZPikw3NiRvG4kt7Ya5MK8u77Rgj/1bTFqO/eDF4k5W9H5GXplMZCpKkNbp5kNBICgSB0w==",
"path": "microsoft.data.sqlclient.sni.runtime/3.0.0",
"hashPath": "microsoft.data.sqlclient.sni.runtime.3.0.0.nupkg.sha512"
},
"Microsoft.Identity.Client/4.22.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-GlamU9rs8cSVIx9WSGv5QKpt66KkE+ImxNa/wNZZUJ3knt3PM98T9sOY8B7NcEfhw7NoxU2/0TSOcmnRSJQgqw==",
"path": "microsoft.identity.client/4.22.0",
"hashPath": "microsoft.identity.client.4.22.0.nupkg.sha512"
},
"Microsoft.Identity.Client.Extensions.Msal/2.16.5": {
"type": "package",
"serviceable": true,
"sha512": "sha512-VlGUZEpF8KP/GCfFI59sdE0WA0o9quqwM1YQY0dSp6jpGy5EOBkureaybLfpwCuYUUjQbLkN2p7neUIcQCfbzA==",
"path": "microsoft.identity.client.extensions.msal/2.16.5",
"hashPath": "microsoft.identity.client.extensions.msal.2.16.5.nupkg.sha512"
},
"Microsoft.IdentityModel.JsonWebTokens/6.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-+7JIww64PkMt7NWFxoe4Y/joeF7TAtA/fQ0b2GFGcagzB59sKkTt/sMZWR6aSZht5YC7SdHi3W6yM1yylRGJCQ==",
"path": "microsoft.identitymodel.jsonwebtokens/6.8.0",
"hashPath": "microsoft.identitymodel.jsonwebtokens.6.8.0.nupkg.sha512"
},
"Microsoft.IdentityModel.Logging/6.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-Rfh/p4MaN4gkmhPxwbu8IjrmoDncGfHHPh1sTnc0AcM/Oc39/fzC9doKNWvUAjzFb8LqA6lgZyblTrIsX/wDXg==",
"path": "microsoft.identitymodel.logging/6.8.0",
"hashPath": "microsoft.identitymodel.logging.6.8.0.nupkg.sha512"
},
"Microsoft.IdentityModel.Protocols/6.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-OJZx5nPdiH+MEkwCkbJrTAUiO/YzLe0VSswNlDxJsJD9bhOIdXHufh650pfm59YH1DNevp3/bXzukKrG57gA1w==",
"path": "microsoft.identitymodel.protocols/6.8.0",
"hashPath": "microsoft.identitymodel.protocols.6.8.0.nupkg.sha512"
},
"Microsoft.IdentityModel.Protocols.OpenIdConnect/6.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-X/PiV5l3nYYsodtrNMrNQIVlDmHpjQQ5w48E+o/D5H4es2+4niEyQf3l03chvZGWNzBRhfSstaXr25/Ye4AeYw==",
"path": "microsoft.identitymodel.protocols.openidconnect/6.8.0",
"hashPath": "microsoft.identitymodel.protocols.openidconnect.6.8.0.nupkg.sha512"
},
"Microsoft.IdentityModel.Tokens/6.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-gTqzsGcmD13HgtNePPcuVHZ/NXWmyV+InJgalW/FhWpII1D7V1k0obIseGlWMeA4G+tZfeGMfXr0klnWbMR/mQ==",
"path": "microsoft.identitymodel.tokens/6.8.0",
"hashPath": "microsoft.identitymodel.tokens.6.8.0.nupkg.sha512"
},
"Microsoft.NETCore.Platforms/3.1.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-z7aeg8oHln2CuNulfhiLYxCVMPEwBl3rzicjvIX+4sUuCwvXw5oXQEtbiU2c0z4qYL5L3Kmx0mMA/+t/SbY67w==",
"path": "microsoft.netcore.platforms/3.1.0",
"hashPath": "microsoft.netcore.platforms.3.1.0.nupkg.sha512"
},
"Microsoft.Win32.Registry/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-KSrRMb5vNi0CWSGG1++id2ZOs/1QhRqROt+qgbEAdQuGjGrFcl4AOl4/exGPUYz2wUnU42nvJqon1T3U0kPXLA==",
"path": "microsoft.win32.registry/4.7.0",
"hashPath": "microsoft.win32.registry.4.7.0.nupkg.sha512"
},
"Microsoft.Win32.SystemEvents/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-mtVirZr++rq+XCDITMUdnETD59XoeMxSpLRIII7JRI6Yj0LEDiO1pPn0ktlnIj12Ix8bfvQqQDMMIF9wC98oCA==",
"path": "microsoft.win32.systemevents/4.7.0",
"hashPath": "microsoft.win32.systemevents.4.7.0.nupkg.sha512"
},
"System.Buffers/4.5.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-pL2ChpaRRWI/p4LXyy4RgeWlYF2sgfj/pnVMvBqwNFr5cXg7CXNnWZWxrOONLg8VGdFB8oB+EG2Qw4MLgTOe+A==",
"path": "system.buffers/4.5.0",
"hashPath": "system.buffers.4.5.0.nupkg.sha512"
},
"System.Configuration.ConfigurationManager/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-/anOTeSZCNNI2zDilogWrZ8pNqCmYbzGNexUnNhjW8k0sHqEZ2nHJBp147jBV3hGYswu5lINpNg1vxR7bnqvVA==",
"path": "system.configuration.configurationmanager/4.7.0",
"hashPath": "system.configuration.configurationmanager.4.7.0.nupkg.sha512"
},
"System.Diagnostics.DiagnosticSource/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-oJjw3uFuVDJiJNbCD8HB4a2p3NYLdt1fiT5OGsPLw+WTOuG0KpP4OXelMmmVKpClueMsit6xOlzy4wNKQFiBLg==",
"path": "system.diagnostics.diagnosticsource/4.7.0",
"hashPath": "system.diagnostics.diagnosticsource.4.7.0.nupkg.sha512"
},
"System.Drawing.Common/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-v+XbyYHaZjDfn0ENmJEV1VYLgGgCTx1gnfOBcppowbpOAriglYgGCvFCPr2EEZyBvXlpxbEsTwkOlInl107ahA==",
"path": "system.drawing.common/4.7.0",
"hashPath": "system.drawing.common.4.7.0.nupkg.sha512"
},
"System.IdentityModel.Tokens.Jwt/6.8.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-5tBCjAub2Bhd5qmcd0WhR5s354e4oLYa//kOWrkX+6/7ZbDDJjMTfwLSOiZ/MMpWdE4DWPLOfTLOq/juj9CKzA==",
"path": "system.identitymodel.tokens.jwt/6.8.0",
"hashPath": "system.identitymodel.tokens.jwt.6.8.0.nupkg.sha512"
},
"System.Memory/4.5.3": {
"type": "package",
"serviceable": true,
"sha512": "sha512-3oDzvc/zzetpTKWMShs1AADwZjQ/36HnsufHRPcOjyRAAMLDlu2iD33MBI2opxnezcVUtXyqDXXjoFMOU9c7SA==",
"path": "system.memory/4.5.3",
"hashPath": "system.memory.4.5.3.nupkg.sha512"
},
"System.Numerics.Vectors/4.5.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-QQTlPTl06J/iiDbJCiepZ4H//BVraReU4O4EoRw1U02H5TLUIT7xn3GnDp9AXPSlJUDyFs4uWjWafNX6WrAojQ==",
"path": "system.numerics.vectors/4.5.0",
"hashPath": "system.numerics.vectors.4.5.0.nupkg.sha512"
},
"System.Runtime.Caching/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-NdvNRjTPxYvIEhXQszT9L9vJhdQoX6AQ0AlhjTU+5NqFQVuacJTfhPVAvtGWNA2OJCqRiR/okBcZgMwI6MqcZg==",
"path": "system.runtime.caching/4.7.0",
"hashPath": "system.runtime.caching.4.7.0.nupkg.sha512"
},
"System.Security.AccessControl/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-JECvTt5aFF3WT3gHpfofL2MNNP6v84sxtXxpqhLBCcDRzqsPBmHhQ6shv4DwwN2tRlzsUxtb3G9M3763rbXKDg==",
"path": "system.security.accesscontrol/4.7.0",
"hashPath": "system.security.accesscontrol.4.7.0.nupkg.sha512"
},
"System.Security.Cryptography.Cng/4.5.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-WG3r7EyjUe9CMPFSs6bty5doUqT+q9pbI80hlNzo2SkPkZ4VTuZkGWjpp77JB8+uaL4DFPRdBsAY+DX3dBK92A==",
"path": "system.security.cryptography.cng/4.5.0",
"hashPath": "system.security.cryptography.cng.4.5.0.nupkg.sha512"
},
"System.Security.Cryptography.ProtectedData/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-ehYW0m9ptxpGWvE4zgqongBVWpSDU/JCFD4K7krxkQwSz/sFQjEXCUqpvencjy6DYDbn7Ig09R8GFffu8TtneQ==",
"path": "system.security.cryptography.protecteddata/4.7.0",
"hashPath": "system.security.cryptography.protecteddata.4.7.0.nupkg.sha512"
},
"System.Security.Permissions/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-dkOV6YYVBnYRa15/yv004eCGRBVADXw8qRbbNiCn/XpdJSUXkkUeIvdvFHkvnko4CdKMqG8yRHC4ox83LSlMsQ==",
"path": "system.security.permissions/4.7.0",
"hashPath": "system.security.permissions.4.7.0.nupkg.sha512"
},
"System.Security.Principal.Windows/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-ojD0PX0XhneCsUbAZVKdb7h/70vyYMDYs85lwEI+LngEONe/17A0cFaRFqZU+sOEidcVswYWikYOQ9PPfjlbtQ==",
"path": "system.security.principal.windows/4.7.0",
"hashPath": "system.security.principal.windows.4.7.0.nupkg.sha512"
},
"System.Text.Encoding.CodePages/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-aeu4FlaUTemuT1qOd1MyU4T516QR4Fy+9yDbwWMPHOHy7U8FD6SgTzdZFO7gHcfAPHtECqInbwklVvUK4RHcNg==",
"path": "system.text.encoding.codepages/4.7.0",
"hashPath": "system.text.encoding.codepages.4.7.0.nupkg.sha512"
},
"System.Text.Encodings.Web/4.7.2": {
"type": "package",
"serviceable": true,
"sha512": "sha512-iTUgB/WtrZ1sWZs84F2hwyQhiRH6QNjQv2DkwrH+WP6RoFga2Q1m3f9/Q7FG8cck8AdHitQkmkXSY8qylcDmuA==",
"path": "system.text.encodings.web/4.7.2",
"hashPath": "system.text.encodings.web.4.7.2.nupkg.sha512"
},
"System.Text.Json/4.6.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-4F8Xe+JIkVoDJ8hDAZ7HqLkjctN/6WItJIzQaifBwClC7wmoLSda/Sv2i6i1kycqDb3hWF4JCVbpAweyOKHEUA==",
"path": "system.text.json/4.6.0",
"hashPath": "system.text.json.4.6.0.nupkg.sha512"
},
"System.Threading.Tasks.Extensions/4.5.2": {
"type": "package",
"serviceable": true,
"sha512": "sha512-BG/TNxDFv0svAzx8OiMXDlsHfGw623BZ8tCXw4YLhDFDvDhNUEV58jKYMGRnkbJNm7c3JNNJDiN7JBMzxRBR2w==",
"path": "system.threading.tasks.extensions/4.5.2",
"hashPath": "system.threading.tasks.extensions.4.5.2.nupkg.sha512"
},
"System.Windows.Extensions/4.7.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-CeWTdRNfRaSh0pm2gDTJFwVaXfTq6Xwv/sA887iwPTneW7oMtMlpvDIO+U60+3GWTB7Aom6oQwv5VZVUhQRdPQ==",
"path": "system.windows.extensions/4.7.0",
"hashPath": "system.windows.extensions.4.7.0.nupkg.sha512"
}
}
}

View File

@@ -0,0 +1,628 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes.Hardware;
using DTS.Common.Interface.DataRecorders;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using DTS.Common.Interface.Database;
using System.Data.SqlClient;
using DTS.Common.Enums.DASFactory;
using DTS.Common.Classes;
namespace DbAPI.DAS
{
/// <summary>
/// No need to export, this is just an internal implementation of the <see cref="IDataRecorders"/> interface
/// <inheritdoc cref="IDataRecorders"/>
/// </summary>
internal class DataRecorders : IDataRecorders
{
/// <summary>
/// Deletes all channels related to DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="hardwareId"></param>
/// <returns>0 on success, all other values are errors</returns>
public ulong DASChannelsDelete(IUserDbRecord user, IConnectionDetails connection,
string hardwareId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChannelsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@HardwareId", SqlDbType.NVarChar, 50) { Value = hardwareId });
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
var error = Convert.ToInt32(errorNumberParam.Value);
var msg = Convert.ToString(errorMessageParam.Value);
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, $"Failed DASChannelsDelete {error} - {msg}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// inserts das channel record into db. modifies record by updating id after insert
/// </summary>
/// <param name="user">user making insert</param>
/// <param name="connection">connection channel is being inserted on</param>
/// <param name="hardwareId">string identifier for hardware (serialnumber_dastype)</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
public ulong DASChannelsInsert(IUserDbRecord user, IConnectionDetails connection,
string hardwareId,
ref IDASChannelDBRecord record)
{
if (null == record)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (string.IsNullOrWhiteSpace(hardwareId))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChannelsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(
new SqlParameter("@HardwareId", SqlDbType.NVarChar, 50) { Value = hardwareId });
cmd.Parameters.Add(new SqlParameter("@ChannelIdx", SqlDbType.Int) { Value = record.ChannelIdx });
cmd.Parameters.Add(new SqlParameter("@SupportedBridges", SqlDbType.Int) { Value = record.SupportedBridges });
cmd.Parameters.Add(new SqlParameter("@SupportedExcitations", SqlDbType.Int) { Value = record.SupportedExcitations });
cmd.Parameters.Add(new SqlParameter("@DASDisplayOrder", SqlDbType.Int) { Value = record.DASDisplayOrder });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Int) { Value = record.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@SupportedDigitalInputModes", SqlDbType.Int)
{
Value = record.SupportedDigitalInputModes
});
cmd.Parameters.Add(
new SqlParameter("@SupportedSquibFireModes", SqlDbType.Int) { Value = record.SupportedSquibFireModes });
cmd.Parameters.Add(
new SqlParameter("@SupportedDigitalOutputModes", SqlDbType.Int)
{
Value = record.SupportedDigitalOutputModes
});
cmd.Parameters.Add(new SqlParameter("@ModuleSerialNumber", SqlDbType.NVarChar, 16) { Value = record.ModuleSerialNumber });
cmd.Parameters.Add(new SqlParameter("@ModuleArrayIndex", SqlDbType.Int) { Value = record.ModuleArrayIndex });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
var error = Convert.ToInt32(errorNumberParam.Value);
var msg = Convert.ToString(errorMessageParam.Value);
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, $"Failed DASChannelsInsert {error} - {msg}");
return ErrorCodes.ERROR_UNKNOWN;
}
record.DaschannelId = Convert.ToInt32(newIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns DASChannels for given DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="hardwareId">string identifying hardware in the form of DASSerial_DASType
/// (or null for all records)</param>
/// <param name="channels"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
public ulong DASChannelsGet(IUserDbRecord user, IConnectionDetails connection, string hardwareId, out IDASChannelDBRecord[] channels)
{
channels = new IDASChannelDBRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChannelsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
var list = new List<IDASChannelDBRecord>();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@HardwareId", SqlDbType.NVarChar, 50) { Value = hardwareId });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new DASChannelDBRecord(reader));
}
channels = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns all the DAS serials associated with a given parent DAS
/// used for discovering which das are associated with a das in the db for encapsulated/compacted DAS
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="dasSerialNumber"></param>
/// <param name="childrenSerialNumbers"></param>
/// <returns>0 on success, all other values are errors</returns>
public ulong DASChildrenGet(IUserDbRecord user, IConnectionDetails connection, string dasSerialNumber, out string[] childrenSerialNumbers)
{
childrenSerialNumbers = new string[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASChildrenGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
var serials = new List<string>();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@ParentSerialNumber", SqlDbType.NVarChar) { Value = dasSerialNumber });
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var serial = Utility.GetString(reader, "SerialNumber", string.Empty);
if (!string.IsNullOrWhiteSpace(serial)) { serials.Add(serial); }
}
}
childrenSerialNumbers = serials.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong DASDelete(IUserDbRecord user, IConnectionDetails connection, int DASId, string serialNumber, bool embedded)
{
if (DASId <= 0 && string.IsNullOrEmpty(serialNumber))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
Console.WriteLine($"DASDelete executing sp");
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = DASId });
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = serialNumber });
cmd.Parameters.Add(new SqlParameter("@Embedded", SqlDbType.Bit) { Value = embedded });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
var error = Convert.ToInt32(errorNumber.Value);
var msg = Convert.ToString(errorMessage.Value);
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, $"DeleteDAS failed error: {error} - {msg}");
Console.WriteLine($"DASDelete {error} - {msg}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong DASUpdate(IUserDbRecord user, IConnectionDetails connection, IDASDBRecord das)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = 0 });
cmd.Parameters.Add(
new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = das.SerialNumber });
cmd.Parameters.Add(new SqlParameter("@Type", SqlDbType.Int) { Value = das.DASType });
cmd.Parameters.Add(new SqlParameter("@MaxModules", SqlDbType.Int) { Value = das.MaxModules });
cmd.Parameters.Add(new SqlParameter("@MaxMemory", SqlDbType.BigInt) { Value = das.MaxMemory });
cmd.Parameters.Add(
new SqlParameter("@MaxSampleRate", SqlDbType.Float)
{
Value = Convert.ToDecimal(das.MaxSampleRate)
});
cmd.Parameters.Add(
new SqlParameter("@MinSampleRate", SqlDbType.Float)
{
Value = Convert.ToDecimal(das.MinSampleRate)
});
cmd.Parameters.Add(
new SqlParameter("@FirmwareVersion", SqlDbType.NVarChar, 50) { Value = das.FirmwareVersion });
cmd.Parameters.Add(new SqlParameter("@CalDate", SqlDbType.DateTime) { Value = das.CalDate });
cmd.Parameters.Add(
new SqlParameter("@ProtocolVersion", SqlDbType.Int) { Value = das.ProtocolVersion });
cmd.Parameters.Add(
new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = das.LastModified });
cmd.Parameters.Add(
new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = das.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = das.Version });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = das.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastUsed", SqlDbType.DateTime) { Value = das.LastUsed });
cmd.Parameters.Add(
new SqlParameter("@LastUsedBy", SqlDbType.NVarChar, 50) { Value = das.LastUsedBy });
cmd.Parameters.Add(new SqlParameter("@Connection", SqlDbType.NVarChar, 50) { Value = das.Connection });
cmd.Parameters.Add(new SqlParameter("@Channels", SqlDbType.Int) { Value = das.Channels });
cmd.Parameters.Add(new SqlParameter("@Position", SqlDbType.NVarChar, 50) { Value = das.Position });
cmd.Parameters.Add(
new SqlParameter("@ChannelTypes", SqlDbType.NVarChar, 255)
{
Value = string.Join(",", das.ChannelTypes)
});
cmd.Parameters.Add(new SqlParameter("@Reprogramable", SqlDbType.Bit) { Value = das.IsProgrammable });
cmd.Parameters.Add(
new SqlParameter("@Reconfigurable", SqlDbType.Bit) { Value = das.IsReconfigurable });
cmd.Parameters.Add(new SqlParameter("@IsModule", SqlDbType.Bit) { Value = das.IsModule });
cmd.Parameters.Add(
new SqlParameter("@PositionOnDistributor", SqlDbType.SmallInt)
{
Value = das.PositionOnDistributor
});
cmd.Parameters.Add(
new SqlParameter("@PositionOnChain", SqlDbType.SmallInt) { Value = das.PositionOnChain });
cmd.Parameters.Add(new SqlParameter("@Port", SqlDbType.SmallInt) { Value = das.Port });
cmd.Parameters.Add(new SqlParameter("@ParentDAS", SqlDbType.NVarChar, 50) { Value = null == das.ParentDAS ? string.Empty : das.ParentDAS });
if (das.IsFirstUseValid)
{
if (null == das.FirstUseDate)
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = DFConstantsAndEnums.FIRST_USE_DATE_NOT_SET });
}
else
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = (DateTime)das.FirstUseDate });
}
}
else { cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime) { Value = DBNull.Value }); }
//to avoid confusion, if it's not a stand in it's also not test/group specific
if (null == das.TestId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = (int)das.TestId });
}
if (null == das.GroupId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = (int)das.GroupId });
}
cmd.Parameters.Add(new SqlParameter("@StandIn", SqlDbType.Bit) { Value = das.StandIn });
cmd.Parameters.Add(new SqlParameter("@MaxAAFRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MaxAAFRate) });
SqlParameter newIdParam = null;
newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
throw new Exception((string)errorMessageParam.Value);
}
das.DASId = Convert.ToInt32(newIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// Inserts a DAS record into the db
/// the DASId will be modified before return if insert is successful
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="das"></param>
/// <param name="iDASId">id of das in Db after insert</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors
/// returns ERROR_NOACCESS if user is not logged in</returns>
public ulong DASInsert(IUserDbRecord user, IConnectionDetails connection, IDASDBRecord das)
{
if (null == das)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DASInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(
new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = das.SerialNumber });
cmd.Parameters.Add(new SqlParameter("@Type", SqlDbType.Int) { Value = das.DASType });
cmd.Parameters.Add(new SqlParameter("@MaxModules", SqlDbType.Int) { Value = das.MaxModules });
cmd.Parameters.Add(new SqlParameter("@MaxMemory", SqlDbType.BigInt) { Value = das.MaxMemory });
cmd.Parameters.Add(
new SqlParameter("@MaxSampleRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MaxSampleRate) });
cmd.Parameters.Add(
new SqlParameter("@MinSampleRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MinSampleRate) });
cmd.Parameters.Add(
new SqlParameter("@FirmwareVersion", SqlDbType.NVarChar, 50) { Value = das.FirmwareVersion });
cmd.Parameters.Add(new SqlParameter("@CalDate", SqlDbType.DateTime) { Value = das.CalDate });
cmd.Parameters.Add(new SqlParameter("@ProtocolVersion", SqlDbType.Int) { Value = das.ProtocolVersion });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = das.LastModified });
cmd.Parameters.Add(
new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = das.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = das.Version });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = das.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastUsed", SqlDbType.DateTime) { Value = das.LastUsed });
cmd.Parameters.Add(new SqlParameter("@LastUsedBy", SqlDbType.NVarChar, 50) { Value = null == das.LastUsedBy ? string.Empty : das.LastUsedBy });
cmd.Parameters.Add(new SqlParameter("@Connection", SqlDbType.NVarChar, 50) { Value = das.Connection });
cmd.Parameters.Add(new SqlParameter("@Channels", SqlDbType.Int) { Value = das.Channels });
cmd.Parameters.Add(new SqlParameter("@Position", SqlDbType.NVarChar, 50) { Value = null == das.Position ? string.Empty : das.Position });
cmd.Parameters.Add(
new SqlParameter("@ChannelTypes", SqlDbType.NVarChar, 255)
{
Value = null == das.ChannelTypes ? "" : string.Join(",", das.ChannelTypes)
});
cmd.Parameters.Add(new SqlParameter("@Reprogramable", SqlDbType.Bit) { Value = das.IsProgrammable });
cmd.Parameters.Add(new SqlParameter("@Reconfigurable", SqlDbType.Bit) { Value = das.IsReconfigurable });
cmd.Parameters.Add(new SqlParameter("@IsModule", SqlDbType.Bit) { Value = das.IsModule });
cmd.Parameters.Add(
new SqlParameter("@PositionOnDistributor", SqlDbType.SmallInt) { Value = das.PositionOnDistributor });
cmd.Parameters.Add(
new SqlParameter("@PositionOnChain", SqlDbType.SmallInt) { Value = das.PositionOnChain });
cmd.Parameters.Add(new SqlParameter("@Port", SqlDbType.SmallInt) { Value = das.Port });
cmd.Parameters.Add(new SqlParameter("@ParentDAS", SqlDbType.NVarChar, 50) { Value = null == das.ParentDAS ? string.Empty : das.ParentDAS });
if (das.IsFirstUseValid)
{
if (null == das.FirstUseDate)
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = DFConstantsAndEnums.FIRST_USE_DATE_NOT_SET });
}
else
{
cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime)
{ Value = (DateTime)das.FirstUseDate });
}
}
else { cmd.Parameters.Add(new SqlParameter("@FirstUseDate", SqlDbType.DateTime) { Value = DBNull.Value }); }
//only standin das are allowed to be test/group specific
if (null == das.TestId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@TestId", SqlDbType.Int) { Value = das.TestId });
}
if (null == das.GroupId || !das.StandIn)
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = DBNull.Value });
}
else
{
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = das.GroupId });
}
cmd.Parameters.Add(new SqlParameter("@StandIn", SqlDbType.Bit) { Value = das.StandIn });
cmd.Parameters.Add(new SqlParameter("@MaxAAFRate", SqlDbType.Float) { Value = Convert.ToDecimal(das.MaxAAFRate) });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam =
new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam =
new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
throw new Exception((string)errorMessageParam.Value);
}
das.DASId = Convert.ToInt32(newIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns the DAS requested. If no DASId or serial number is specified, returns all DAS
/// user must be logged in
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="DASId">null is allowed, specify an ID or leave null</param>
/// <param name="DASSerial">null and empty string allowed, specify a serial number or leave null</param>
/// <param name="das">das found, can be null or empty</param>
/// <returns></returns>
public ulong DASGet(IUserDbRecord user, IConnectionDetails connection, int clientDbVersion, string DASSerial, string position, out IDASDBRecord[] das)
{
das = null;
var allDAS = new List<IDASDBRecord>();
var storedProcedureVersionToUse = 0;
SqlCommand cmd;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion, "sp_DASGet", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 50) { Value = DASSerial });
cmd.Parameters.Add(new SqlParameter("@Position", SqlDbType.NVarChar, 10) { Value = position });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
allDAS.Add(new DASDBRecord(reader));
}
reader.Close();
das = allDAS.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
}
}

View File

@@ -0,0 +1,204 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Groups;
using DTS.Common.Interface.TestSetups;
using DTS.Common.Interface.TestSetups.TestSetupsList;
using System;
namespace DbAPI.TestSetups
{
/// <summary>
/// defines functions to create, retrieve, update, delete test setups
/// </summary>
public interface ITestSetups
{
/// <summary>
/// deletes matching test setup hardware record
/// at least one parameter (id/dasid/testsetupid) must be specified
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="Id">id of test setup hardware record (null for all)</param>
/// <param name="dasId">id of das (null for all)</param>
/// <param name="testSetupId">id of test setup (null for all)</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupHardwareDelete(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
int? dasId,
int? testSetupId
);
/// <summary>
/// updates a test setup hardware record
/// </summary>
/// <param name="user">user committing update</param>
/// <param name="connection">connection update is being made on</param>
/// <param name="record">updated record</param>
/// <returns>0 on success, all other values are error codes</returns>
ulong TestSetupHardwareUpdate(IUserDbRecord user,
IConnectionDetails connection,
ITestSetupHardwareRecord record);
/// <summary>
/// inserts a new record
/// </summary>
/// <param name="user">user inserting record</param>
/// <param name="connection">connection being inserted on</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupHardwareInsert(IUserDbRecord user,
IConnectionDetails connection,
ITestSetupHardwareRecord record);
/// <summary>
/// retrieves all hardware meta data associated with test
/// [sample rate, aaf, etc]
/// </summary>
/// <param name="user">user retrieving hardware</param>
/// <param name="connection">connecting hardware is retrieved on</param>
/// <param name="testSetupId">id of test setup (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupHardwareGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int? testSetupId,
out ITestSetupHardwareRecord[] records);
/// <summary>
/// inserts a new group/test setup association into db
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="record">record to insert</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupGroupsInsert(IUserDbRecord user,
IConnectionDetails connection,
ITestSetupGroupRecord record);
/// <summary>
/// updates a group/test setup association in db
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection is being made on</param>
/// <param name="record">updated record</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupGroupsUpdate(IUserDbRecord user,
IConnectionDetails connection,
ITestSetupGroupRecord record);
/// <summary>
/// retrieves all group records matching search criteria
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection request is being made on</param>
/// <param name="groupId">database id of group (use null for all)</param>
/// <param name="testSetupId">database id of test setup (use null for all)</param>
/// <param name="testSetupName">test setup name for test setup (use null for all)</param>
/// <param name="groups">matching groups</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupGroupsGet(IUserDbRecord user,
IConnectionDetails connection,
int? groupId,
int? testSetupId,
string testSetupName,
out ITestSetupGroupRecord[] groups
);
/// <summary>
/// Commits a change to the IsDirty or IsComplete flags in the db for a test
/// </summary>
/// <param name="user">user committing change</param>
/// <param name="connection">connection change is being committed on</param>
/// <param name="name">name of test setup to modify</param>
/// <param name="dirty">whether to set dirty flag or not. Dirty flag indicates
/// whether the test setup has been checked for completeness and readiness to run</param>
/// <param name="complete">whether the test setup is ready to run or not</param>
/// <param name="error">error message(s) associated with test setup, if any</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupsMarkIsDirtyIsComplete(IUserDbRecord user,
IConnectionDetails connection,
string name,
bool dirty,
bool complete,
string error);
/// <summary>
/// deletes all test setups matching criteria
/// </summary>
/// <param name="user">user deleting test setups</param>
/// <param name="connection">connection tests are being deleted on</param>
/// <param name="date">date of oldest allowed test setup</param>
/// <returns>0 (ERROR_SUCCESS) on success. All other values are error codes.</returns>
ulong TestSetupsDeleteByDate(IUserDbRecord user,
IConnectionDetails connection,
DateTime date);
/// <summary>
/// deletes all test setups and groups
/// </summary>
/// <param name="user">user requesting deletes</param>
/// <param name="connection">connection to delete on</param>
/// <returns>0 (ERROR_SUCCESS) on success. All other values are error codes</returns>
ulong TestSetupsAndGroupsDeleteAll(IUserDbRecord user,
IConnectionDetails connection);
/// <summary>
/// Deletes all test setups that match the search criteria
/// </summary>
/// <param name="user">user deleting test setups</param>
/// <param name="connection">connection to delete test setups on</param>
/// <param name="ids">ids of test setups to delete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupsDeleteById(IUserDbRecord user,
IConnectionDetails connection,
int[] ids);
/// <summary>
/// deletes all test setups that match the search criteria
/// </summary>
/// <param name="user">user deleting test setups</param>
/// <param name="connection">connection to delete test setups on</param>
/// <param name="names">names of test setups to delete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestSetupsDeleteByName(IUserDbRecord user,
IConnectionDetails connection,
string[] names);
/// <summary>
/// commits a test setup into the database
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection record is being committed on</param>
/// <param name="clientDbVersion">the database version of the client code</param>
/// <param name="record">record being committed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong TestSetupsUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
ref ITestSetupRecord record);
/// <summary>
/// Retrieves all test setups which match given search criteria
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection over which query is to be made</param>
/// <param name="clientDbVersion">the database version of the client code</param>
/// <param name="testSetupId">database id of test setup (can be null)</param>
/// <param name="testSetupName">name of test setup (can be null or empty)</param>
/// <param name="defaultROIStart">start time for any ROIs that have to be generated
/// some old test setups may not have ROIs specified for every event</param>
/// <param name="defaultROIEnd">end time for any ROIs that have to be generated
/// some old test setups may not have ROIs specified for every event</param>
/// <param name="defaultIgnoreShortedStart">whether or not to ignore a shorted start
/// since we may be using a Version 91 database that doesn't store this</param>
/// <param name="defaultIgnoreShortedTrigger">whether or not to ignore a shorted trigger
/// since we may be using a Version 91 database that doesn't store this</param>
/// <param name="records">matching records</param>
/// <param name="errors">any errors encountered while retrieving test setups</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong TestSetupsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int? testSetupId,
string testSetupName,
double defaultROIStart,
double defaultROIEnd,
bool defaultIgnoreShortedStart,
bool defaultIgnoreShortedTrigger,
out ITestSetupRecord[] records,
out string[] errors);
}
}

View File

@@ -0,0 +1,272 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes;
using DTS.Common.Classes.TestSetups;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.TestSetups;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
namespace DbAPI.TestSetups
{
/// <summary>
/// Handles calculated channel functions
/// <inheritdoc cref="ICalculatedChannels"/>
/// </summary>
internal class CalculatedChannels : ICalculatedChannels
{
/// <summary>
/// removes calculated channel from database
/// </summary>
/// <param name="user">user committing delete</param>
/// <param name="connection">connection over which to delete</param>
/// <param name="calculatedChannelId">database id of calculated channel to delete</param>
/// <returns></returns>
public ulong CalculatedChannelsDelete(IUserDbRecord user,
IConnectionDetails connection,
int calculatedChannelId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CalculatedChannelsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@CalculatedChannelsId", SqlDbType.Int) { Value = calculatedChannelId });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.CalculatedChannels, $"sp_CalculatedChannelsDelete failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.CalculatedChannels, $"sp_CalculatedChannelsDelete failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// inserts a new calculated channel into the database
/// original record is modified with database id after insert is complete
/// </summary>
/// <param name="user">user adding record</param>
/// <param name="connection">connection record is being added on</param>
/// <param name="record">record being added</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong CalculatedChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref ICalculatedChannelRecord record)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == record)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CalculatedChannelsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Operation", SqlDbType.Int) { Value = (int)record.Operation });
cmd.Parameters.Add(new SqlParameter("@CalculatedChannelValueCode", SqlDbType.NVarChar, 255)
{ Value = record.CalculatedValueCode });
cmd.Parameters.Add(new SqlParameter("@InputChannelIds", SqlDbType.VarBinary)
{
Value = Utility.GetBytesFromStringArray(record.InputChannelIds,
CultureInfo.InvariantCulture.TextInfo.ListSeparator)
});
cmd.Parameters.Add(new SqlParameter("@CFCForInputChannels", SqlDbType.NVarChar, 255) { Value = record.CFCForInputChannels });
cmd.Parameters.Add(new SqlParameter("@CFCForOutput", SqlDbType.NVarChar, 255)
{ Value = record.ChannelFilterClassForOutput });
cmd.Parameters.Add(new SqlParameter("TestSetupName", SqlDbType.NVarChar, 255)
{ Value = record.TestSetupName });
cmd.Parameters.Add(new SqlParameter("@CCName", SqlDbType.NVarChar, 255) { Value = record.Name });
cmd.Parameters.Add(new SqlParameter("@ViewInRealtime", SqlDbType.Bit) { Value = record.ViewInRealtime });
cmd.Parameters.Add(new SqlParameter("@ClipLength", SqlDbType.Int) { Value = record.ClipLength });
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.CalculatedChannels, $"sp_CalculatedChannelsInsert failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
record.Id = Convert.ToInt32(newId.Value);
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.CalculatedChannels, $"sp_CalculatedChannelsInsert failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// updates calculated channel in the database
/// </summary>
/// <param name="user">user updating record</param>
/// <param name="connection">connection record is being updated on</param>
/// <param name="record">record to be updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong CalculatedChannelsUpdate(IUserDbRecord user,
IConnectionDetails connection,
ICalculatedChannelRecord record)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == record)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CalculatedChannelsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) { Value = record.Id });
cmd.Parameters.Add(new SqlParameter("@Operation", SqlDbType.Int) { Value = (int)record.Operation });
cmd.Parameters.Add(new SqlParameter("@CalculatedChannelValueCode", SqlDbType.NVarChar, 255)
{ Value = record.CalculatedValueCode });
cmd.Parameters.Add(new SqlParameter("@InputChannelIds", SqlDbType.VarBinary)
{ Value = Utility.GetBytesFromStringArray(record.InputChannelIds, CultureInfo.InvariantCulture.TextInfo.ListSeparator) });
cmd.Parameters.Add(new SqlParameter("@CFCForInputChannels", SqlDbType.NVarChar) { Value = record.CFCForInputChannels });
cmd.Parameters.Add(new SqlParameter("@CFCForOutput", SqlDbType.NVarChar, 255)
{ Value = record.ChannelFilterClassForOutput });
cmd.Parameters.Add(new SqlParameter("@TestSetupName", SqlDbType.NVarChar, 255)
{ Value = record.TestSetupName });
cmd.Parameters.Add(new SqlParameter("@CCName", SqlDbType.NVarChar, 255) { Value = record.Name });
cmd.Parameters.Add(new SqlParameter("@ViewInRealtime", SqlDbType.Bit) { Value = record.ViewInRealtime });
cmd.Parameters.Add(new SqlParameter("@ClipLength", SqlDbType.Int) { Value = record.ClipLength });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.CalculatedChannels, $"sp_CalculatedChannelsUpdate failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.CalculatedChannels, $"sp_CalculatedChannelsUpdate failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// retrieves all CalculatedChannel records matching search criteria
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="calculatedChannelId">database id of calculated channel (can be null)</param>
/// <param name="testSetupName">test setup calculated channel(s) belong to (can be empty)</param>
/// <param name="records">all matching records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong CalculatedChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int? calculatedChannelId,
string testSetupName,
out ICalculatedChannelRecord[] records)
{
records = new ICalculatedChannelRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CalculatedChannelsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null == calculatedChannelId)
{
cmd.Parameters.Add(new SqlParameter("@CalculatedChannelsId", SqlDbType.Int) { Value = null });
}
else
{
cmd.Parameters.Add(new SqlParameter("@CalculatedChannelsId", SqlDbType.Int) { Value = (int)calculatedChannelId });
}
cmd.Parameters.Add(new SqlParameter("@TestSetupName", SqlDbType.NVarChar, 50) { Value = testSetupName });
var reader = cmd.ExecuteReader();
var list = new List<ICalculatedChannelRecord>();
while (reader.Read())
{
list.Add(new CalculatedChannelRecord(reader));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"sp_CalculatedChannelsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
}
}

View File

@@ -0,0 +1,275 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes.TestSetups;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Graphs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace DbAPI.TestSetups
{
/// <summary>
/// Handles graph functions
/// <inheritdoc cref="IGraphs"/>
/// </summary>
internal class Graphs : IGraphs
{
/// <summary>
/// removes a record from the db
/// </summary>
/// <param name="user">user removing record</param>
/// <param name="connection">connection record is being removed on</param>
/// <param name="graphId">database id of record being removed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GraphsDelete(IUserDbRecord user, IConnectionDetails connection, int graphId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestGraphsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = null });
cmd.Parameters.Add(new SqlParameter("@GraphId", SqlDbType.Int) { Value = graphId });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsDelete error: {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsInsert exception {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// inserts a record into the db, updates GraphId of record after insert with database id
/// </summary>
/// <param name="user">user inserting record</param>
/// <param name="connection">connection record is being inserted on</param>
/// <param name="record">record being inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GraphsInsert(IUserDbRecord user, IConnectionDetails connection, ref IGraphRecord record)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestGraphsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
if (null == record)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsUpdate no record supplied to update");
cmd.Connection.Dispose();
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = record.TestSetupId });
cmd.Parameters.Add(new SqlParameter("@GraphName", SqlDbType.NVarChar, 50)
{ Value = record.GraphName });
cmd.Parameters.Add(new SqlParameter("@GraphDescription", SqlDbType.NVarChar, 50)
{ Value = record.GraphDescription });
cmd.Parameters.Add(new SqlParameter("@Channels", SqlDbType.NVarChar, 2048) { Value = record.ChannelsString });
cmd.Parameters.Add(new SqlParameter("@UseDomainMin", SqlDbType.Bit) { Value = record.UseDomainMin });
cmd.Parameters.Add(new SqlParameter("@DomainMin", SqlDbType.Float) { Value = record.DomainMin });
cmd.Parameters.Add(new SqlParameter("@UseDomainMax", SqlDbType.Bit) { Value = record.UseDomainMax });
cmd.Parameters.Add(new SqlParameter("@DomainMax", SqlDbType.Float) { Value = record.DomainMax });
cmd.Parameters.Add(new SqlParameter("@UseRangeMin", SqlDbType.Bit) { Value = record.UseRangeMin });
cmd.Parameters.Add(new SqlParameter("@RangeMin", SqlDbType.Float) { Value = record.RangeMin });
cmd.Parameters.Add(new SqlParameter("@UseRangeMax", SqlDbType.Bit) { Value = record.UseRangeMax });
cmd.Parameters.Add(new SqlParameter("@RangeMax", SqlDbType.Float) { Value = record.RangeMax });
cmd.Parameters.Add(
new SqlParameter("@Thresholds", SqlDbType.NVarChar, 2048) { Value = record.ThresholdsString });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = record.LocalOnly });
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value && 0 != Convert.ToInt32(errorNumber.Value))
{
throw new Exception((string)errorMessage.Value);
}
record.GraphId = Convert.ToInt32(newId.Value);
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsInsert exception {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// updates a record in the database
/// </summary>
/// <param name="user">user updating record</param>
/// <param name="connection">connection record is being updated on</param>
/// <param name="record">record to update</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GraphsUpdate(IUserDbRecord user, IConnectionDetails connection, IGraphRecord record)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestGraphsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
if (null == record)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsUpdate no record supplied to update");
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@GraphId", SqlDbType.Int) { Value = record.GraphId });
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = record.TestSetupId });
cmd.Parameters.Add(new SqlParameter("@GraphName", SqlDbType.NVarChar, 50)
{ Value = record.GraphName });
cmd.Parameters.Add(new SqlParameter("@GraphDescription", SqlDbType.NVarChar, 50)
{ Value = record.GraphDescription });
cmd.Parameters.Add(new SqlParameter("@Channels", SqlDbType.NVarChar, 2048) { Value = record.ChannelsString });
cmd.Parameters.Add(new SqlParameter("@UseDomainMin", SqlDbType.Bit) { Value = record.UseDomainMin });
cmd.Parameters.Add(new SqlParameter("@DomainMin", SqlDbType.Float) { Value = record.DomainMin });
cmd.Parameters.Add(new SqlParameter("@UseDomainMax", SqlDbType.Bit) { Value = record.UseDomainMax });
cmd.Parameters.Add(new SqlParameter("@DomainMax", SqlDbType.Float) { Value = record.DomainMax });
cmd.Parameters.Add(new SqlParameter("@UseRangeMin", SqlDbType.Bit) { Value = record.UseRangeMin });
cmd.Parameters.Add(new SqlParameter("@RangeMin", SqlDbType.Float) { Value = record.RangeMin });
cmd.Parameters.Add(new SqlParameter("@UseRangeMax", SqlDbType.Bit) { Value = record.UseRangeMax });
cmd.Parameters.Add(new SqlParameter("@RangeMax", SqlDbType.Float) { Value = record.RangeMax });
cmd.Parameters.Add(
new SqlParameter("@Thresholds", SqlDbType.NVarChar, 2048) { Value = record.ThresholdsString });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = record.LocalOnly });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsUpdate exception {errorNumber.Value} - {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"GraphsUpdate exception {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// retrieves all graph records matching search criteria
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="graphId">graph to query for (can be null)</param>
/// <param name="testSetupId">test setup graph belongs to</param>
/// <param name="records">all matching records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
public ulong GraphsGet(IUserDbRecord user, IConnectionDetails connection,
int? graphId,
int? testSetupId,
out IGraphRecord[] records)
{
records = new IGraphRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestGraphsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
if (null == graphId)
{
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = null });
}
else { cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = (int)graphId }); }
if (null == testSetupId)
{
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = null });
}
else
{
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = (int)testSetupId });
}
var reader = cmd.ExecuteReader();
var list = new List<IGraphRecord>();
while (reader.Read())
{
var graph = new GraphRecord(reader);
list.Add(graph);
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"sp_GraphsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
}
}

View File

@@ -0,0 +1,388 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.Sensors;
using DTS.Common.Interface.Sensors.AnalogDiagnostics;
using System;
namespace DbAPI.Sensors
{
/// <summary>
/// Sensor related functions (GetAnalogSensors, InsertUpdateSensor, DeleteSensor)
/// </summary>
public interface ISensors
{
/// <summary>
/// returns all matching analog diagnostic records
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection being queried over</param>
/// <param name="Id">id of record, or null for all records</param>
/// <param name="diagnosticRunId">id of diagnostic run, or null for all records</param>
/// <param name="sensorId">sensor id to query for, or null for all</param>
/// <param name="sensorSerialNumber">serial number to query for, or null for all</param>
/// <returns></returns>
ulong SensorsAnalogDiagnosticsGet(IUserDbRecord user, IConnectionDetails connection,
long? Id, long? diagnosticRunId, int? sensorId, string sensorSerialNumber, out IDiagnosticEntry [] records);
/// <summary>
/// retrieves any matching
/// </summary>
/// <param name="user">user making query</param>
/// <param name="Id">diagnostic run id to query for or null for any id</param>
/// <param name="testId">test setup id to query for or null for any id</param>
/// <param name="testName">test setup name to query for or null for any name</param>
/// <param name="connection">connection to query on</param>
/// <param name="records">out records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogDiagnosticRunGet(IUserDbRecord user, IConnectionDetails connection,
long? Id, int? testId, string testName, out IDiagnosticRun [] records);
/// <summary>
/// update or inserts all entries passed in
/// </summary>
/// <param name="user">user committing entries</param>
/// <param name="connection">connection to commit over</param>
/// <param name="entries">entries to insert or update</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogDiagnosticUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IDiagnosticEntry entry);
/// <summary>
/// updates or inserts a Diagnostic run into the database
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection diagnostic run is being committed over</param>
/// <param name="run">the record to insert or update</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogDiagnosticRunUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IDiagnosticRun run);
/// <summary>
/// updates or inserts an input stream record into the database
/// Database id is modified on record on an insert operation
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection record is being committed over</param>
/// <param name="record">record to be inserted or updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsInputStreamUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IStreamInputRecord record);
/// <summary>
/// retrieves matching input streams from database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection over which to look for records</param>
/// <param name="Id">database id of record (use null for all)</param>
/// <param name="SerialNumber">serial number of record (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsInputStreamGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out IStreamInputRecord[] records);
/// <summary>
/// retrieves matching thermocouplers from database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection over which to look for records</param>
/// <param name="Id">database id of record (use null for all)</param>
/// <param name="SerialNumber">serial number of record (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsThermocouplerGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int? Id,
string SerialNumber,
out IThermocouplerRecord[] records);
/// <summary>
/// updates or inserts an output stream record into the database
/// Database id is modified on record on an insert operation
/// </summary>
/// <param name="user">user committing record</param>
/// <param name="connection">connection record is being committed over</param>
/// <param name="record">record to be inserted or updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsOutputStreamUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IStreamOutputRecord record);
/// <summary>
/// retrieves matching output streams from database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection over which to look for records</param>
/// <param name="Id">database id of record (use null for all)</param>
/// <param name="SerialNumber">serial number of record (use null for all)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsOutputStreamGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out IStreamOutputRecord[] records);
/// <summary>
/// updates or inserts a new UART record into the database
/// Id is updated if a new record is inserted
/// </summary>
/// <param name="user">user committing UART</param>
/// <param name="connection">connection UART should be committed on</param>
/// <param name="record">record being inserted or updated</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsUARTUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IUARTRecord record);
/// <summary>
/// retrieves UART settings
/// </summary>
/// <param name="user">user making requests</param>
/// <param name="connection">connection request sh</param>
/// <param name="Id">Id to search for (use null for all)</param>
/// <param name="SerialNumber">serial number to search for (use null or empty for all)</param>
/// <param name="records">matching records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsUARTGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out IUARTRecord[] records);
ulong SensorsCanGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string SerialNumber,
out ICANRecord[] records);
ulong SensorsCanUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ref ICANRecord record);
/// <summary>
/// commits a digital output setting to the db
/// The record will be modified with a new database id if
/// a new record is inserted
/// </summary>
/// <param name="user">user making commit</param>
/// <param name="connection">connection over which to commit</param>
/// <param name="record">the record to commit</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsDigitalOutUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
IDigitalOutDbRecord record);
/// <summary>
/// retrieves all matching digital output settings in the db
/// </summary>
/// <param name="user">user requesting records</param>
/// <param name="connection">connection to query records on</param>
/// <param name="Id">Database id of records (can be null)</param>
/// <param name="serialNumber">serial number/name of setting (can be null)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsDigitalOutGet(
IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string serialNumber,
out IDigitalOutDbRecord[] records);
/// <summary>
/// inserts or updates a digital input record into the db. If a record is inserted
/// then the original record is updated with the database id of the entry
/// </summary>
/// <param name="user">user committing record </param>
/// <param name="connection"></param>
/// <param name="record"></param>
/// <returns></returns>
ulong SensorsDigitalInUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
IDigitalInDbRecord record);
/// <summary>
/// retrieves any digital input settings matching input criteria
/// in the database
/// </summary>
/// <param name="user">user making request</param>
/// <param name="connection">connection to query over</param>
/// <param name="id">Database Id of digital input setting (can be null)</param>
/// <param name="serialNumber">serial number of setting (can be null)</param>
/// <param name="eId">Electronic id of setting (can be null)</param>
/// <param name="records">all matching records</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsDigitalInGet(IUserDbRecord user,
IConnectionDetails connection,
int? id,
string serialNumber,
string eId,
out IDigitalInDbRecord[] records);
/// <summary>
/// Inserts or updates a squib setting in the db
/// setting is modified with new db id after execution
/// </summary>
/// <param name="user">user inserting setting</param>
/// <param name="connection">connection for inserting</param>
/// <param name="record">record to be inserted</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsSquibUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
ISquibDbRecord record);
/// <summary>
/// retrieves all squib settings matching input criteria
/// </summary>
/// <param name="user">user requesting squib settings</param>
/// <param name="connection">connection for retrieving squib settings</param>
/// <param name="eId">Electronic Id </param>
/// <param name="Id">Database Id for squib setting</param>
/// <param name="serialNumber">serial number/name of squib setting</param>
/// <param name="records">output records discovered</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsSquibGet(IUserDbRecord user,
IConnectionDetails connection,
int? Id,
string serialNumber,
string eId,
out ISquibDbRecord[] records);
/// <summary>
/// Deletes ALL sensors in the db
/// </summary>
/// <param name="user">user deleting sensors</param>
/// <param name="connection">connection sensors to be deleted on</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsDeleteAll(IUserDbRecord user,
IConnectionDetails connection);
/// <summary>
/// retrieves the bridge resistance for a sensor
/// </summary>
/// <param name="user">user making query</param>
/// <param name="connection">connection query is being made on</param>
/// <param name="serialNumber">serial number of sensor</param>
/// <param name="bridgeResistance">output bridge resistance of sensor</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogBridgeResistanceGet(IUserDbRecord user,
IConnectionDetails connection,
string serialNumber,
out double bridgeResistance);
/// <summary>
/// deletes all sensor calibrations matching criteria
/// nulls are wild cards, so passing in all nulls will
/// delete all calibrations
/// </summary>
/// <param name="user">user deleting calibrations</param>
/// <param name="connection">connection to use for deletes</param>
/// <param name="sensorSerialNumber">allows null</param>
/// <param name="calibrationDate">allows null</param>
/// <param name="modifyDate">allows null</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorCalibrationsDelete(IUserDbRecord user,
IConnectionDetails connection,
string sensorSerialNumber,
DateTime? calibrationDate,
DateTime? modifyDate
);
/// <summary>
/// inserts a new calibration record
/// </summary>
/// <param name="user">user submitting record</param>
/// <param name="connection">connection record is being submitted on</param>
/// <param name="cal">calibration record</param>
/// <param name="sensorType">type of sensor</param>
/// <param name="setCalibrationId"></param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorCalibrationsInsert(IUserDbRecord user,
IConnectionDetails connection,
ISensorCalDbRecord cal,
int sensorType,
bool setCalibrationId);
/// <summary>
/// deletes all sensors matching criteria
/// sensor types are defined in table SensorsType
/// 0 - analog
/// 1 - digital in
/// 2 - digital out
/// 3 - squib
/// 4 - UART
/// </summary>
/// <param name="user">user deleting sensors</param>
/// <param name="connection">connection sensors are being deleted on</param>
/// <param name="sensorId">id in database</param>
/// <param name="sensorType">type of sensor</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are errors</returns>
ulong SensorsDelete(IUserDbRecord user,
IConnectionDetails connection,
int sensorId,
int sensorType);
/// <summary>
/// commits an analog sensor to the db
/// </summary>
/// <param name="user">DataPRO user making commit</param>
/// <param name="connection">connection commit is being made on</param>
/// <param name="record">the record being committed</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorsAnalogUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
IAnalogDbRecord record);
/// <summary>
/// retrieves all calibrations matching search criteria
/// </summary>
/// <param name="user">user querying calibrations</param>
/// <param name="connection">connection user is using</param>
/// <param name="sensorId">sensor id (allows null)</param>
/// <param name="serialNumber">serial number (allows null and empty)</param>
/// <param name="calibrations">any calibrations matching criteria</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong SensorCalibrationsGet(IUserDbRecord user,
IConnectionDetails connection,
int? sensorId,
string serialNumber,
out ISensorCalDbRecord[] calibrations
);
/// <summary>
/// retrieves all analog sensors matching search criteria
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="sensorId">sensor database id (allows null)</param>
/// <param name="serialNumber">sensor serial number (allows null)</param>
/// <param name="eId">electronic Id (DALLAS or TEDS id value)</param>
/// <param name="sensors">any sensors matching criteria</param>
/// <returns>0 (ERROR_SUCCES) on success, all other values are error codes</returns>
ulong SensorsAnalogGet(IUserDbRecord user,
IConnectionDetails connection,
int? sensorId,
string serialNumber,
string eId,
out IAnalogDbRecord[] sensors);
/// <summary>
/// retrieves all analog sensors matching search criteria
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="serialNumber">sensor serial number (allows null)</param>
/// <param name="sensors">any sensors matching criteria</param>
/// <returns>0 (ERROR_SUCCES) on success, all other values are error codes</returns>
ulong SensorsGet(IUserDbRecord user,
IConnectionDetails connection,
string serialNumber,
out ISensorDbRecord[] sensors);
ulong UpdateAssemblySensorUsageCount(IUserDbRecord user,
IConnectionDetails connection,
string assemblyName,
int newUsageCount);
/// <summary>
/// Updates a sensor's (total) usage count
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="sd">The sensor to be updated</param>
/// <returns></returns>
ulong UpdateSensorUsageCount(IUserDbRecord user,
IConnectionDetails connection,
ISensorData sd);
/// <summary>
/// Updates a sensor calibration's usage count
/// </summary>
/// <param name="user">user querying sensors</param>
/// <param name="connection">connection is using</param>
/// <param name="sd">The sensor to be updated</param>
/// <returns></returns>
ulong UpdateSensorCalibrationUsageCount(IUserDbRecord user,
IConnectionDetails connection,
int sensorId,
int sensorCalibrationId,
int newUsageCount);
}
}

View File

@@ -0,0 +1,81 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using System;
using DTS.Common.Classes.TestEngineerDetails;
using DTS.Common.Interface.TestMetaData;
namespace DbAPI.TestEngineerDetails
{
/// <summary>
/// TestEngineerDetails related functions (GetTestEngineerDetails, )
/// </summary>
public interface ITestEngineerDetails
{
/// <summary>
/// Inserts a new record in the TestEngineerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testEngineerDetailsDbRecord"></param>
/// <param name="newId">The Id of the new record in the TestEngineerDetails table</param>
/// <param name="errorString">Error string returned, possibly from sp_TestEngineerDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestEngineerDetailsInsert(IUserDbRecord user,
IConnectionDetails connection,
TestEngineerDetailsDbRecord testEngineerDetailsDbRecord,
out int newId,
out string errorString);
/// <summary>
/// Updates an existing record in the TestEngineerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name = "testEngineerDetailsDbRecord"></param>
/// <param name="errorString">Error string returned, possibly from sp_TestEngineerDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestEngineerDetailsUpdate(IUserDbRecord user,
IConnectionDetails connection,
TestEngineerDetailsDbRecord testEngineerDetailsDbRecord,
out string errorString);
/// <summary>
/// Updates an existing record or Inserts a new record in the TestEngineerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name = "testEngineerDetailsDbRecord"></param>
/// <param name="errorString">Error string returned, possibly from sp_TestEngineerDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestEngineerDetailsUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
TestEngineerDetailsDbRecord testEngineerDetailsDbRecord,
out string errorString);
/// <summary>
/// retrieves all test engineers matching search criteria
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="name">Name in the TestEngineerDetails table</param>
/// <param name="testEngineerDetailsDbRecords">null, or records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestEngineerDetailsGet(IUserDbRecord user,
IConnectionDetails connection,
string name,
out ITestEngineerDetailsDbRecord[] testEngineerDetailsDbRecords);
/// <summary>
/// Deletes an entry in the TestEngineerDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="name">Name in the TestEngineerDetails table</param>
/// <param name="errorString">Error string returned, possibly from sp_TestEngineerDetailsDelete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong TestEngineerDetailsDelete(IUserDbRecord user,
IConnectionDetails connection,
string name,
out string errorString);
}
}

View File

@@ -0,0 +1,71 @@
namespace DbAPI.Connections
{
/// <summary>
/// Basic implementation of <see cref="IConnectionDetails"/>
/// <inheritdoc cref="IConnectionDetails" />
/// </summary>
public class ConnectionDetails : IConnectionDetails
{
public virtual bool UseNTLMAuthentication { get; set; } = true;
public virtual string DbUser { get; set; } = "DataPROUser";
public virtual string DbUserPassword { get; set; } = "DTSSealBeachHQ";
public virtual string InstanceName { get; set; } = "DataPROInstance";
public virtual string DbServer { get; set; } = @"(localdb)\DataPROInstance";
public virtual string DbName { get; set; } = "DataPRO";
public virtual bool UsingCentralizedDb { get; set; } = false;
public virtual string DbFolderPath { get; set; } = "";
public virtual string AttachDbsBatPath { get; set; } = "";
public virtual string SqlDbPath { get; set; } = "";
public virtual string ODBCToolsPath { get; set; } = "";
/// <summary>
/// holds the code version of the database, what we would use if available
/// should be initialized by clients
/// </summary>
public int ClientDbVersion { get; set; }
/// <summary>
/// holds the version of the database, what we will be using
/// should be initialized by clients
/// </summary>
public int ConnectionDbVersion { get; set; }
protected string _Connection = null;
public virtual string GetConnectionString()
{
if (null != _Connection) { return _Connection; }
_Connection = UseNTLMAuthentication
? $"Server={DbServer};Database={DbName};Trusted_Connection=TRUE;"
: $"Server={DbServer};Database={DbName};User Id={DbUser};Password={DbUserPassword};";
return _Connection;
}
public override string ToString()
{
return UsingCentralizedDb ? $"{DbServer}\\{DbName}" : $"Local\\{DbName}";
}
public ConnectionDetails() { }
public ConnectionDetails(ConnectionDetails details)
{
UseNTLMAuthentication = details.UseNTLMAuthentication;
DbUser = details.DbUser;
DbUserPassword = details.DbUserPassword;
InstanceName = details.InstanceName;
DbServer = details.DbServer;
DbName = details.DbName;
UsingCentralizedDb = details.UsingCentralizedDb;
DbFolderPath = details.DbFolderPath;
AttachDbsBatPath = details.AttachDbsBatPath;
SqlDbPath = details.SqlDbPath;
ODBCToolsPath = details.ODBCToolsPath;
_Connection = details._Connection;
ClientDbVersion = details.ClientDbVersion;
ConnectionDbVersion = details.ConnectionDbVersion;
}
public virtual IConnectionDetails Clone()
{
return new ConnectionDetails(this);
}
}
}

View File

@@ -0,0 +1,417 @@
using System.Collections.Generic;
using DbAPI.Connections;
using DbAPI.Errors;
using DTS.Common.Classes.TestSetups;
using DTS.Common.Interface.Database;
using DTS.Common.Interface.TestSetups;
using System.Data;
using System.Data.SqlClient;
using System;
using DbAPI.Logging;
using System.Diagnostics;
using DTS.Common;
namespace DbAPI.TestSetups
{
/// <summary>
/// Handles RegionsOfInterest functions
/// </summary>
internal class RegionsOfInterest : IRegionsOfInterest
{
/// <summary>
/// Removes records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <returns></returns>
public ulong RegionsOfInterestDelete(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId)
{
return TestSetupROIsDelete(user, connection, testSetupId);
}
/// <summary>
/// Inserts records into the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="regionOfInterest">The class that is split between the TestSetupROIs and ROIPeriodChannels tables</param>
/// <returns></returns>
public ulong RegionsOfInterestInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupId,
DTS.Common.Interface.RegionOfInterest.IRegionOfInterest regionOfInterest)
{
var hResult = TestSetupROIsInsert(user, connection, testSetupId, regionOfInterest, out int testSetupROIId);
if (hResult == ErrorCodes.ERROR_SUCCESS && testSetupROIId > 0)
{
var channelIndex = 0;
foreach (var channelId in regionOfInterest.ChannelIds)
{
var channelName = regionOfInterest.ChannelNames[channelIndex];
hResult = ROIPeriodChannelsInsert(user, connection, clientDbVersion, testSetupROIId, channelName, channelId);
if (hResult != ErrorCodes.ERROR_SUCCESS)
{
return hResult;
}
channelIndex++;
}
return ErrorCodes.ERROR_SUCCESS;
}
else
{
return ErrorCodes.ERROR_UNKNOWN;
}
}
/// <summary>
/// Gets records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="records">The array of records combined from the TetSetupROIs and ROIPeriodChannels tables</param>
/// <returns></returns>
public ulong RegionsOfInterestGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupId,
out DTS.Common.Interface.RegionOfInterest.IRegionOfInterest[] records)
{
records = new DTS.Common.Interface.RegionOfInterest.IRegionOfInterest[0];
var list = new List<DTS.Common.Interface.RegionOfInterest.IRegionOfInterest>();
TestSetupROIsGet(user, connection, testSetupId, out var testSetupROIRecords);
foreach (var testSetupROIRecord in testSetupROIRecords)
{
ROIPeriodChannelsGet(user, connection, clientDbVersion, testSetupROIRecord.TestSetupROIId, out var roiPeriodChannelRecords);
var channelNameList = new List<string>();
var channelIdList = new List<long>();
foreach (var roiPeriodChannelRecord in roiPeriodChannelRecords)
{
var serialNumberIndex = roiPeriodChannelRecord.ChannelName.LastIndexOf("\\");
if (serialNumberIndex > -1)
{
var serialNumber = roiPeriodChannelRecord.ChannelName.Substring(serialNumberIndex + 1);
var hardwareChannelName = roiPeriodChannelRecord.ChannelName.Substring(0, serialNumberIndex);
var newChannelName = RegionOfInterest.GetChanName(serialNumber, hardwareChannelName);
channelNameList.Add(newChannelName);
}
else
{
channelNameList.Add(roiPeriodChannelRecord.ChannelName);
}
channelIdList.Add(roiPeriodChannelRecord.ChannelId);
}
list.Add(new RegionOfInterest()
{
Suffix = testSetupROIRecord.Suffix,
Start = testSetupROIRecord.ROIStart,
End = testSetupROIRecord.ROIEnd,
IsEnabled = testSetupROIRecord.IsEnabled,
IsDefault = testSetupROIRecord.IsDefault,
ChannelNames = channelNameList.ToArray(),
ChannelIds = channelIdList.ToArray()
});
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Removes records from the TestSetupROIs and ROIPeriodChannels tables
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <returns></returns>
public ulong TestSetupROIsDelete(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestSetupROIsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = testSetupId });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
#endregion params
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, $"sp_TestSetupROIsDelete failed: {errorNumber.Value} : {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, $"sp_TestSetupROIsDelete failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// Inserts records into the TestSetupROIs table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="regionOfInterest">The class that will have a portion stored in the TestSetupROIs table</param>
/// <param name="testSetupROIId">The new value of the Primary key of the TestSetupROIs table</param>
/// <returns></returns>
public ulong TestSetupROIsInsert(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId,
DTS.Common.Interface.RegionOfInterest.IRegionOfInterest regionOfInterest,
out int testSetupROIId)
{
testSetupROIId = 0;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (null == regionOfInterest)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestSetupROIsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.Int) { Value = testSetupId });
cmd.Parameters.Add(new SqlParameter("@Suffix", SqlDbType.NVarChar, 50) { Value = regionOfInterest.Suffix });
cmd.Parameters.Add(new SqlParameter("@ROIStart", SqlDbType.Float) { Value = regionOfInterest.Start });
cmd.Parameters.Add(new SqlParameter("@ROIEnd", SqlDbType.Float) { Value = regionOfInterest.End });
cmd.Parameters.Add(new SqlParameter("@IsEnabled", SqlDbType.Bit) { Value = regionOfInterest.IsEnabled });
cmd.Parameters.Add(new SqlParameter("@IsDefault", SqlDbType.Bit) { Value = regionOfInterest.IsDefault });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, errorMessageParam.Value.ToString());
}
else
{
//Return the new id so that it can be used to enter this ROI period's channels into the ROIPeriodChannels table
testSetupROIId = int.Parse(newIdParam.Value.ToString());
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Gets records from the TestSetupROIs table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupId">The value that matches the Primary key of the TestSetups table</param>
/// <param name="records">The array of records from the TestSetupROIs table</param>
/// <returns></returns>
public ulong TestSetupROIsGet(IUserDbRecord user,
IConnectionDetails connection,
int testSetupId,
out ITestSetupROIRecord[] records)
{
records = new ITestSetupROIRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_TestSetupROIsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TestSetupId", SqlDbType.BigInt) { Value = testSetupId });
var reader = cmd.ExecuteReader();
var list = new List<TestSetupROIsRecord>();
while (reader.Read())
{
list.Add(new TestSetupROIsRecord(reader));
}
records = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, $"sp_TestSetupROIsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
/// <summary>
/// Inserts records into the ROIPeriodChannels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupROIId">The value of the Primary key of the TestSetupROIs table</param>
/// <param name="channelName">The name of a channel to be stored in the ROIPeriodChannels table</param>
/// <param name="channelId">The id of a channel to be stored in the ROIPeriodChannels table</param>
/// <returns></returns>
public ulong ROIPeriodChannelsInsert(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupROIId,
string channelName,
long channelId)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
if (testSetupROIId == 0 || null == channelName)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
SqlCommand cmd;
var storedProcedureVersionToUse = 0;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion,
"sp_ROIPeriodChannelsInsert", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@TestSetupROIId", SqlDbType.Int) { Value = testSetupROIId });
cmd.Parameters.Add(new SqlParameter("@ChannelName", SqlDbType.NVarChar, 4000) { Value = channelName });
if (storedProcedureVersionToUse >= Constants.ROIPERIODCHANNELS_CHANNELID_DB_VERSION)
{
cmd.Parameters.Add(new SqlParameter("@ChannelId", SqlDbType.BigInt) { Value = channelId });
}
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if (int.Parse(errorNumberParam.Value.ToString()) != 0)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, errorMessageParam.Value.ToString());
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.RegionsOfInterest, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
return ErrorCodes.ERROR_SUCCESS;
}
/// <summary>
/// Gets records from the ROIPeriodChannels table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="testSetupROIId">The value of the Primary key of the TestSetupROIs table</param>
/// <param name="roiPeriodChannelRecords">The array of records from the ROIPeriodChannels table</param>
/// <returns></returns>
public ulong ROIPeriodChannelsGet(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
int testSetupROIId,
out IROIPeriodChannelRecord[] roiPeriodChannelRecords)
{
roiPeriodChannelRecords = new IROIPeriodChannelRecord[0];
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
SqlCommand cmd;
var storedProcedureVersionToUse = 0;
var ret = Database.Database.PrepareForDbAccess(user, connection, clientDbVersion,
"sp_ROIPeriodChannelsGet", out storedProcedureVersionToUse, out cmd);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TestSetupROIId", SqlDbType.BigInt) { Value = testSetupROIId });
var reader = cmd.ExecuteReader();
var list = new List<ROIPeriodChannelRecord>();
while (reader.Read())
{
var newROIPeriodChannelRecord = new ROIPeriodChannelRecord(reader, storedProcedureVersionToUse);
var cleanROIPeriodChannelName = RegionOfInterest.RemoveAssignedByIDFromHardwareString(newROIPeriodChannelRecord.ChannelName);
cleanROIPeriodChannelName = RegionOfInterest.RemoveParentDASName(cleanROIPeriodChannelName);
newROIPeriodChannelRecord.ChannelName = cleanROIPeriodChannelName;
list.Add(newROIPeriodChannelRecord);
}
roiPeriodChannelRecords = list.ToArray();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Graphs, $"sp_TestSetupROIsGet failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
}
}

View File

@@ -0,0 +1,191 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Classes;
using DTS.Common.Interface.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
namespace DbAPI.Database
{
/// <summary>
/// no real reason to export this, this class handles the implementation for the <see cref="IDatabase"/> interface
/// <inheritdoc cref="IDatabase"/>
/// </summary>
internal class Database : IDatabase
{
public ulong GetDatabaseVersion(IUserDbRecord user, IConnectionDetails connection, out int version)
{
version = 0;
//allow querying database version without a user
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DBVersionGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = DBNull.Value });
var reader = cmd.ExecuteReader();
var dbVersionsList = new List<int>();
while (reader.Read())
{
var tmp = Utility.GetInt(reader, "Version");
dbVersionsList.Add(tmp);
}
reader.Close();
version = dbVersionsList.Max();
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Information, ex.Message);
version = 0;
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public int GetSQLVersion(IConnectionDetails connection)
{
var sqlVersion = 0;
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd);
if (ret == ErrorCodes.ERROR_SUCCESS)
{
try
{
var serverVersion = cmd.Connection.ServerVersion;
string[] serverVersionDetails = serverVersion.Split(new string[] { "." }, StringSplitOptions.None);
sqlVersion = int.Parse(serverVersionDetails[0]);
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Information, ex.Message);
sqlVersion = 0;
}
finally
{
cmd.Connection.Dispose();
}
}
return sqlVersion;
}
public ulong InsertDatabaseVersion(IUserDbRecord user, IConnectionDetails connection, int version, int step, DateTime date, string remarks, string userField)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_DbVersionInsert");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = version });
cmd.Parameters.Add(new SqlParameter("@Step", SqlDbType.Int) { Value = step });
cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime) { Value = date });
cmd.Parameters.Add(new SqlParameter("@Remarks", SqlDbType.NVarChar, 255) { Value = remarks });
cmd.Parameters.Add(new SqlParameter("@UserField", SqlDbType.NVarChar, 255) { Value = userField });
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
var reader = cmd.ExecuteReader();
if (!DBNull.Value.Equals(errorNumber.Value))
{
var error = Convert.ToInt32(errorNumber.Value);
if (0 != error)
{
return ErrorCodes.ERROR_UNKNOWN;
}
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Information, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
/// <summary>
/// returns the command text to use for a given stored procedure that might be versioned
/// </summary>
/// <param name="connection">connection stored procedure is to be run on</param>
/// <param name="storedProcedure">the stored procedure name</param>
/// <param name="clientDbVersion">the code/requested version of the stored procedure</param>
/// <returns>the stored procedure name that should be called given the current db and client versions</returns>
public static string GetStoredProcedureVersion(IConnectionDetails connection, string storedProcedure, int clientDbVersion)
{
var ret = DbAPI.GetStoredProcedureToUse(connection, storedProcedure, clientDbVersion, out var storedProcedureVersionToUse);
if (ret != ErrorCodes.ERROR_SUCCESS) { return storedProcedure; }
return storedProcedureVersionToUse == 0 ? storedProcedure : $"{storedProcedure}_{storedProcedureVersionToUse}";
}
/// <summary>
/// returns the command text to use for a given stored procedure that might be versioned
/// retrieves/stores it in a cache to reduce calls to db ...
/// </summary>
/// <param name="connection">connection stored procedure is to be run on</param>
/// <param name="storedProcedure">the stored procedure name</param>
/// <param name="clientDbVersion">the code/requested version of the stored procedure</param>
/// <returns>the stored procedure name that should be called given the current db and client versions</returns>
public static string GetStoredProcedureVersionCached(IConnectionDetails connection, string storedProcedure)
{
var ret = DbAPI.GetStoredProcedureToUseCached(connection, storedProcedure, connection.ClientDbVersion, out var storedProcedureVersionToUse);
if (ret != ErrorCodes.ERROR_SUCCESS) { return storedProcedure; }
return storedProcedureVersionToUse == 0 ? storedProcedure : $"{storedProcedure}_{storedProcedureVersionToUse}";
}
/// <summary>
/// Prepares a Sql command based on client version
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="clientDbVersion"></param>
/// <param name="storedProcedure"></param>
/// <param name="storedProcedureVersionToUse"></param>
/// <param name="cmd"></param>
/// <returns></returns>
public static ulong PrepareForDbAccess(IUserDbRecord user,
IConnectionDetails connection,
int clientDbVersion,
string storedProcedure,
out int storedProcedureVersionToUse,
out SqlCommand cmd)
{
storedProcedureVersionToUse = 0;
cmd = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = DbAPI.GetStoredProcedureToUse(connection, storedProcedure, clientDbVersion, out storedProcedureVersionToUse);
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
ret = ConnectionManager.GetSqlCommand(connection, out cmd, storedProcedureVersionToUse == 0 ? storedProcedure : $"{storedProcedure}_{storedProcedureVersionToUse}");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
return ret;
}
}
}

View File

@@ -0,0 +1,34 @@
namespace DbAPI.Errors
{
public abstract class ErrorCodes
{
public const ulong ERROR_SUCCESS = 0x0;
public const ulong ERROR_INVALID_FUNCTION = 0x1;
public const ulong ERROR_FILE_NOT_FOUND = 0x2;
public const ulong ERROR_PATH_NOT_FOUND = 0x3;
public const ulong ERROR_ACCESS_DENIED = 0x5;
public const ulong ERROR_NOT_SUPPORTED = 0x32;
public const ulong INVALID_SESSIONID = 0x200;
public const ulong ERROR_UNKNOWN = 0x201;
public const ulong ERROR_NOUSER = 0x202;
public const ulong ERROR_LOGINFAILED = 0x203;
public const ulong ERROR_MISSING_PARAMETER = 0x204;
public static string ResultToString(ulong hr)
{
switch (hr)
{
case ERROR_SUCCESS: return @"SUCCESS";
case ERROR_INVALID_FUNCTION: return @"INVALID_FUNCTION";
case ERROR_FILE_NOT_FOUND: return @"FILE_NOT_FOUND";
case ERROR_PATH_NOT_FOUND: return @"PATH_NOT_FOUND";
case ERROR_ACCESS_DENIED: return @"ACCESS_DENIED";
case ERROR_NOT_SUPPORTED: return @"NOT_SUPPORTED";
case INVALID_SESSIONID: return @"INVALID_SESSIONID";
case ERROR_UNKNOWN: return @"UNKNOWN_ERROR";
case ERROR_NOUSER: return @"NO_USER";
case ERROR_LOGINFAILED: return "LOGIN_FAILED";
default: return hr.ToString("X");
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,176 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DTS.Common.Interface.Database;
using System;
using System.Data;
using System.Data.SqlClient;
using DTS.Common.Interface.Groups.GroupList;
using System.Collections.Generic;
using DTS.Common.Interface.Groups;
using DTS.Common.Classes.Groups;
using DbAPI.Logging;
using System.Diagnostics;
namespace DbAPI.GroupHardware
{
/// <summary>
/// Handles GroupHardware functions
/// </summary>
internal class GroupHardware : IGroupHardware
{
public ulong GroupHardwareInsert(IUserDbRecord user,
IConnectionDetails connection,
GroupHardwareDbRecord groupHardwareDbRecord,
out int newId,
out string errorMessageString)
{
newId = -1;
errorMessageString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupHardwareInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = groupHardwareDbRecord.GroupId });
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = groupHardwareDbRecord.DASId });
var newGroupHardwareIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newGroupHardwareIdParam);
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value)
{
if (Convert.ToInt32(errorNumber.Value) != 0)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupHardwareInsert failed: {errorNumber.Value} {errorMessage.Value}");
errorMessageString = errorMessage.Value.ToString();
return Convert.ToUInt32(errorNumber.Value);
}
}
newId = Convert.ToInt32(newGroupHardwareIdParam.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupHardwareInsert failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
public ulong GroupHardwareGet(IUserDbRecord user,
IConnectionDetails connection,
int? groupId,
string serialNumber,
bool? embedded,
out GroupHardwareDbRecord[] groupHardwareRecords)
{
groupHardwareRecords = null;
var list = new List<GroupHardwareDbRecord>();
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupHardwareGet");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = groupId });
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar) { Value = serialNumber });
cmd.Parameters.Add(new SqlParameter("@Embedded", SqlDbType.Bit) { Value = embedded });
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new GroupHardwareDbRecord(reader));
}
groupHardwareRecords = list.ToArray();
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupsGet failed - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong GroupHardwareDelete(IUserDbRecord user,
IConnectionDetails connection,
int? groupId,
int? dasId,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupHardwareDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int) { Value = groupId });
cmd.Parameters.Add(new SqlParameter("@DASId", SqlDbType.Int) { Value = dasId });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value)
{
if (Convert.ToInt32(errorNumber.Value) != 0)
{
errorNumberULong = Convert.ToUInt64(errorNumber.Value);
throw new Exception((string)errorMessage.Value);
}
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
}
}

View File

@@ -0,0 +1,81 @@
using DbAPI.Connections;
using DTS.Common.Interface.Database;
using System;
using DTS.Common.Classes.LabratoryDetails;
using DTS.Common.Interface.TestMetaData;
namespace DbAPI.LabratoryDetails
{
/// <summary>
/// LabratoryDetails related functions (GetLabratoryDetails, )
/// </summary>
public interface ILabratoryDetails
{
/// <summary>
/// Inserts a new record in the LabratoryDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="labratoryDetailsDbRecord"></param>
/// <param name="newId">The Id of the new record in the LabratoryDetails table</param>
/// <param name="errorString">Error string returned, possibly from sp_LabratoryDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong LabratoryDetailsInsert(IUserDbRecord user,
IConnectionDetails connection,
LabratoryDetailsDbRecord labratoryDetailsDbRecord,
out int newId,
out string errorString);
/// <summary>
/// Updates an existing record in the LabratoryDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name = "labratoryDetailsDbRecord"></param>
/// <param name="errorString">Error string returned, possibly from sp_LabratoryDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong LabratoryDetailsUpdate(IUserDbRecord user,
IConnectionDetails connection,
LabratoryDetailsDbRecord labratoryDetailsDbRecord,
out string errorString);
/// <summary>
/// Updates an existing record or Inserts a new record in the LabratoryDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name = "labratoryDetailsDbRecord"></param>
/// <param name="errorString">Error string returned, possibly from sp_LabratoryDetailsUpdate</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong LabratoryDetailsUpdateInsert(IUserDbRecord user,
IConnectionDetails connection,
LabratoryDetailsDbRecord labratoryDetailsDbRecord,
out string errorString);
/// <summary>
/// retrieves all laboratory details matching search criteria
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="name">Name in the LabratoryDetails table</param>
/// <param name="labratoryDetailsDbRecords">null, or records found</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong LabratoryDetailsGet(IUserDbRecord user,
IConnectionDetails connection,
string name,
out ILabratoryDetailsDbRecord[] labratoryDetailsDbRecords);
/// <summary>
/// Deletes an entry in the LabratoryDetails table
/// </summary>
/// <param name="user"></param>
/// <param name="connection"></param>
/// <param name="name">Name in the LabratoryDetails table</param>
/// <param name="errorString">Error string returned, possibly from sp_LabratoryDetailsDelete</param>
/// <returns>0 (ERROR_SUCCESS) on success, all other values are error codes</returns>
ulong LabratoryDetailsDelete(IUserDbRecord user,
IConnectionDetails connection,
string name,
out string errorString);
}
}

View File

@@ -0,0 +1,235 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DTS.Common.Interface.Database;
using System;
using System.Data;
using System.Data.SqlClient;
using DTS.Common.Interface.Groups.GroupList;
using System.Collections.Generic;
using DTS.Common.Interface.Groups;
using DTS.Common.Classes.Groups;
using DbAPI.Logging;
using System.Diagnostics;
namespace DbAPI.Groups
{
/// <summary>
/// Handles channel functions
/// </summary>
internal class Groups : IGroups
{
public ulong GroupsInsert(IUserDbRecord user,
IConnectionDetails connection,
ref IGroupDbRecord group)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 255) { Value = group.SerialNumber });
cmd.Parameters.Add(new SqlParameter("@DisplayName", SqlDbType.NVarChar, 255) { Value = group.DisplayName });
cmd.Parameters.Add(new SqlParameter("@Description", SqlDbType.NVarChar, 255) { Value = group.Description });
cmd.Parameters.Add(new SqlParameter("@Embedded", SqlDbType.Bit) { Value = group.Embedded });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = group.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 255) { Value = group.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@StaticGroupId", SqlDbType.Int) { Value = group.StaticGroupId });
cmd.Parameters.Add(new SqlParameter("@ExtraProperties", SqlDbType.NVarChar, -1) { Value = group.ExtraProperties ?? "" });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newId);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value)
{
if (Convert.ToInt32(errorNumber.Value) != 0)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupsInsert failed: {errorNumber.Value} {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
}
group.Id = Convert.ToInt32(newId.Value);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupsInsert failed: {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
cmd.Dispose();
}
}
public ulong GroupsUpdate(IUserDbRecord user,
IConnectionDetails connection,
IGroupDbRecord group)
{
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = group.Id });
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar, 255) { Value = group.SerialNumber });
cmd.Parameters.Add(new SqlParameter("@DisplayName", SqlDbType.NVarChar, 255) { Value = group.DisplayName });
cmd.Parameters.Add(new SqlParameter("@Description", SqlDbType.NVarChar, 255) { Value = group.Description });
cmd.Parameters.Add(new SqlParameter("@Embedded", SqlDbType.Bit) { Value = group.Embedded });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = group.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 255) { Value = group.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@StaticGroupId", SqlDbType.Int) { Value = group.StaticGroupId });
cmd.Parameters.Add(new SqlParameter("@ExtraProperties", SqlDbType.NVarChar, -1) { Value = group.ExtraProperties });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (!DBNull.Value.Equals(errorNumber.Value) && 0 != Convert.ToInt32(errorNumber.Value))
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupsUpdate failed - {errorNumber.Value} {errorMessage.Value}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupsUpdate failed - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong GroupsGet(IUserDbRecord user,
IConnectionDetails connection,
int? id,
string serialNumber,
string displayName,
bool? embedded,
int? staticGroupId,
out IGroupDbRecord[] groups)
{
groups = null;
var list = new List<IGroupDbRecord>();
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupsGet");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = id });
cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar) { Value = serialNumber });
cmd.Parameters.Add(new SqlParameter("@DisplayName", SqlDbType.NVarChar) { Value = displayName });
cmd.Parameters.Add(new SqlParameter("@Embedded", SqlDbType.Bit) { Value = embedded });
cmd.Parameters.Add(new SqlParameter("@StaticGroupId", SqlDbType.Int) { Value = staticGroupId });
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new GroupDbRecord(reader));
}
groups = list.ToArray();
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.TestSetups, $"GroupsGet failed - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
}
}
public ulong GroupsDelete(IUserDbRecord user,
IConnectionDetails connection,
long id,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_GroupsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = id });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessage);
cmd.ExecuteNonQuery();
if (null != errorNumber.Value && !DBNull.Value.Equals(errorNumber.Value))
{
if (0 != Convert.ToInt32(errorNumber.Value))
{
errorNumberULong = Convert.ToUInt64(errorNumber.Value);
errorString = (string)errorMessage.Value;
}
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
}
}

View File

@@ -0,0 +1,244 @@
using DbAPI.Connections;
using DbAPI.Errors;
using DbAPI.Logging;
using DbAPI.CustomerDetails;
using DTS.Common.Classes.Channels;
using DTS.Common.Interface.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using DTS.Common.Interface.TestMetaData;
using DTS.Common.Classes.CustomerDetails;
namespace DbAPI.CustomerDetails
{
/// <summary>
/// Handles Customer Details functions
/// </summary>
internal class CustomerDetails : ICustomerDetails
{
public ulong CustomerDetailsInsert(IUserDbRecord user,
IConnectionDetails connection,
CustomerDetailsDbRecord customerDetailsDbRecord,
out int newId,
out string errorString)
{
errorString = string.Empty;
newId = -1;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CustomerDetailsInsert");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerName });
cmd.Parameters.Add(new SqlParameter("@CustomerTestRefNumber", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerTestRefNumber });
cmd.Parameters.Add(new SqlParameter("@ProjectRefNumber", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.ProjectRefNumber });
cmd.Parameters.Add(new SqlParameter("@CustomerOrderNumber", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerOrderNumber });
cmd.Parameters.Add(new SqlParameter("@CustomerCostUnit", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerCostUnit });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = customerDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = customerDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = customerDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var newIdParam = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(newIdParam);
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
else
{
newId = (int)newIdParam.Value;
}
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong CustomerDetailsUpdate(IUserDbRecord user,
IConnectionDetails connection,
CustomerDetailsDbRecord customerDetailsDbRecord,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CustomerDetailsUpdate");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.Name });
cmd.Parameters.Add(new SqlParameter("@CustomerName", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerName });
cmd.Parameters.Add(new SqlParameter("@CustomerTestRefNumber", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerTestRefNumber });
cmd.Parameters.Add(new SqlParameter("@ProjectRefNumber", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.ProjectRefNumber });
cmd.Parameters.Add(new SqlParameter("@CustomerOrderNumber", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerOrderNumber });
cmd.Parameters.Add(new SqlParameter("@CustomerCostUnit", SqlDbType.NVarChar, 255) { Value = customerDetailsDbRecord.CustomerCostUnit });
cmd.Parameters.Add(new SqlParameter("@LocalOnly", SqlDbType.Bit) { Value = customerDetailsDbRecord.LocalOnly });
cmd.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = customerDetailsDbRecord.LastModified });
cmd.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 50) { Value = customerDetailsDbRecord.LastModifiedBy });
cmd.Parameters.Add(new SqlParameter("@Version", SqlDbType.Int) { Value = 1 });
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
public ulong CustomerDetailsGet(IUserDbRecord user,
IConnectionDetails connection,
string name,
out ICustomerDetailsDbRecord[] customerDetailsDbRecords)
{
customerDetailsDbRecords = null;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CustomerDetailsGet");
if (ret != ErrorCodes.ERROR_SUCCESS) { return ret; }
var list = new List<ICustomerDetailsDbRecord>();
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar) { Value = name });
var reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
var cd = new CustomerDetailsDbRecord(reader);
if (!cd.IsInvalidBlank())
{
list.Add(cd);
}
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
}
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.DataRecorders, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
finally
{
cmd.Connection.Dispose();
customerDetailsDbRecords = list.ToArray();
}
}
public ulong CustomerDetailsDelete(IUserDbRecord user,
IConnectionDetails connection,
string name,
out string errorString)
{
errorString = string.Empty;
if (!DbAPI.Connections.IsUserLoggedIn(user, connection))
{
return ErrorCodes.ERROR_ACCESS_DENIED;
}
var ret = ConnectionManager.GetSqlCommand(connection, out var cmd, "sp_CustomerDetailsDelete");
if (ret != ErrorCodes.ERROR_SUCCESS)
{
return ret;
}
var errorNumberULong = ErrorCodes.ERROR_SUCCESS;
try
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
#region params
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 255) { Value = string.IsNullOrEmpty(name) ? null : name });
var errorNumberParam = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorNumberParam);
var errorMessageParam = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(errorMessageParam);
#endregion params
cmd.ExecuteNonQuery();
if ((int)errorNumberParam.Value != 0)
{
errorNumberULong = (ulong)errorNumberParam.Value;
errorString = (string)errorMessageParam.Value;
}
}
finally
{
cmd.Connection.Dispose();
}
}
catch (Exception ex)
{
//Concatenate any error string returned from the stored procedure call
errorString = $"{ex.Message}; {errorString}";
return errorNumberULong;
}
finally
{
cmd.Connection.Dispose();
}
return errorNumberULong;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,101 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbAPI", "DbAPI.csproj", "{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTS.Common", "..\..\Common\DTS.Common\DTS.Common.csproj", "{F7A0804F-61A4-40AE-83D0-F1137622B592}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTS.Common.Utilities", "..\..\Common\DTS.Common.Utilities\DTS.Common.Utilities.csproj", "{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
x64|Any CPU = x64|Any CPU
x64|x64 = x64|x64
x64|x86 = x64|x86
x86|Any CPU = x86|Any CPU
x86|x64 = x86|x64
x86|x86 = x86|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Debug|x64.ActiveCfg = Debug|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Debug|x64.Build.0 = Debug|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Debug|x86.ActiveCfg = Debug|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Debug|x86.Build.0 = Debug|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Release|Any CPU.Build.0 = Release|Any CPU
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Release|x64.ActiveCfg = Release|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Release|x64.Build.0 = Release|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Release|x86.ActiveCfg = Release|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.Release|x86.Build.0 = Release|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x64|Any CPU.ActiveCfg = Release|Any CPU
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x64|x64.ActiveCfg = Debug|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x64|x64.Build.0 = Debug|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x64|x86.ActiveCfg = Debug|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x64|x86.Build.0 = Debug|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x86|Any CPU.ActiveCfg = Release|Any CPU
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x86|x64.ActiveCfg = Debug|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x86|x64.Build.0 = Debug|x64
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x86|x86.ActiveCfg = Debug|x86
{B2E3788A-FFDA-42AC-B785-0165BD44AFDA}.x86|x86.Build.0 = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Debug|Any CPU.ActiveCfg = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Debug|x64.ActiveCfg = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Debug|x64.Build.0 = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Debug|x86.ActiveCfg = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Debug|x86.Build.0 = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Release|Any CPU.ActiveCfg = Release|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Release|x64.ActiveCfg = Release|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Release|x64.Build.0 = Release|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Release|x86.ActiveCfg = Release|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.Release|x86.Build.0 = Release|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x64|Any CPU.ActiveCfg = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x64|Any CPU.Build.0 = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x64|x64.ActiveCfg = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x64|x64.Build.0 = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x64|x86.ActiveCfg = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x64|x86.Build.0 = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x86|Any CPU.ActiveCfg = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x86|Any CPU.Build.0 = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x86|x64.ActiveCfg = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x86|x64.Build.0 = Debug|x64
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x86|x86.ActiveCfg = Debug|x86
{F7A0804F-61A4-40AE-83D0-F1137622B592}.x86|x86.Build.0 = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Debug|Any CPU.ActiveCfg = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Debug|x64.ActiveCfg = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Debug|x64.Build.0 = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Debug|x86.ActiveCfg = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Debug|x86.Build.0 = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Release|Any CPU.ActiveCfg = Release|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Release|x64.ActiveCfg = Release|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Release|x64.Build.0 = Release|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Release|x86.ActiveCfg = Release|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.Release|x86.Build.0 = Release|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x64|Any CPU.ActiveCfg = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x64|Any CPU.Build.0 = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x64|x64.ActiveCfg = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x64|x64.Build.0 = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x64|x86.ActiveCfg = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x64|x86.Build.0 = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x86|Any CPU.ActiveCfg = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x86|Any CPU.Build.0 = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x86|x64.ActiveCfg = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x86|x64.Build.0 = Debug|x64
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x86|x86.ActiveCfg = Debug|x86
{D6DA1B74-C711-43C2-91B1-1908A8D04DBF}.x86|x86.Build.0 = Debug|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5CFFD2F2-ACF3-413B-BE7F-A69B318F950E}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,475 @@
using DbAPI.Errors;
using DbAPI.Logging;
using DTS.Common.Interface.Database;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace DbAPI.Connections
{
/// <summary>
/// internal class, no real reason to export this class, it handles all the details for the interface we exported
/// Implements <see cref="IConnections"/>
/// <inheritdoc cref="IConnections"/>
/// </summary>
internal class ConnectionManager : IConnections
{
private static readonly object LOGIN_LOCK = new object();
private List<Tuple<IUserDbRecord, IConnectionDetails>> _loggedInUsers = new List<Tuple<IUserDbRecord, IConnectionDetails>>();
private static readonly object CONNECT_LOCK = new object();
private List<IConnectionDetails> _connections = new List<IConnectionDetails>();
private void AddLoggedInUser(IConnectionDetails con, IUserDbRecord user)
{
lock (LOGIN_LOCK)
{
_loggedInUsers.Add(new Tuple<IUserDbRecord, IConnectionDetails>(user, con));
}
}
/// <summary>
/// removes all logged in users and all database connections
/// </summary>
public void ClearConnections()
{
lock (LOGIN_LOCK)
{
_loggedInUsers.Clear();
}
lock (CONNECT_LOCK)
{
_connections.Clear();
}
}
public ulong ConnectToDb(IConnectionDetails details)
{
try
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"ConnectToDb {details}");
var ret = Connect(details);
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"Connection result {ErrorCodes.ResultToString(ret)}");
return ret;
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Connections, ex.Message);
return ErrorCodes.ERROR_UNKNOWN;
}
}
public IConnectionDetails[] GetActiveConnections()
{
lock (CONNECT_LOCK)
{
return _connections.ToArray();
}
}
public ulong LoginUserHash(IConnectionDetails connection, string user, string hash, out IUserDbRecord userObject)
{
userObject = null;
try
{
var res = User.User.GetUser(connection, out var foundUser, user);
if (res != ErrorCodes.ERROR_SUCCESS)
{
return ErrorCodes.ERROR_LOGINFAILED;
}
if (hash != foundUser.Password)
{
return ErrorCodes.ERROR_LOGINFAILED;
}
userObject = foundUser;
AddLoggedInUser(connection, userObject);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Login, $"Login {connection} Error: {ex.Message}");
}
return ErrorCodes.ERROR_UNKNOWN;
}
public ulong LoginUser(IConnectionDetails connection, string user, string password, out IUserDbRecord userObject)
{
userObject = null;
try
{
if (null == connection)
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
if (string.IsNullOrEmpty(user))
{
return ErrorCodes.ERROR_MISSING_PARAMETER;
}
var res = User.User.GetUser(connection, out var foundUser, user);
if (res != ErrorCodes.ERROR_SUCCESS)
{
return ErrorCodes.ERROR_LOGINFAILED;
}
var b = Encoding.UTF8.GetBytes(string.Format("{0}_{1}", password, user));
var sha2 = SHA256.Create();
var hashed = sha2.ComputeHash(b);
var hashedEncoded = Convert.ToBase64String(hashed);
if (hashedEncoded != foundUser.Password)
{
return ErrorCodes.ERROR_LOGINFAILED;
}
userObject = foundUser;
AddLoggedInUser(connection, userObject);
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Login, $"Login {connection} Error: {ex.Message}");
}
return ErrorCodes.ERROR_UNKNOWN;
}
public Tuple<IUserDbRecord, IConnectionDetails>[] GetLoggedInUsers()
{
lock (LOGIN_LOCK)
{
return _loggedInUsers.ToArray();
}
}
private ulong Connect(IConnectionDetails details)
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"Connecting: {details}");
var copy = details.Clone();
ulong result;
if (copy.UsingCentralizedDb)
{
result = ConnectRemote(details);
}
else
{
result = ConnectLocal(copy);
}
if (result == Errors.ErrorCodes.ERROR_SUCCESS)
{
AddConnection(copy);
}
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"Connect {details} result: {ErrorCodes.ResultToString(result)}");
return result;
}
private void AddConnection(IConnectionDetails details)
{
lock (CONNECT_LOCK)
{
_connections.Add(details);
}
}
private ulong ConnectRemote(IConnectionDetails details)
{
return ErrorCodes.ERROR_SUCCESS;
}
private ulong ConnectLocal(IConnectionDetails details)
{
try
{
try
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, "Stopping instance");
StopInstance(details, DTS.Common.Utilities.Logging.APILogger.Log);
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"StopInstance {details} - {ex.Message}");
//29362 Don't re-throw exception if there was no instance to stop - just keep going
if (!(ex is DTS.Common.Utils.Database.SqlServerLocalDbException) ||
(ex as DTS.Common.Utils.Database.SqlServerLocalDbException).Error != DTS.Common.Utils.Database.SqlServerLocalDbException.Errors.LocalDbDoesntExist)
{
throw ex;
}
}
try
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, "Deleting instance");
DeleteInstance(details, DTS.Common.Utilities.Logging.APILogger.Log);
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"DeleteInstance {details} - {ex.Message}");
//29362 Don't re-throw exception if there was no instance to delete - just keep going
if (!(ex is DTS.Common.Utils.Database.SqlServerLocalDbException) ||
(ex as DTS.Common.Utils.Database.SqlServerLocalDbException).Error != DTS.Common.Utils.Database.SqlServerLocalDbException.Errors.LocalDbDoesntExist)
{
throw ex;
}
}
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, "Creating instance");
CreateInstance(details, DTS.Common.Utilities.Logging.APILogger.Log);
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, "Starting instance");
StartInstance(details, DTS.Common.Utilities.Logging.APILogger.Log);
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, "Attaching databases");
AttachDatabases(details, DTS.Common.Utilities.Logging.APILogger.Log);
}
catch (Exception ex)
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"ConnectLocal {details} - {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
return ErrorCodes.ERROR_SUCCESS;
}
private static readonly object PROCESS_LOCK = new object();
private static readonly StringBuilder sb = new StringBuilder();
private static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (outLine.Data != null)
{
if (string.IsNullOrWhiteSpace(outLine.Data))
{
sb.Append("\r\n");
}
sb.Append(outLine.Data);
}
}
private static readonly StringBuilder sbErrors = new StringBuilder();
/// <summary>
/// starts a process with a given command and logs
/// </summary>
/// <param name="sqlLocalDbExeFileName"></param>
/// <param name="command"></param>
/// <param name="log"></param>
/// <returns></returns>
private static string SqlCommandProcessor(string sqlLocalDbExeFileName, string command, DTS.Common.Utils.Database.LogDelegate log)
{
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"{command}");
var resultString = string.Empty;
lock (PROCESS_LOCK)
{
sb.Clear();
sbErrors.Clear();
var process = new Process
{
StartInfo =
{
FileName = sqlLocalDbExeFileName,
Arguments = command,
LoadUserProfile = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
//* Set ONLY ONE handler here.
process.OutputDataReceived += OutputHandler;
process.ErrorDataReceived += Process_ErrorDataReceived;
//* Start process
process.Start();
//* Read one element asynchronously
process.BeginErrorReadLine();
//* Read the other one synchronously
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
log?.Invoke($"Result of {command} command is: {output}");
process.WaitForExit();
if (sb.Length > 0)
{
resultString = sb.ToString();
}
if (sbErrors.Length > 0)
{
resultString = sbErrors.ToString();
}
}
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"{resultString}");
return resultString;
}
private static void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
sbErrors.AppendLine(e.Data);
}
}
private string ProcessSqlLocalDbCommand(string command, string localDbPath, DTS.Common.Utils.Database.LogDelegate log)
{
if (localDbPath == string.Empty)
{
//SQL Server LocalDb is not installed so display error and go away
throw new FileNotFoundException();
}
var sqlLocalDbExeFileName = localDbPath + "SqlLocalDB.exe";
return SqlCommandProcessor(sqlLocalDbExeFileName, command, log);
}
private void StopInstance(IConnectionDetails details, DTS.Common.Utils.Database.LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"stop {details.InstanceName}", details.SqlDbPath, log);
if (resultString.Length != 0)
{
////29362 If the error is because the instance doesn't exist, throw that type of Exception
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"Stop result: {resultString}");
//if (resultString.Contains(DTS.Common.Strings.Strings.SQLLocalDBInstanceDoesNotExist))
//{
throw new DTS.Common.Utils.Database.SqlServerLocalDbException(DTS.Common.Utils.Database.SqlServerLocalDbException.Errors.LocalDbDoesntExist, resultString);
//}
//else
//{
// throw new Exception(resultString);
//}
}
}
private void DeleteInstance(IConnectionDetails details, DTS.Common.Utils.Database.LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"delete {details.InstanceName}", details.SqlDbPath, log);
if (resultString.Length != 0)
{
////29362 If the error is because the instance doesn't exist, throw that type of Exception
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"Delete result: {resultString}");
//if (resultString.Contains(DTS.Common.Strings.Strings.SQLLocalDBInstanceDoesNotExist))
//{
throw new DTS.Common.Utils.Database.SqlServerLocalDbException(DTS.Common.Utils.Database.SqlServerLocalDbException.Errors.LocalDbDoesntExist, resultString);
//}
//else
//{
// throw new Exception(resultString);
//}
}
}
private void CreateInstance(IConnectionDetails details, DTS.Common.Utils.Database.LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"create {details.InstanceName}", details.SqlDbPath, log);
if (resultString.Length != 0)
{
throw new Exception(resultString);
}
}
private void StartInstance(IConnectionDetails details, DTS.Common.Utils.Database.LogDelegate log)
{
var resultString = ProcessSqlLocalDbCommand($"start {details.InstanceName}", details.SqlDbPath, log);
if (resultString.Length != 0)
{
throw new Exception(resultString);
}
}
private static string BatchCommandProcessor(string batchFileName,
string dbName,
string sqlDbFileName,
string sqlLogFileName,
string fullSqlcmdPath,
DTS.Common.Utils.Database.LogDelegate log)
{
var resultString = string.Empty;
lock (PROCESS_LOCK)
{
sb.Clear();
sbErrors.Clear();
var fi = new FileInfo(batchFileName);
var fi2 = new FileInfo(sqlLogFileName);
var fi3 = new FileInfo(sqlDbFileName);
var process = new Process
{
StartInfo =
{
FileName = fi.FullName,
Arguments = $"{dbName} \"{fi3.FullName}\" \"{fi2.FullName}\" {fullSqlcmdPath}",
LoadUserProfile = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
//* Set ONLY ONE handler here.
process.OutputDataReceived += OutputHandler;
process.ErrorDataReceived += Process_ErrorDataReceived;
//* Start process
process.Start();
//* Read one element asynchronously
process.BeginErrorReadLine();
//* Read the other one synchronously
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
log?.Invoke($"Result of attach {dbName} using {sqlDbFileName} and {sqlLogFileName} is:");
log?.Invoke(output);
process.WaitForExit();
if (sb.Length > 0)
{
resultString = sb.ToString();
}
if (sbErrors.Length > 0)
{
resultString += sbErrors.ToString();
}
}
return resultString;
}
/// <summary>
/// attaches to a given database
/// throws DbNotAttached exception
/// </summary>
private static void AttachDatabase(IConnectionDetails details, string dbName, DTS.Common.Utils.Database.LogDelegate log)
{
const string SqlCmdExe = "sqlcmd.exe";
var dbFileName = Path.Combine(details.DbFolderPath, dbName) + ".mdf";
var logFileName = Path.Combine(details.DbFolderPath, dbName) + "_log.ldf";
var batchFileName = details.AttachDbsBatPath;
log?.Invoke($"ODBCToolsPath is {details.ODBCToolsPath}");
var fullSqlcmdPath = Path.Combine(details.ODBCToolsPath, SqlCmdExe); //e.g. $"\"C:\\Program Files\\Microsoft SQL Server\\Client SDK\\ODBC\\110\\Tools\\Binn\\sqlcmd.exe\""
if (!File.Exists(fullSqlcmdPath))
{
log?.Invoke($"sqlcmd.exe DOES NOT EXIST at {fullSqlcmdPath}");
}
var resultString = BatchCommandProcessor(batchFileName, dbName, dbFileName, logFileName, $"\"{fullSqlcmdPath}\"", log);
if (resultString.Length != 0)
{
throw new Exception(resultString);
}
}
private void AttachDatabases(IConnectionDetails details, DTS.Common.Utils.Database.LogDelegate log)
{
//Attach the DataPRO database
AttachDatabase(details, details.DbName, log);
//Attach the ISO database
AttachDatabase(details, "ISO", log);
}
internal static ulong GetSqlCommand(IConnectionDetails con, out SqlCommand cmd, string commandText = "")
{
try
{
cmd = new SqlCommand();
cmd.Connection = new SqlConnection(con.GetConnectionString());
cmd.Connection.Open();
cmd.CommandText = commandText;
LogManager.Log(TraceEventType.Information, LogManager.LogEvents.Connections, $"CommandText is {commandText}");
return ErrorCodes.ERROR_SUCCESS;
}
catch (Exception ex)
{
cmd = null;
LogManager.Log(TraceEventType.Error, LogManager.LogEvents.Connections, $"GetSqlCommand, {ex.Message}");
return ErrorCodes.ERROR_UNKNOWN;
}
}
public bool IsUserLoggedIn(IUserDbRecord user, IConnectionDetails details)
{
lock (LOGIN_LOCK)
{
return _loggedInUsers.Exists(item => item.Item1 == user && item.Item2 == details);
}
}
}
}