getValue() публичный Метод

This method allows the program to access the configuration file using a single interface. Checks the configuration file for the key given and returns either the value, if found, or an exception should the key not exist.
public getValue ( string key ) : string
key string Key to check the value of.
Результат string
Пример #1
0
 /// <summary>
 /// Constructs a <code>Master</code> object by initializing the
 /// <code>ConfigReader</code> and the <code>UIController</code>.
 /// </summary>
 public Master()
 {
     _configReader = new ConfigReader();
     bool firstUse = _configReader.getValue("First Use").Equals("True");
     if (firstUse) {
         _configReader.setValue("First Use", "False");
     }
     new UIController(this, firstUse);
 }
Пример #2
0
        /// <summary>
        /// Adds a weapon name to the database.
        /// </summary>
        /// <param name="weaponName">The weapon name to add to the database.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The INSERT INTO Weapon command failed.</exception>
        public static void AddWeaponName(String weaponName, ConfigReader configReader)
        {
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "INSERT INTO Weapon (WeaponName) VALUES (?)";
                    command.Prepare();
                    setStringParameter(command, "WeaponName", weaponName);

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform INSERT INTO Weapon.", "SQL", command.CommandText);
                        throw e;
                    }
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Adds a caliber unit to the database.
        /// </summary>
        /// <param name="caliberUnit">The <c>CaliberUnit</c> to add to the database.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The INSERT INTO Caliber command failed.</exception>
        public static void AddCaliberUnit(Datatype.CaliberUnit caliberUnit, ConfigReader configReader)
        {
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location")))
            {
                openConnection(conn);

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "INSERT INTO Caliber (UnitName, UnitsPerInch) VALUES (?, ?)";
                    command.Prepare();
                    setStringParameter(command, "UnitName", caliberUnit.unitName);
                    command.Parameters.Add("UnitsPerInch", OleDbType.Double).Value = caliberUnit.unitsPerInch;

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform INSERT INTO Caliber.", "SQL", command.CommandText);
                        throw e;
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Returns all of the caliber options already in the database with their IDs.
        /// </summary>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <returns>A Hashtable where the keys are the caliberIDs as ints and the values are
        /// caliber names as Strings.</returns>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        public static List<Datatype.CaliberUnit> GetCaliberUnits(ConfigReader configReader)
        {
            List<Datatype.CaliberUnit> calibers = new List<Datatype.CaliberUnit>();
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location")))
            {
                openConnection(conn);

                using (OleDbCommand command = new OleDbCommand("SELECT * FROM Caliber", conn)) {
                    using (OleDbDataReader reader = command.ExecuteReader()) {
                        while (reader.Read()) {
                            // We could trust that the columns are index 0, 1, and 2,
                            // but let's use the specific column name for safety.
                            int caliberUnitID = reader.GetInt32(reader.GetOrdinal("CaliberID"));
                            String unitName = reader.GetString(reader.GetOrdinal("UnitName"));
                            double unitsPerInch = reader.GetDouble(reader.GetOrdinal("UnitsPerInch"));
                            calibers.Add(new Datatype.CaliberUnit(caliberUnitID, unitName, unitsPerInch));
                        }
                    }
                }
            }

            return calibers;
        }
Пример #5
0
 /// <summary>
 /// Returns true if the given <c>weaponName</c> is in the database.
 /// </summary>
 /// <param name="caliberID">The <c>weaponName</c> to find.</param>
 /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
 /// <returns>True if the given <c>weaponName</c> is in the database.</returns>
 private static Boolean WeaponExists(String weaponName, ConfigReader configReader)
 {
     using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
         openConnection(conn);
         using (OleDbCommand command = new OleDbCommand()) {
             command.Connection = conn;
             command.CommandText = "SELECT WeaponName FROM Weapon WHERE WeaponName = ?";
             command.Prepare();
             setStringParameter(command, "WeaponName", weaponName);
             using (OleDbDataReader reader = command.ExecuteReader()) {
                 return reader.HasRows;
             }
         }
     }
 }
Пример #6
0
        /// <summary>
        /// Updates an existing <c>ImageData</c> object in the <c>Target</c> table.
        /// </summary>
        /// <param name="imageData">The <c>ImageData</c> to update.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The UPDATE Target command failed.</exception>
        /// <exception cref="ArgumentException">The caliber or weapon name was not found in the database.</exception>
        /// <returns>The <c>targetID</c> of the updated record.</returns>
        private static int UpdateData(Datatype.ImageData imageData, ConfigReader configReader)
        {
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                if (!CaliberIDExists(imageData.caliber.caliberUnitID, configReader)) {
                    Log.LogError("Caliber to insert not found in database.", "unitID",
                        imageData.caliber.caliberUnitID.ToString(), "unitName", imageData.caliber.unitName,
                        "unitsPerInch", imageData.caliber.unitsPerInch.ToString());
                    throw new ArgumentException("Caliber to insert does not exist.", "caliber");
                }
                if (!WeaponExists(imageData.weaponName, configReader)) {
                    Log.LogError("Weapon name to insert not found in database.", "weaponName", imageData.weaponName);
                    throw new ArgumentException("Weapon name to insert not found in database.", "weaponName");
                }

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "UPDATE Target SET OrigFilename = ?, ReportFilename = ?, DateTimeFired = ?, DateTimeProcessed = ?, ShooterLName = ?, ShooterFName = ?, RangeLocation = ?, DistanceUnits = ?, Distance = ?, Temperature = ?, WeaponName = ?, SerialNumber = ?, WeaponNotes = ?, CaliberID = ?, CaliberValue = ?, LotNumber = ?, ProjectileMassGrains = ?, AmmunitionNotes = ?, ShotsFired = ?, ShotLocations = ?, Scale = ?, ROI = ? WHERE TargetID = ?";
                    command.Prepare();
                    setStringParameter(command, "OrigFilename", imageData.origFilename);
                    setStringParameter(command, "ReportFilename", imageData.reportFilename);
                    command.Parameters.Add("DateTimeFired", OleDbType.Date).Value = imageData.dateTimeFired;
                    command.Parameters.Add("DateTimeProcessed", OleDbType.Date).Value = DateTime.Now;
                    setStringParameter(command, "ShooterLName", imageData.shooterLName);
                    setStringParameter(command, "ShooterFName", imageData.shooterFName);
                    setStringParameter(command, "RangeLocation", imageData.rangeLocation);
                    command.Parameters.Add("DistanceUnits", OleDbType.UnsignedTinyInt).Value = imageData.distanceUnits;
                    command.Parameters.Add("Distance", OleDbType.Integer).Value = imageData.distance;
                    command.Parameters.Add("Temperature", OleDbType.UnsignedTinyInt).Value = imageData.temperature;
                    setStringParameter(command, "WeaponName", imageData.weaponName);
                    setStringParameter(command, "SerialNumber", imageData.serialNumber);
                    command.Parameters.Add("WeaponNotes", OleDbType.LongVarWChar).Value = imageData.weaponNotes;
                    command.Parameters.Add("CaliberID", OleDbType.Integer).Value = imageData.caliber.caliberUnitID;
                    command.Parameters.Add("CaliberValue", OleDbType.Double).Value = imageData.caliberValue;
                    setStringParameter(command, "LotNumber", imageData.lotNumber);
                    command.Parameters.Add("ProjectileMassGrains", OleDbType.Integer).Value = imageData.projectileMassGrains;
                    command.Parameters.Add("AmmunitionNotes", OleDbType.LongVarWChar).Value = imageData.ammunitionNotes;
                    command.Parameters.Add("ShotsFired", OleDbType.Integer).Value = imageData.shotsFired;

                    StringBuilder pointStringBuilder = new StringBuilder();
                    foreach (Point point in imageData.points) {
                        pointStringBuilder.Append(point.X);
                        pointStringBuilder.Append(",");
                        pointStringBuilder.Append(point.Y);
                        pointStringBuilder.Append(",");
                    }
                    command.Parameters.Add("ShotLocations", OleDbType.LongVarWChar).Value = pointStringBuilder.ToString();

                    StringBuilder scaleStringBuilder = new StringBuilder();
                    scaleStringBuilder.Append(imageData.scale.horizontal.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontal.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontalLength);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.verticalLength);
                    setStringParameter(command, "Scale", scaleStringBuilder.ToString());

                    StringBuilder ROIStringBuilder = new StringBuilder();
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.Y);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.Y);
                    setStringParameter(command, "ROI", ROIStringBuilder.ToString());

                    command.Parameters.Add("TargetID", OleDbType.Integer).Value = imageData.targetID;

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform UPDATE Target.", "SQL", command.CommandText);
                        throw e;
                    }
                }
            }

            return imageData.targetID;
        }
Пример #7
0
        /// <summary>
        /// Inserts an <c>ImageData</c> object into the <c>Target</c> table.
        /// </summary>
        /// <param name="imageData">The <c>ImageData</c> to insert.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        /// <exception cref="InvalidOperationException">The INSERT INTO Target command failed.</exception>
        /// <exception cref="ArgumentException">The caliber or weapon name was not found in the database.</exception>
        /// <returns>The <c>targetID</c> of the newly-inserted record.</returns>
        private static int InsertData(Datatype.ImageData imageData, ConfigReader configReader)
        {
            int targetID = -1;
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                if (!CaliberIDExists(imageData.caliber.caliberUnitID, configReader)) {
                    Log.LogError("Caliber to insert not found in database.", "unitID",
                        imageData.caliber.caliberUnitID.ToString(), "unitName", imageData.caliber.unitName,
                        "unitsPerInch", imageData.caliber.unitsPerInch.ToString());
                    throw new ArgumentException("Caliber to insert does not exist.", "caliber");
                }
                if (!WeaponExists(imageData.weaponName, configReader)) {
                    Log.LogError("Weapon name to insert not found in database.", "weaponName", imageData.weaponName);
                    throw new ArgumentException("Weapon name to insert not found in database.", "weaponName");
                }

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "INSERT INTO Target (OrigFilename, ReportFilename, DateTimeFired, DateTimeProcessed, ShooterLName, ShooterFName, RangeLocation, DistanceUnits, Distance, Temperature, WeaponName, SerialNumber, WeaponNotes, CaliberID, CaliberValue, LotNumber, ProjectileMassGrains, AmmunitionNotes, ShotsFired, ShotLocations, Scale, ROI) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    command.Prepare();
                    setStringParameter(command, "OrigFilename", imageData.origFilename);
                    setStringParameter(command, "ReportFilename", imageData.reportFilename);
                    command.Parameters.Add("DateTimeFired", OleDbType.Date).Value = imageData.dateTimeFired;
                    command.Parameters.Add("DateTimeProcessed", OleDbType.Date).Value = DateTime.Now;
                    setStringParameter(command, "ShooterLName", imageData.shooterLName);
                    setStringParameter(command, "ShooterFName", imageData.shooterFName);
                    setStringParameter(command, "RangeLocation", imageData.rangeLocation);
                    command.Parameters.Add("DistanceUnits", OleDbType.UnsignedTinyInt).Value = imageData.distanceUnits;
                    command.Parameters.Add("Distance", OleDbType.Integer).Value = imageData.distance;
                    command.Parameters.Add("Temperature", OleDbType.UnsignedTinyInt).Value = imageData.temperature;
                    setStringParameter(command, "WeaponName", imageData.weaponName);
                    setStringParameter(command, "SerialNumber", imageData.serialNumber);
                    command.Parameters.Add("WeaponNotes", OleDbType.LongVarWChar).Value = imageData.weaponNotes == null ? "" : imageData.weaponNotes;
                    command.Parameters.Add("CaliberID", OleDbType.Integer).Value = imageData.caliber.caliberUnitID;
                    command.Parameters.Add("CaliberValue", OleDbType.Double).Value = imageData.caliberValue;
                    setStringParameter(command, "LotNumber", imageData.lotNumber);
                    command.Parameters.Add("ProjectileMassGrains", OleDbType.Integer).Value = imageData.projectileMassGrains;
                    command.Parameters.Add("AmmunitionNotes", OleDbType.LongVarWChar).Value = imageData.ammunitionNotes == null ? "" : imageData.ammunitionNotes;
                    command.Parameters.Add("ShotsFired", OleDbType.Integer).Value = imageData.shotsFired;

                    StringBuilder pointStringBuilder = new StringBuilder();
                    foreach (Point point in imageData.points) {
                        pointStringBuilder.Append(point.X);
                        pointStringBuilder.Append(",");
                        pointStringBuilder.Append(point.Y);
                        pointStringBuilder.Append(",");
                    }
                    command.Parameters.Add("ShotLocations", OleDbType.LongVarWChar).Value = pointStringBuilder.ToString();

                    StringBuilder scaleStringBuilder = new StringBuilder();
                    scaleStringBuilder.Append(imageData.scale.horizontal.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontal.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.middle.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.X);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.vertical.Y);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.horizontalLength);
                    scaleStringBuilder.Append(",");
                    scaleStringBuilder.Append(imageData.scale.verticalLength);
                    setStringParameter(command, "Scale", scaleStringBuilder.ToString());

                    StringBuilder ROIStringBuilder = new StringBuilder();
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.topLeft.Y);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.X);
                    ROIStringBuilder.Append(",");
                    ROIStringBuilder.Append(imageData.regionOfInterest.bottomRight.Y);
                    setStringParameter(command, "ROI", ROIStringBuilder.ToString());

                    try {
                        command.ExecuteNonQuery();
                    } catch (InvalidOperationException e) {
                        Log.LogError("Could not perform INSERT INTO Target.", "SQL", command.CommandText);
                        throw e;
                    }
                }

                using (OleDbCommand command = new OleDbCommand("SELECT MAX(TargetID) FROM Target", conn)) {
                    using (OleDbDataReader reader = command.ExecuteReader()) {
                        if (reader.Read()) {
                            targetID = reader.GetInt32(0);
                        } else {
                            Log.LogError("Unable to get the maximum TargetID.", "SQL", command.CommandText);
                        }
                    }
                }
            }

            return targetID;
        }
Пример #8
0
 /// <summary>
 /// Loads a <c>CaliberUnit</c> from the database.
 /// </summary>
 /// <param name="caliberID">The <paramref name="caliberID"/> of the <c>CaliberUnit</c>.</param>
 /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
 /// <returns>The <c>CaliberUnit</c> from the database.</returns>
 /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
 private static Datatype.CaliberUnit GetCaliberUnit(int caliberID, ConfigReader configReader)
 {
     using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
         openConnection(conn);
         using (OleDbCommand command = new OleDbCommand()) {
             command.Connection = conn;
             command.CommandText = "SELECT * FROM Caliber WHERE CaliberID = ?";
             command.Prepare();
             command.Parameters.Add("CaliberID", OleDbType.Integer).Value = caliberID;
             using (OleDbDataReader reader = command.ExecuteReader()) {
                 if (reader.Read()) {
                     // We could trust that the columns are index 0, 1, and 2,
                     // but let's use the specific column name for safety.
                     int caliberUnitID = reader.GetInt32(reader.GetOrdinal("CaliberID"));
                     String unitName = reader.GetString(reader.GetOrdinal("UnitName"));
                     double unitsPerInch = reader.GetDouble(reader.GetOrdinal("UnitsPerInch"));
                     if (caliberID != caliberUnitID) {
                         Log.LogError("IDs do not match in GetCaliberUnit().", "caliberID", caliberID.ToString(),
                             "caliberUnitID", caliberUnitID.ToString());
                     }
                     return new Datatype.CaliberUnit(caliberUnitID, unitName, unitsPerInch);
                 }
             }
         }
     }
     Log.LogError("Caliber unit not found in database.", "unitID", caliberID.ToString());
     throw new Exception("Error in GetCaliberUnit()");
 }
Пример #9
0
 /// <summary>
 /// Returns true if the given <c>caliberID</c> is in the database.
 /// </summary>
 /// <param name="caliberID">The <c>caliberID</c> to find.</param>
 /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
 /// <returns>True if the given <c>caliberID</c> is in the database.</returns>
 private static Boolean CaliberIDExists(int caliberID, ConfigReader configReader)
 {
     using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
         openConnection(conn);
         using (OleDbCommand command = new OleDbCommand()) {
             command.Connection = conn;
             command.CommandText = "SELECT CaliberID FROM Caliber WHERE CaliberID = ?";
             command.Prepare();
             command.Parameters.Add("CaliberID", OleDbType.Integer).Value = caliberID;
             using (OleDbDataReader reader = command.ExecuteReader()) {
                 return reader.HasRows;
             }
         }
     }
 }
Пример #10
0
        /// <summary>
        /// Loads an <c>ImageData</c> from the database.
        /// </summary>
        /// <param name="targetID">The <paramref name="targetID"/> of the target to load.</param>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <returns>The <c>ImageData</c> corresponding to the <paramref name="targetID"/>.</returns>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        public static Datatype.ImageData LoadData(int targetID, ConfigReader configReader)
        {
            Datatype.ImageData imageData = new Datatype.ImageData();
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                using (OleDbCommand command = new OleDbCommand()) {
                    command.Connection = conn;
                    command.CommandText = "SELECT * FROM Target WHERE TargetID = ?";
                    command.Prepare();
                    command.Parameters.Add("TargetID", OleDbType.Integer).Value = targetID;

                    using (OleDbDataReader reader = command.ExecuteReader()) {
                        if (reader.Read()) {
                            imageData.targetID = reader.GetInt32(reader.GetOrdinal("TargetID"));
                            if (imageData.targetID != targetID) {
                                throw new Exception("Error in LoadData()");
                            }

                            imageData.origFilename = reader.GetString(reader.GetOrdinal("OrigFilename"));
                            imageData.reportFilename = reader.GetString(reader.GetOrdinal("ReportFilename"));
                            imageData.dateTimeFired = reader.GetDateTime(reader.GetOrdinal("DateTimeFired"));
                            imageData.dateTimeProcessed = reader.GetDateTime(reader.GetOrdinal("DateTimeProcessed"));
                            imageData.shooterLName = reader.GetString(reader.GetOrdinal("ShooterLName"));
                            imageData.shooterFName = reader.GetString(reader.GetOrdinal("ShooterFName"));
                            imageData.rangeLocation = reader.GetString(reader.GetOrdinal("RangeLocation"));
                            imageData.distanceUnits = (Datatype.UnitsOfMeasure)reader.GetByte(reader.GetOrdinal("DistanceUnits"));
                            imageData.distance = reader.GetInt32(reader.GetOrdinal("Distance"));
                            imageData.temperature = (Datatype.ImageData.Temperature)reader.GetByte(reader.GetOrdinal("Temperature"));
                            imageData.weaponName = reader.GetString(reader.GetOrdinal("WeaponName"));
                            imageData.serialNumber = reader.GetString(reader.GetOrdinal("SerialNumber"));
                            imageData.weaponNotes = reader.GetString(reader.GetOrdinal("WeaponNotes"));
                            imageData.caliber = GetCaliberUnit(reader.GetInt32(reader.GetOrdinal("CaliberID")), configReader);
                            imageData.caliberValue = reader.GetDouble(reader.GetOrdinal("CaliberValue"));
                            imageData.lotNumber = reader.GetString(reader.GetOrdinal("LotNumber"));
                            imageData.projectileMassGrains = reader.GetInt32(reader.GetOrdinal("ProjectileMassGrains"));
                            imageData.ammunitionNotes = reader.GetString(reader.GetOrdinal("AmmunitionNotes"));
                            imageData.shotsFired = reader.GetInt32(reader.GetOrdinal("ShotsFired"));

                            String points = reader.GetString(reader.GetOrdinal("ShotLocations"));
                            String[] pointElements = points.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (pointElements.Length % 2 != 0) {
                                Log.LogWarning("A Points field has invalid values.", "targetID", targetID.ToString(),
                                    "SQL", command.CommandText);
                            } else {
                                for (int i = 0; i < pointElements.Length; i += 2) {
                                    imageData.points.Add(new Point(Int32.Parse(pointElements[i]), Int32.Parse(pointElements[i + 1])));
                                }
                            }

                            String scale = reader.GetString(reader.GetOrdinal("Scale"));
                            String[] scaleElements = scale.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (scaleElements.Length != 8) {
                                Log.LogWarning("A Scale field has invalid values.", "targetID", targetID.ToString(),
                                    "SQL", command.CommandText);
                            } else {
                                imageData.scale.horizontal = new Point(Int32.Parse(scaleElements[0]), Int32.Parse(scaleElements[1]));
                                imageData.scale.middle = new Point(Int32.Parse(scaleElements[2]), Int32.Parse(scaleElements[3]));
                                imageData.scale.vertical = new Point(Int32.Parse(scaleElements[4]), Int32.Parse(scaleElements[5]));
                                imageData.scale.horizontalLength = float.Parse(scaleElements[6]);
                                imageData.scale.verticalLength = float.Parse(scaleElements[7]);
                            }

                            String ROI = reader.GetString(reader.GetOrdinal("ROI"));
                            String[] ROIElements = ROI.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (ROIElements.Length != 4) {
                                Log.LogWarning("An ROI field has invalid values.", "targetID", targetID.ToString(),
                                    "SQL", command.CommandText);
                            } else {
                                imageData.regionOfInterest.topLeft = new Point(Int32.Parse(ROIElements[0]), Int32.Parse(ROIElements[1]));
                                imageData.regionOfInterest.bottomRight = new Point(Int32.Parse(ROIElements[2]), Int32.Parse(ROIElements[3]));
                            }
                        } else {
                            Log.LogInfo("Target ID not found.", "targetID", targetID.ToString(), "SQL", command.CommandText);
                            return null;
                        }
                    }
                }
            }

            return imageData;
        }
Пример #11
0
        /// <summary>
        /// Loads a list of weapon names from the database.
        /// </summary>
        /// <param name="configReader">The <c>ConfigReader</c> with the path to the database.</param>
        /// <returns>A list of all weapon names in the database.</returns>
        /// <exception cref="OleDbException">A connection-level error occurred while opening the connection.</exception>
        public static List<String> GetWeaponNames(ConfigReader configReader)
        {
            List<String> weaponNames = new List<String>();
            using (OleDbConnection conn = new OleDbConnection(configReader.getValue("Database Location"))) {
                openConnection(conn);

                using (OleDbCommand command = new OleDbCommand("SELECT WeaponName FROM Weapon", conn)) {
                    using (OleDbDataReader reader = command.ExecuteReader()) {
                        while (reader.Read()) {
                            // We could trust that the column is index 0,
                            // but let's use the specific column name for safety.
                            weaponNames.Add(reader.GetString(reader.GetOrdinal("WeaponName")));
                        }
                    }
                }
            }

            return weaponNames;
        }
Пример #12
0
        private static void insertStat(ExcelWorksheet reportWorksheet, string configName, double statValue, ConfigReader reader)
        {
            String output = "=IF(" + reader.getValue("Cell To Determine Unit of Measure") + " =\"Statistics (in inches):\", " + statValue + ", IF(" + reader.getValue("Cell To Determine Unit of Measure") + " =\"Statistics (in centimeters):\", " + (statValue * 2.54) + ", " + (statValue * minutesOfAngleConverter) + "))";

            reportWorksheet.Cells[reader.getValue(configName)].Formula = output;
        }
Пример #13
0
        public static void GenerateReport(IList<Datatype.DoublePoint> newPoints, Datatype.ImageData data, Datatype.Stats stats, ConfigReader reader)
        {
            string imagePath = data.origFilename;
            string savePath = data.reportFilename;

            if (savePath == null)
            {
                throw new NullReferenceException("A save path must be provided in order for the report to save");
            }

            //Open Excel File
            ExcelFile excelFile = new ExcelFile();

            try
            {
                excelFile.LoadXlsx(reader.getValue("Template Location"),
                                  XlsxOptions.PreserveKeepOpen);
            }
            //Catch and report error if directory is not valid
            catch (System.IO.DirectoryNotFoundException)
            {
                MessageBox.Show("A report could not be generated.  Please check the configuration file for errors.  " +
                "The path to the default template contains a directory that doesn't seem to exist.", "Directory Not Found",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new System.InvalidOperationException("DirectoryNotFoundException");
            }
            //Catch and return error if file is not found.
            catch (System.IO.FileNotFoundException)
            {
                MessageBox.Show("A report could not be generated.  Please check the configuration file for errors.  " +
                "The file name given doesn't seem to exist.", "File Not Found",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new System.InvalidOperationException("FileNotFoundException");
            }
            //Catch and report error if the file is already opened and locked
            catch (System.IO.IOException)
            {
                MessageBox.Show("A report could not be generated because the template file is locked.  " +
                "Please close any application that may be using the file and try again.", "File Could Not Load",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                throw new System.InvalidOperationException("FileLoadException");
            }
            ExcelWorksheet reportWorksheet = excelFile.Worksheets[0];
            ExcelWorksheet otherStatsWorksheet = excelFile.Worksheets[1];

            //Set row fill color.
            Color rowFillColor = Color.FromArgb(219, 229, 241);

            //Check that data.distance != 0
            if (data.distance == 0)
            {
                throw new DivideByZeroException("Data.distance cannot be 0");
            }

            //Determine minutes of angle factor.  If yards, use the literal data.distance; else convert to yards.
            if (data.distanceUnits == SANTA.Datatype.UnitsOfMeasure.Yard)
            {
                minutesOfAngleConverter = minutesOfAngleConversionFactor*100/data.distance;
            } else if (data.distanceUnits == SANTA.Datatype.UnitsOfMeasure.Meter)
            {
                minutesOfAngleConverter = minutesOfAngleConversionFactor*100/(data.distance*1.0936133);
            } else
            {
                //Should never get here, but exception will trigger if we do.
                throw new InstanceNotFoundException("Distance Units are not of a known datatype.");
            }

            // Column width of 8, 30, 16, 9, 9, 9, 9, 4 and 5 characters.
            reportWorksheet.Columns[0].Width = 285/7*256;
            reportWorksheet.Columns[1].Width = 107/7*256;
            reportWorksheet.Columns[2].Width = 12*(256 - 24);
            reportWorksheet.Columns[3].Width = 12*(256 - 24);
            reportWorksheet.Columns[4].Width = 12*(256 - 24);
            reportWorksheet.Columns[5].Width = 12*(256 - 24);
            reportWorksheet.Columns[6].Width = 12*(256 - 24);
            reportWorksheet.Columns[7].Width = 12*(256 - 24);

            // Fill in cell data

            placeValue(reportWorksheet, "Target Distance", data.distance);

            reportWorksheet.Cells[reader.getValue("Shooter Name")].Value = data.shooterFName + " " + data.shooterLName;
            reportWorksheet.Cells[reader.getValue("Shoot Date")].Value = data.dateTimeFired;
            reportWorksheet.Cells[reader.getValue("Shoot Date")].Style.NumberFormat = reader.getValue("Date Format");
            reportWorksheet.Cells[reader.getValue("Range Name")].Value = data.rangeLocation;
            reportWorksheet.Cells[reader.getValue("Temperature")].Value = Datatype.ImageData.tempDetails[(int) data.temperature];
            reportWorksheet.Cells[reader.getValue("Target Distance")].Value = data.distance + " " + data.distanceUnits;

            if (data.shotsFired == newPoints.Count)
            {
                reportWorksheet.Cells[reader.getValue("Shots Fired")].Value = data.shotsFired;
            }
            else
            {
                reportWorksheet.Cells[reader.getValue("Shots Fired")].Value = newPoints.Count.ToString() + " found of " + data.shotsFired.ToString() + " indicated";
            }

            reportWorksheet.Cells[reader.getValue("Weapon Name")].Value = data.weaponName;
            reportWorksheet.Cells[reader.getValue("Weapon Serial Number")].Value = data.serialNumber;
            reportWorksheet.Cells[reader.getValue("Ammo Caliber")].Value = data.caliberValue + " " + data.caliber.unitName;
            reportWorksheet.Cells[reader.getValue("Ammo Lot Number")].Value = data.lotNumber;
            reportWorksheet.Cells[reader.getValue("Ammo Mass")].Value = data.projectileMassGrains + " grains";

            reportWorksheet.Cells[reader.getValue("Target ID")].Value = "Target ID: " + data.targetID;
            reportWorksheet.Cells[reader.getValue("Weapon Notes")].Value = "Weapon Notes: " + data.weaponNotes;
            reportWorksheet.Cells[reader.getValue("Ammo Notes")].Value = "Ammo Notes: " + data.ammunitionNotes;

            //Fill in the shot records
            Random generator = new Random();

                for (int i = 0; i < newPoints.Count && i < 50; i++)
                {
                    //TODO: Set first point of x, y, z values (or specify each point)
                    insertPoints(reportWorksheet, "G" + (i + 15).ToString(), newPoints[i].X, reader);
                    insertPoints(reportWorksheet, "H" + (i + 15).ToString(), newPoints[i].Y, reader);

                    //Color every other row in the shot record table.
                    if (i % 2 == 1)
                    {
                        reportWorksheet.Cells["F" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                        reportWorksheet.Cells["G" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                        reportWorksheet.Cells["H" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                    }

                }

            //Fill in the color for
                for (int i = newPoints.Count; i < 50; i = i + 2)
            {
                //if the first time through, we are on an odd instead of an even, put us back on evens.
                if (i%2 == 0)
                {
                    i++;
                }
                reportWorksheet.Cells["F" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                reportWorksheet.Cells["G" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
                reportWorksheet.Cells["H" + (i + 15).ToString()].Style.FillPattern.SetSolid(rowFillColor);
            }

            //Display stats
            insertStat(reportWorksheet, "Extreme Spread X", stats.extremeSpreadX, reader);
            insertStat(reportWorksheet, "Extreme Spread Y", stats.extremeSpreadY, reader);
            insertStat(reportWorksheet, "Extreme Spread", stats.extremeSpread, reader);
            insertStat(reportWorksheet, "Mean Radius", stats.meanRadius, reader);
            insertStat(reportWorksheet, "Sigma X", stats.sigmaX, reader);
            insertStat(reportWorksheet, "Sigma Y", stats.sigmaY, reader);
            insertStat(reportWorksheet, "Furthest Left", stats.furthestLeft, reader);
            insertStat(reportWorksheet, "Furthest Right", stats.furthestRight, reader);
            insertStat(reportWorksheet, "Highest Round", stats.highestRound, reader);
            insertStat(reportWorksheet, "Lowest Round", stats.lowestRound, reader);
            insertStat(reportWorksheet, "CEP", stats.CEPRadius, reader);

            //Add a small image of the pic in the upper right corner.
            Bitmap image = new Bitmap(imagePath);
            int width = image.Width;
            int height = image.Height;

            double aspectRatio = (double)width / (double)height;

            image.Dispose();

            if (aspectRatio > (double)reportImageWidth / (double)reportImageHeight)
            {
                double newHeight = (double)reportImageWidth / aspectRatio * 0.9; // The 0.9 is a fudge factor because GemBox doesn't know how to scale things properly.
                reportWorksheet.Pictures.Add(imagePath, new Rectangle(0, (int) ((reportImageHeight - newHeight) * 0.5), reportImageWidth, (int) (newHeight + 0.5)));
            }
            else
            {
                double newWidth = (double)reportImageHeight * aspectRatio / 0.9; // The 0.9 is a fudge factor because GemBox doesn't know how to scale things properly.
                reportWorksheet.Pictures.Add(imagePath, new Rectangle((int) ((reportImageWidth - newWidth) * 0.5), 0, (int) (newWidth + 0.5), reportImageHeight));
            }

            //Add CEP Data
            otherStatsWorksheet.Cells[reader.getValue("X Offset")].Value = stats.center.X;
            otherStatsWorksheet.Cells[reader.getValue("Y Offset")].Value = stats.center.Y;
            otherStatsWorksheet.Cells[reader.getValue("Mean X Offset")].Value = stats.center.X;
            otherStatsWorksheet.Cells[reader.getValue("Mean Y Offset")].Value = stats.center.Y;
            otherStatsWorksheet.Cells[reader.getValue("CEP Radius")].Formula = "=IF(Report!" + reader.getValue("CEP Toggle Cell") + " =\"CEP Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.CEPRadius + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.CEPRadius * 2.54) + ", " + (stats.CEPRadius * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Mean Radius Circle")].Formula = "=IF(Report!" + reader.getValue("Mean Radius Toggle Cell") + " =\"Mean Radius Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.meanRadius + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.meanRadius * 2.54) + ", " + (stats.meanRadius * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread x1")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[0].X + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[0].X * 2.54) + ", " + (stats.extremePoints[0].X * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread x2")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[1].X + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[1].X * 2.54) + ", " + (stats.extremePoints[1].X * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread y1")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[0].Y + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[0].Y * 2.54) + ", " + (stats.extremePoints[0].Y * minutesOfAngleConverter) + ")))";
            otherStatsWorksheet.Cells[reader.getValue("Extreme Spread y2")].Formula = "=IF(Report!" + reader.getValue("Extreme Spread Toggle Cell") + " =\"Extreme Spread Off\", " + 0 + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + stats.extremePoints[1].Y + ", IF(Report!" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (stats.extremePoints[1].Y * 2.54) + ", " + (stats.extremePoints[1].Y * minutesOfAngleConverter) + ")))";

            //Generate CEP Circle formula data
            for (int cell = 0; cell <= 39; cell++)
            {
                otherStatsWorksheet.Cells["B" + (cell + 9).ToString()].Formula = "=$B$3+A" + (cell + 9).ToString();
                otherStatsWorksheet.Cells["C" + (cell + 9).ToString()].Formula = "=SQRT(ABS(POWER($B$5,2)-POWER(B" + (cell + 9).ToString() + ",2))) +$B$4";
                otherStatsWorksheet.Cells["D" + (cell + 9).ToString()].Formula = "=$B$4 - SQRT(ABS(POWER($B$5,2)-POWER(B" + (cell + 9).ToString() + ",2)))";
            }

            //Generate Mean Circle formula data
            for (int cell = 0; cell <= 39; cell++)
            {
                otherStatsWorksheet.Cells["M" + (cell + 9).ToString()].Formula = "=$M$3+L" + (cell + 9).ToString();
                otherStatsWorksheet.Cells["N" + (cell + 9).ToString()].Formula = "=SQRT(ABS(POWER($M$5,2)-POWER(M" + (cell + 9).ToString() + ",2))) +$M$4";
                otherStatsWorksheet.Cells["O" + (cell + 9).ToString()].Formula = "=$M$4 - SQRT(ABS(POWER($M$5,2)-POWER(M" + (cell + 9).ToString() + ",2)))";
            }

            try
            {
                //Write Report
                excelFile.SaveXlsx(savePath);
            }
            catch (System.IO.IOException)
            {
                MessageBox.Show("A report could not be generated.  The file you attempted to save to is busy.  Please close all applications using  " + savePath +
                " and press ok to continue.", "File Open", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                throw new System.InvalidOperationException("DirectoryNotFoundException");
            }
            finally
            {
                //Close Report
                excelFile.ClosePreservedXlsx();
            }
            //Check to see what to do with report now
                switch (reader.getValue("Open Excel By Default").ToString())
                {
                    case "nothing":
                        break;
                    case "prompt":
                        DialogResult response = MessageBox.Show("Would you like to open the report you just created?", "Open report?",
                                        MessageBoxButtons.YesNo);
                        if (response == DialogResult.Yes)
                        {
                            openReportWithExcel(savePath);
                        }
                        break;
                    case "open":
                        openReportWithExcel(savePath);
                        break;
                }
        }
Пример #14
0
        private static void insertPoints(ExcelWorksheet reportWorksheet, string configName, double statValue, ConfigReader reader)
        {
            String output = "=IF(" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in inches)\", " + statValue + ", IF(" + reader.getValue("Cell To Determine Unit of Points") + " =\"Shot Record (in centimeters)\", " + (statValue * 2.54) + ", " + (statValue * minutesOfAngleConverter) + "))";

            reportWorksheet.Cells[configName].Formula = output;
        }