Advertisement
Guest User

documentation we might lose when merging

a guest
Jan 21st, 2016
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.50 KB | None | 0 0
  1. using System;
  2. using System.Data.SqlClient;
  3.  
  4. using TeamCShared.Data;
  5. using TeamCShared.Messages;
  6. using TeamCShared.DatabaseAPI.Query;
  7. using TeamCShared.DatabaseAPI.DBMessages;
  8.  
  9. namespace TeamCShared.DatabaseAPI
  10. {
  11.  
  12.     public class DBWrapper
  13.     {
  14.  
  15.         // Use to test Database independently    
  16.         static void Main()
  17.         {
  18.             DBWrapper database = new DBWrapper();
  19.             database.Connect();
  20.             // database.InitializeSchema();
  21.             //database.Command("create table sharks (SharkName varchar(255), Depth int);");
  22.             //database.Command("drop table sharks");
  23.             database.Disconnect();
  24.         }
  25.  
  26.         // Members
  27.         SqlConnection connection;
  28.         SQLGenerator sqlGenerator;
  29.  
  30.         /* TODO: DBWrapper should not have state, because instantiated in multiple classes
  31.         elsewhere in the system. need to find a better way to keep track of transaction ids
  32.         and get rid of these ID members */
  33.         ulong jsonID;
  34.         ulong transactionID;
  35.  
  36.         /// <summary>
  37.         /// Constructor
  38.         /// </summary>
  39.         public DBWrapper() {
  40.             jsonID = 1;
  41.             transactionID = 1;
  42.             sqlGenerator = new SQLGenerator(this);
  43.         }
  44.  
  45.         // Methods
  46.  
  47.         // -- Helper Methods
  48.  
  49.         public string freshJID()
  50.         {
  51.             string rval = Convert.ToString(jsonID);
  52.             jsonID++;
  53.             return rval;          
  54.         }
  55.        
  56.         public ulong freshTID()
  57.         {
  58.             ulong rval = transactionID;
  59.             transactionID++;
  60.             return rval;
  61.         }
  62.  
  63.         /// <summary>
  64.         /// Set up a connection to the Database and create tables if they do not exist.
  65.         /// </summary>
  66.         ///
  67.         /// <returns>
  68.         /// true if connection was successful, false if SQL exception occurred
  69.         /// </returns>
  70.         public bool Connect()
  71.         {
  72.             bool returnVal = true;
  73.             string connectionString, password, userName, SQLConnectionString;
  74.  
  75.             connectionString =
  76.                 @"Server=tcp:comp410-teamc.database.windows.net,1433;
  77.                Database=Warmup-C;
  78.                Connection Timeout=30;
  79.                Encrypt = True;
  80.                TrustServerCertificate=False;";
  81.  
  82.             // njm3: this hard-coded authentication stuff worries me
  83.             userName = "teamc_admin";
  84.             password = "Sharks4ever";
  85.  
  86.             SQLConnectionString = "Password=" + password + ';' +
  87.                 "User ID=" + userName + ";" + connectionString;
  88.  
  89.             try
  90.             {
  91.                 connection = new SqlConnection(SQLConnectionString);
  92.                 connection.Open();
  93.             }
  94.             catch (SqlException e)
  95.             {
  96.                 e.ToString();
  97.                 returnVal = false;
  98.             }
  99.  
  100.             InitializeSchema();
  101.             return returnVal;
  102.  
  103.         }
  104.  
  105.         /// <summary>
  106.         /// Close connection to the database.
  107.         /// </summary>
  108.         ///
  109.         /// <returns>
  110.         /// True if connection successfully closed, false if a SQL exception occurred
  111.         /// </returns>
  112.         public bool Disconnect()
  113.         {
  114.             bool returnVal = true;
  115.             try
  116.             {
  117.                 connection.Close();
  118.                 connection.Dispose();
  119.             }
  120.             catch (SqlException e)
  121.             {
  122.                 e.ToString();
  123.                 returnVal = false;
  124.             }
  125.  
  126.             return returnVal;
  127.         }
  128.  
  129.  
  130.  
  131.         /// <summary>
  132.         /// Sends Non-Query SQL commands (that is, commands that do not require a return value)
  133.         /// </summary>
  134.         ///
  135.         /// <param name="sqlQuery">
  136.         /// the non-query command to be executed
  137.         /// </param>
  138.         public void Command(string sqlQuery)
  139.         {
  140.             SqlCommand command = new SqlCommand();
  141.             command.Connection = connection;
  142.             command.CommandType = System.Data.CommandType.Text;
  143.             command.CommandText = sqlQuery;
  144.             command.ExecuteNonQuery();
  145.         }
  146.  
  147.         /// <summary>
  148.         /// Sends Query SQL commands (that is, commands that require a return value)
  149.         /// </summary>
  150.         ///
  151.         /// <param name="sqlQuery">
  152.         /// the query command to be executed
  153.         /// </param>
  154.         ///
  155.         /// <returns>
  156.         /// a SQLDataReader
  157.         /// </returns>
  158.         public System.Data.SqlClient.SqlDataReader Query(string sqlQuery)
  159.         {
  160.             SqlCommand command = new SqlCommand();
  161.             command.Connection = connection;
  162.             command.CommandType = System.Data.CommandType.Text;
  163.             command.CommandText = sqlQuery;
  164.             return command.ExecuteReader();
  165.         }
  166.  
  167.         public void InitializeSchema()
  168.         {
  169.             // Construct Float Table
  170.  
  171.             Command(@"if not exists(select 1 from sys.Tables where Name = N'FloatData' and Type = N'U')
  172.                      begin
  173.                          create table FloatData (Data float, ID int);
  174.                      end");
  175.  
  176.             // Construct String Table
  177.             Command(@"if not exists(select 1 from sys.Tables where Name = N'StringData' and Type = N'U')
  178.                      begin
  179.                          create table StringData (Data varchar(255), ID int);
  180.                      end");
  181.  
  182.             // Construct JSON Table
  183.             Command(@"
  184.                      if not exists(select 1 from sys.Tables where Name = N'JSONData' and Type = N'U')
  185.                      begin
  186.                          create table JSONData (Name varchar(255), JSONKey varchar(255), FloatVal float, StringVal varchar(255), ID int);
  187.                      end");
  188.  
  189.             // Construct ToDelete bookeeping table.
  190.             Command(@"
  191.                      if not exists(select 1 from sys.Tables where Name = N'ToDelete' and Type = N'U')
  192.                      begin
  193.                          create table ToDelete (ID int, TableType varchar(255));
  194.                      end");
  195.  
  196.         }
  197.  
  198.  
  199.         //API
  200.  
  201.  
  202.         /// <summary>
  203.         /// Get data from the already-connected database
  204.         /// </summary>
  205.         ///
  206.         /// <param name="message">
  207.         /// An <see cref="TeamCShared.DatabaseAPI.DBMessages.IDBMessage"/> which contains a query
  208.         /// </param>
  209.         public void getData(GetDBMessage message)
  210.         {
  211.             /*
  212.             string query = "";
  213.             string dataType = "";
  214.            
  215.             // Get query from message
  216.             // Get table identifier
  217.  
  218.             query = @" UPDATE _____Data
  219.                     SET ID = ___
  220.                     OUTPUT Inserted.Data
  221.                     WHERE _____ AND ID = 0";
  222.  
  223.            query =  @"UPDATE JSONData
  224.                     SET ID = ___
  225.                     OUTPUT Inserted.Name, Inserted.JSONKey, Inserted.FloatData, Inserted.StringData
  226.                     WHERE NAME IN
  227.                     (SELECT NAME FROM JSONData
  228.                     WHERE _______) AND ID = 0;";
  229.  
  230.            */
  231.  
  232.             // TODO
  233.             // Set data type in ToDelete
  234.             // Remember to close the reader
  235.  
  236.         }
  237.  
  238.         /// <summary>
  239.         /// Put data into the already-connected database
  240.         /// </summary>
  241.         ///
  242.         /// <param name="message">
  243.         /// An <see cref="TeamCShared.DatabaseAPI.DBMessages.IDBMessage"/> with the data to be sent
  244.         /// </param>
  245.         public void putData(PutDBMessage message)
  246.         {
  247.             IData data = message.data;
  248.             data.process(sqlGenerator);
  249.         }
  250.  
  251.         /// <summary>
  252.         /// Delete data from the already-connected database
  253.         /// </summary>
  254.         ///
  255.         /// <param name="message">
  256.         /// An <see cref="TeamCShared.DatabaseAPI.DBMessages.IDBMessage"/> with the transaction id to delete
  257.         /// </param>
  258.         public void delData(DeleteDBMessage message)
  259.         {
  260.             // TODO DISALLOW 0 REMOVAL
  261.             int id = message.id;
  262.             string tableName = "";
  263.             System.Data.SqlClient.SqlDataReader reader = Query(
  264.                 @"SELECT TableType
  265.                FROM ToDelete
  266.                WHERE ToDelete.ID = " + Convert.ToString(id));
  267.  
  268.            
  269.  
  270.             if (reader.Read())
  271.             {
  272.                 switch (reader.GetString(0))
  273.                 {
  274.                     case "f":
  275.                         tableName = "FloatData";
  276.                         break;
  277.                     case "s":
  278.                         tableName = "StringData";
  279.                         break;
  280.                     case "j":
  281.                         tableName = "JSONData";
  282.                         break;
  283.                     default:
  284.                         break;
  285.                         // TODO HANDLE ERROR CASES
  286.                 }
  287.             }
  288.             reader.Close();
  289.  
  290.             //remove data from table only if transaction id is in ToDelete table
  291.             Command(
  292.                     @"DELETE " +  tableName +
  293.                     "FROM " + tableName +
  294.                     "INNER JOIN ToDelete" +
  295.                     "ON ToDelete.ID = " + tableName + ".ID " +
  296.                     "Where ToDelete.ID = " + Convert.ToString(id) + ";");
  297.  
  298.             //remove transaction id from ToDelete table
  299.             Command(
  300.                     @"DELETE FROM ToDelete
  301.                    WHERE ID = "+ Convert.ToString(id) + ";");
  302.         }
  303.  
  304.     }
  305. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement