Initial commit

This commit is contained in:
2014-04-30 17:47:28 -04:00
commit 60d6f93543
102 changed files with 11747 additions and 0 deletions

228
Data/Database.cs Normal file
View File

@@ -0,0 +1,228 @@
using System;
using System.Data.SqlServerCe;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Common.Debug;
using FeedCenter.Properties;
namespace FeedCenter.Data
{
public static class Database
{
#region Static database settings
public static string DatabasePath;
#endregion
#region File version
private enum SqlServerCeFileVersion
{
Unknown,
Version20,
Version30,
Version35,
Version40,
}
private static SqlServerCeFileVersion GetFileVersion(string databasePath)
{
// Create a mapping of version numbers to the version enumeration
var versionMapping = new Dictionary<int, SqlServerCeFileVersion>
{
{ 0x73616261, SqlServerCeFileVersion.Version20 },
{ 0x002dd714, SqlServerCeFileVersion.Version30 },
{ 0x00357b9d, SqlServerCeFileVersion.Version35 },
{ 0x003d0900, SqlServerCeFileVersion.Version40 }
};
int signature;
try
{
// Open the database file
using (FileStream stream = new FileStream(databasePath, FileMode.Open, FileAccess.Read))
{
// Read the file using the binary reader
BinaryReader reader = new BinaryReader(stream);
// Seek to the version signature
stream.Seek(16, SeekOrigin.Begin);
// Read the version signature
signature = reader.ReadInt32();
}
}
catch (Exception exception)
{
Tracer.WriteException(exception);
throw;
}
// If we know about the version number then return the right enumeration - otherwise unknown
return versionMapping.ContainsKey(signature) ? versionMapping[signature] : SqlServerCeFileVersion.Unknown;
}
#endregion
public static bool DatabaseExists
{
get { return File.Exists(DatabasePath); }
}
public static void CreateDatabase()
{
Tracer.WriteLine("Creating database engine");
// Create the database engine
using (SqlCeEngine engine = new SqlCeEngine(string.Format("Data Source={0}", DatabasePath)))
{
Tracer.WriteLine("Creating database");
// Create the database itself
engine.CreateDatabase();
Tracer.WriteLine("Running database script");
// Run the creation script
ExecuteScript(Resources.CreateDatabase);
}
}
private static int getVersion(SqlCeConnection connection)
{
string versionString = string.Empty;
try
{
// Check the database version table
using (SqlCeCommand command = new SqlCeCommand("SELECT Value FROM DatabaseVersion", connection))
versionString = command.ExecuteScalar().ToString();
}
catch (SqlCeException)
{
// Check the setting table for the version
using (SqlCeCommand command = new SqlCeCommand("SELECT Value FROM Setting WHERE Name = 'DatabaseVersion'", connection))
versionString = command.ExecuteScalar().ToString();
}
if (string.IsNullOrEmpty(versionString))
versionString = "0";
Tracer.WriteLine("Database version: {0}", versionString);
return int.Parse(versionString);
}
public static void UpdateDatabase()
{
Tracer.WriteLine("Getting database file version");
// Get the database file version
SqlServerCeFileVersion fileVersion = GetFileVersion(DatabasePath);
Tracer.WriteLine("Database file version: {0}", fileVersion);
// See if we need to upgrade the database file version
if (fileVersion != SqlServerCeFileVersion.Version40)
{
Tracer.WriteLine("Creating database engine");
// Create the database engine
using (SqlCeEngine engine = new SqlCeEngine(string.Format("Data Source={0}", DatabasePath)))
{
Tracer.WriteLine("Upgrading database");
// Upgrade the database (if needed)
engine.Upgrade();
}
}
Tracer.WriteLine("Getting database version");
// Create a database connection
using (SqlCeConnection connection = new SqlCeConnection(string.Format("Data Source={0}", DatabasePath)))
{
// Open the connection
connection.Open();
// Get the database version
int databaseVersion = getVersion(connection);
// Create a dictionary of database upgrade scripts and their version numbers
var scriptList = new Dictionary<int, string>();
// Loop over the properties of the resource object looking for update scripts
foreach (var property in typeof(Resources).GetProperties().Where(property => property.Name.StartsWith("DatabaseUpdate")))
{
// Get the name of the property
string propertyName = property.Name;
// Extract the version from the name
int version = int.Parse(propertyName.Substring(propertyName.IndexOf("_", StringComparison.Ordinal) + 1));
// Add to the script list
scriptList[version] = propertyName;
}
// Loop over the scripts ordered by version
foreach (var pair in scriptList.OrderBy(pair => pair.Key))
{
// If the database version is less than or equal to the script version the script needs to run
if (databaseVersion <= pair.Key)
{
// Get the script text
string scriptText = Resources.ResourceManager.GetString(pair.Value);
// Run the script
ExecuteScript(scriptText);
}
}
}
}
public static void MaintainDatabase()
{
Tracer.WriteLine("Creating database engine");
// Create the database engine
using (SqlCeEngine engine = new SqlCeEngine(string.Format("Data Source={0}", DatabasePath)))
{
Tracer.WriteLine("Shrinking database");
// Compact the database
engine.Shrink();
}
}
private static void ExecuteScript(string scriptText)
{
// Create a database connection
using (SqlCeConnection connection = new SqlCeConnection(string.Format("Data Source={0}", DatabasePath)))
{
// Open the connection
connection.Open();
// Setup the delimiters
string[] delimiters = new[] { "\r\nGO\r\n" };
// Split the script at the delimiters
string[] statements = scriptText.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
// Loop over each statement in the script
foreach (string statement in statements)
{
// Execute the statement
using (SqlCeCommand command = new SqlCeCommand(statement, connection))
command.ExecuteNonQuery();
}
}
}
}
}

155
Data/Extensions.cs Normal file
View File

@@ -0,0 +1,155 @@
using System;
using System.Data;
using System.Data.SqlServerCe;
using System.Data.SqlTypes;
namespace FeedCenter.Data
{
public static class Extensions
{
#region SqlDateTime
public static SqlDateTime SqlDateTimeZero = new SqlDateTime(0, 0);
#endregion
#region DataSet
public static DataRow GetFirstDataRow(this DataSet dataSet)
{
// If we get no data set then return nothing
if (dataSet == null)
return null;
// If there were no tables returns then return nothing
if (dataSet.Tables.Count == 0)
return null;
// Get the first table
DataTable firstTable = dataSet.Tables[0];
// If the table has no rows then return nothing
if (firstTable.Rows.Count == 0)
return null;
// Return the first row
return firstTable.Rows[0];
}
#endregion
#region SqlCeCommand
public static void SetStatement(this SqlCeCommand command, string statement, params object[] parameters)
{
// Create a new array to hold the updated parameters
object[] formattedParameters = new object[parameters.Length];
// Initialize our position
int position = 0;
// Loop over each parameter
foreach (object parameter in parameters)
{
// If the parameter is a DateTime then we need to reformat
if (parameter == null)
{
// Use a explicit null value
formattedParameters[position++] = "NULL";
}
else if (parameter is DateTime)
{
// Cast the parameter back to a DateTime
DateTime dateTime = (DateTime) parameter;
// Convert the DateTime to sortable format
string formatted = dateTime.ToString("s");
// Set into the formatted array
formattedParameters[position++] = formatted;
}
else if (parameter is bool)
{
// Convert the boolean to a number
formattedParameters[position++] = Convert.ToInt32(parameter);
}
else if (parameter.GetType().IsEnum)
{
// Convert the enum to a number
formattedParameters[position++] = Convert.ToInt32(parameter);
}
else if (parameter is string)
{
// Escape single quotes
formattedParameters[position++] = (parameter as string).Replace("'", "''");
}
else
{
// Just put the original value in
formattedParameters[position++] = parameter;
}
}
// Build the full statement
command.CommandText = string.Format(statement, formattedParameters);
}
#endregion
#region SqlCeConnection
public static void ExecuteNonQuery(this SqlCeConnection connection, string query, params object[] parameters)
{
// Create the command object
SqlCeCommand command = connection.CreateCommand();
// Set the statement based on the query and parameters
command.SetStatement(query, parameters);
//Tracer.WriteLine("Executing SQL statement: {0}", command.CommandText);
// Execute the command
command.ExecuteNonQuery();
}
public static DataSet ExecuteDataSet(this SqlCeConnection connection, string query, params object[] parameters)
{
// Create the command object
SqlCeCommand command = connection.CreateCommand();
// Set the statement based on the query and parameters
command.SetStatement(query, parameters);
// Create a new data adapter
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter(command))
{
// Create the new data set
using (DataSet dataSet = new DataSet())
{
//Tracer.WriteLine("Executing SQL query: {0}", command.CommandText);
// Fill the data set
adapter.Fill(dataSet);
return dataSet;
}
}
}
public static object ExecuteScalar(this SqlCeConnection connection, string query, params object[] parameters)
{
// Create the command object
SqlCeCommand command = connection.CreateCommand();
// Set the statement based on the query and parameters
command.SetStatement(query, parameters);
//Tracer.WriteLine("Executing SQL statement: {0}", command.CommandText);
// Execute the command
return command.ExecuteScalar();
}
#endregion
}
}