Advertisement
Anaristos

dmsManager(Data Provider)

Jan 29th, 2012
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.63 KB | None | 0 0
  1. /************************************************************************
  2. --[ License ] -----------------------------------------------------------
  3.  
  4.   This program is free software; you can redistribute it and/or
  5.   modify it under the terms of the GNU General Public License
  6.   as published by the Free Software Foundation; either version 3
  7.   of the License, or (at your option) any later version.
  8.  
  9.   This program is distributed in the hope that it will be useful,
  10.   but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.   GNU General Public License for more details.
  13.  
  14.   You should have received a copy of the GNU General Public License
  15.   along with this program; if not, write to the Free Software
  16.   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  17.  
  18.   You may also access the licence here: http://www.gnu.org/licenses/gpl.html
  19.  
  20.  ------------------------------------------------------------------------
  21.   Copyright (c) 2009-11 Gomez & Associates
  22. /************************************************************************/
  23.  
  24. using System;
  25. using System.IO;
  26. using System.Collections;
  27. using System.Collections.Generic;
  28. using System.Data;
  29. using System.Runtime.InteropServices;
  30. using System.Text;
  31. using System.Text.RegularExpressions;
  32. using System.Windows.Forms;
  33. using Newtonsoft.Json;
  34.  
  35. namespace dmsManager
  36. {
  37.     public partial class DataProvider
  38.     {
  39.         const int SQLITE_OK         =   0;   /* Successful result */
  40.         const int SQLITE_ERROR      =   1;   /* SQL error or missing database */
  41.         const int SQLITE_INTERNAL   =   2;   /* An internal logic error in SQLite */
  42.         const int SQLITE_PERM       =   3;   /* Access permission denied */
  43.         const int SQLITE_ABORT      =   4;   /* Callback routine requested an abort */
  44.         const int SQLITE_BUSY       =   5;   /* The database file is locked */
  45.         const int SQLITE_LOCKED     =   6;   /* A table in the database is locked */
  46.         const int SQLITE_NOMEM      =   7;   /* A malloc() failed */
  47.         const int SQLITE_READONLY   =   8;   /* Attempt to write a readonly database */
  48.         const int SQLITE_INTERRUPT  =   9;   /* Operation terminated by sqlite_interrupt() */
  49.         const int SQLITE_IOERR      =  10;   /* Some kind of disk I/O error occurred */
  50.         const int SQLITE_CORRUPT    =  11;   /* The database disk image is malformed */
  51.         const int SQLITE_NOTFOUND   =  12;   /* (Internal Only) Table or record not found */
  52.         const int SQLITE_FULL       =  13;   /* Insertion failed because database is full */
  53.         const int SQLITE_CANTOPEN   =  14;   /* Unable to open the database file */
  54.         const int SQLITE_PROTOCOL   =  15;   /* Database lock protocol error */
  55.         const int SQLITE_EMPTY      =  16;   /* (Internal Only) Database table is empty */
  56.         const int SQLITE_SCHEMA     =  17;   /* The database schema changed */
  57.         const int SQLITE_TOOBIG     =  18;   /* Too much data for one row of a table */
  58.         const int SQLITE_CONSTRAINT =  19;   /* Abort due to constraint violation */
  59.         const int SQLITE_MISMATCH   =  20;   /* Data type mismatch */
  60.         const int SQLITE_MISUSE     =  21;   /* Library used incorrectly */
  61.         const int SQLITE_NOLFS      =  22;   /* Uses OS features not supported on host */
  62.         const int SQLITE_AUTH       =  23;   /* Authorization denied */
  63.         const int SQLITE_FORMAT     =  24;   /* Auxiliary database format error */
  64.         const int SQLITE_RANGE      =  25;   /* 2nd parameter to sqlite3_bind out of range */
  65.         const int SQLITE_NOTADB     =  26;   /* File opened that is not a database file */
  66.         const int SQLITE_ROW        = 100;   /* sqlite_step() has another row ready */
  67.         const int SQLITE_DONE       = 101;   /* sqlite_step() has finished executing */
  68.  
  69.         const int SQLITE_UTF8          = 1;
  70.         const int SQLITE_UTF16LE       = 2;
  71.         const int SQLITE_UTF16BE       = 3;
  72.         const int SQLITE_UTF16         = 4;    /* Use native byte order */
  73.         const int SQLITE_ANY           = 5;    /* sqlite3_create_function only */
  74.         const int SQLITE_UTF16_ALIGNED = 8;    /* sqlite3_create_collation only */
  75.  
  76.         const int SQLITE_INTEGER = 1;
  77.         const int SQLITE_FLOAT   = 2;
  78.         const int SQLITE_TEXT    = 3;
  79.         const int SQLITE_BLOB    = 4;
  80.         const int SQLITE_NULL    = 5;
  81.  
  82.  
  83.         internal static IntPtr SQLITE_STATIC    = IntPtr.Zero;
  84.         internal static IntPtr SQLITE_TRANSIENT = (IntPtr)(-1);
  85.  
  86.         internal static IntPtr NULL_POINTER = IntPtr.Zero;
  87.  
  88.         const string SQLITE_DLL = "sqlite3.dll";
  89.  
  90.         internal bool   _cmudFormat   = Properties.Settings.Default.cmudFormat;
  91.         internal string _dQuote       = "\"";
  92.         internal string _hashEntrySep = Properties.Settings.Default.hashEntrySep;
  93.         internal string _keyValueSep  = Properties.Settings.Default.keyValueSep;
  94.         internal string _errormsg     = "";
  95.         internal string _null         = Properties.Settings.Default.NULL;
  96.         internal bool   _open         = false;
  97.         internal string _path         = "";
  98.         internal string _procPath     = "";
  99.         internal string _provider     = Properties.Settings.Default.Provider;
  100.         internal string _resultSep    = Properties.Settings.Default.resultSep;
  101.         internal bool   _useJson      = Properties.Settings.Default.jsonFormat;
  102.         internal bool   _useMap       = Properties.Settings.Default.useMap;
  103.         internal int    _version      = 0;
  104.  
  105.         internal static UTF8Encoding encoding = null; //for string to UTF-8 translation.
  106.  
  107.         DataSet _ds = null;
  108.  
  109.         statement_context _sc = null;
  110.  
  111.         /// <summary>
  112.         /// This method is called by the constructor and does the actually object initalization.
  113.         /// The sqlite3.dll is checked for version and the application terminates if lower than 3.0.0.0.
  114.         /// </summary>
  115.         /// <param name="path">
  116.         /// Path to the database file (optional).
  117.         /// </param>
  118.         /// <param name="json">
  119.         /// Flag indicating whether json-formatted result sets are returned.
  120.         /// If this flag is reset an arraylist is returned instead.
  121.         /// </param>
  122.         private void init(string path, bool jason)
  123.         {
  124.             _version = sqlite3_libversion_number();
  125.  
  126.             if (3000000 > _version)
  127.             {
  128.                 MessageBox.Show("Invalid SQLITE.DLL VERSION: " + _version);
  129.  
  130.                 Application.Exit();
  131.             }
  132.  
  133.             encoding = new UTF8Encoding(false, true);
  134.  
  135.             _ds = new DataSet();
  136.  
  137.             _sc = new statement_context();
  138.  
  139.             if (path != null) this.open(path);
  140.  
  141.             this.JSONFormat = jason;
  142.         }
  143.  
  144.         /// <summary>
  145.         ///  This function builds the SQlite3 custom functions found in the function table.
  146.         /// </summary>
  147.         /// <returns>
  148.         /// Returns whether the operation is successful or not.
  149.         /// If any of the function installations fails the installation terminates at that point.
  150.         /// </returns>
  151.         private int installUserFunctions()
  152.         {
  153.             int rc = SQLITE_OK;
  154.  
  155.             foreach (var f in uf) //create user functions.
  156.             {
  157.                 rc = sqlite3_create_function(_conn, encoding.GetBytes(f.Key), f.Value.Count, SQLITE_ANY, NULL_POINTER, f.Value.Func, null, null);
  158.  
  159.                 if (rc != SQLITE_OK) break;
  160.             }
  161.  
  162.             return rc;
  163.         }
  164.  
  165.         private string readFile(string filename)
  166.         {
  167.             StreamReader sr = null;
  168.  
  169.             string query = null;
  170.  
  171.             try
  172.             {
  173.                 sr = new StreamReader(_procPath + filename);
  174.  
  175.                 query = sr.ReadToEnd();
  176.  
  177.                 sr.Close();
  178.             }
  179.             catch (IOException ioe)
  180.             {
  181.                 _errormsg = ioe.Message;
  182.  
  183.                 query = null;
  184.             }
  185.             finally
  186.             {
  187.                 if (sr != null) sr.Close();
  188.             }
  189.  
  190.             return query;
  191.         }
  192.  
  193.         private void BindParameters()
  194.         {
  195.             int pCount = sqlite3_bind_parameter_count(_sc.stmtHandle), rCount = _sc.argc - _sc.argp, index = 0, mCount = pCount - rCount;
  196.  
  197.             int limit = _sc.argp + Math.Min(pCount, rCount);
  198.  
  199.             _sc.rc = SQLITE_OK;
  200.  
  201.             for (; _sc.argp < limit; _sc.argp++)
  202.             {
  203.                 if (_sc.args[_sc.argp] is Int32) _sc.rc = sqlite3_bind_int(_sc.stmtHandle, ++index, (int) _sc.args[_sc.argp]);
  204.  
  205.                 else if (_sc.args[_sc.argp] is Int64) _sc.rc = sqlite3_bind_double(_sc.stmtHandle, ++index, (double) _sc.args[_sc.argp]);
  206.  
  207.                 else if (_sc.args[_sc.argp] != null) _sc.rc = sqlite3_bind_text(_sc.stmtHandle, ++index, (string) _sc.args[_sc.argp], -1, SQLITE_TRANSIENT);
  208.  
  209.                     else _sc.rc = sqlite3_bind_null(_sc.stmtHandle, ++index);
  210.  
  211.                 if (_sc.rc != SQLITE_OK) break;
  212.             }
  213.  
  214.             if (mCount > 0 && _sc.rc == SQLITE_OK)
  215.             {
  216.                 for (; index < mCount; index++)
  217.                 {
  218.                     _sc.rc = sqlite3_bind_null(_sc.stmtHandle, index);
  219.  
  220.                     if (_sc.rc != SQLITE_OK) break;
  221.                 }
  222.             }            
  223.         }
  224.  
  225.         private void PrepareStatement()
  226.         {
  227.             string query = _sc.getNext();
  228.  
  229.             _sc.rc = sqlite3_prepare_v2(_conn, query, query.Length, out _sc.stmtHandle, out NULL_POINTER);
  230.  
  231.             if (_sc.rc != SQLITE_OK) _errormsg = sqlite3_errmsg(_conn);
  232.         }
  233.  
  234.         private void FinalizeStatement()
  235.         {
  236.             _sc.rc = sqlite3_finalize(_sc.stmtHandle);
  237.  
  238.             _sc.stmtHandle = NULL_POINTER;
  239.  
  240.             if ( _sc.rc != SQLITE_OK) _errormsg = sqlite3_errmsg(_conn);
  241.         }
  242.  
  243.         private int processScript(string query)
  244.         {
  245.             if (_open)
  246.             {
  247.                 _errormsg = "";
  248.  
  249.                 IntPtr errMsg;
  250.  
  251.                 sqlite3_exec(_conn, query, null, NULL_POINTER, out errMsg);
  252.  
  253.                 if (errMsg != NULL_POINTER)
  254.                 {
  255.                     _errormsg = Marshal.PtrToStringAnsi(errMsg);
  256.  
  257.                     sqlite3_free(errMsg);
  258.  
  259.                     return SQLITE_ERROR;
  260.                 }
  261.  
  262.                 return SQLITE_OK;
  263.             }
  264.  
  265.             _errormsg = "Cannot operate on a closed database.";
  266.  
  267.             return SQLITE_ERROR;
  268.         }
  269.  
  270.         private string processScalarQuery(string query, params object[] args)
  271.         {
  272.             if (_open)
  273.             {
  274.                 _errormsg = ""; //bug fixed 01/29/2011.
  275.  
  276.                 _sc.setContext(query, args);
  277.  
  278.                 object result = null;
  279.  
  280.                 PrepareStatement();
  281.  
  282.                 if (_sc.rc == SQLITE_OK)
  283.                 {
  284.                     BindParameters();
  285.  
  286.                     if (_sc.rc == SQLITE_OK)
  287.                     {
  288.                         if (sqlite3_column_count(_sc.stmtHandle) > 0)
  289.                         {
  290.                             if (sqlite3_step(_sc.stmtHandle) == SQLITE_ROW)
  291.                             {
  292.                                 switch (sqlite3_column_type(_sc.stmtHandle, 0))
  293.                                 {
  294.                                     case SQLITE_NULL:
  295.                                         result = "";
  296.                                         break;
  297.                                     default:
  298.                                         result = sqlite3_column_text(_sc.stmtHandle, 0);
  299.                                         break;
  300.                                 }
  301.                             }
  302.  
  303.                             else result = "";
  304.  
  305.                             FinalizeStatement();
  306.  
  307.                             if (result != null) return result.ToString();
  308.  
  309.                             else return "";
  310.                         }
  311.                     }
  312.                 }
  313.  
  314.                 FinalizeStatement();
  315.  
  316.                 return "";        
  317.             }
  318.  
  319.             _errormsg = "Cannot operate on a closed database.";
  320.  
  321.             return "";
  322.         }
  323.  
  324.         private void processQuery(string query, params object[] args)
  325.         {
  326.             if (_open)
  327.             {
  328.                 _errormsg = ""; //bug fixed 01/29/2011.
  329.  
  330.                 _sc.setContext(query, args);
  331.  
  332.                 _ds.Clear();
  333.  
  334.                 while (!_sc.isComplete)
  335.                 {
  336.                     PrepareStatement();
  337.  
  338.                     if (_sc.rc == SQLITE_OK)
  339.                     {
  340.                         BindParameters();
  341.  
  342.                         if (_sc.rc == SQLITE_OK) getRows();
  343.  
  344.                         else break;
  345.                     }
  346.                 }
  347.  
  348.                 FinalizeStatement();
  349.             }
  350.  
  351.             else _errormsg = "Cannot operate on a closed database.";
  352.         }
  353.  
  354.         private void getRows()
  355.         {
  356.             int columnCount = sqlite3_column_count(_sc.stmtHandle);
  357.  
  358.             DataTable dt = _ds.Tables.Add();
  359.  
  360.             double temp;
  361.  
  362.             for (int i = 0; i < columnCount; i++) dt.Columns.Add(sqlite3_column_name(_sc.stmtHandle, i));
  363.  
  364.             while (sqlite3_step(_sc.stmtHandle) == SQLITE_ROW)
  365.             {
  366.                 object[] row = new object[columnCount];
  367.  
  368.                 for (int i = 0; i < columnCount; i++)
  369.                 {
  370.                     if (SQLITE_NULL == sqlite3_column_type(_sc.stmtHandle, i)) row[i] = _null;
  371.  
  372.                     else row[i] = sqlite3_column_text(_sc.stmtHandle, i);
  373.  
  374.                     if (double.TryParse((string) row[i], out temp)) row[i] = temp;
  375.                 }
  376.  
  377.                 dt.Rows.Add(row);
  378.             }
  379.  
  380.             FinalizeStatement();
  381.         }    
  382.  
  383.         private string testnull(string arg)
  384.         {
  385.             return (arg != null) ? arg : _null;
  386.         }
  387.  
  388.         private string normalize(string arg)
  389.         {
  390.             string m = @"\""|\|";
  391.             string s = arg.Replace("\"", "\"\"");
  392.  
  393.             return Regex.IsMatch(s, m) == false ? s : "\"" + s + "\"";
  394.         }
  395.  
  396.         private string getJsonData()
  397.         {
  398.             return JsonConvert.SerializeObject(getJsonDataRecord());
  399.         }
  400.  
  401.         private string getData()
  402.         {
  403.             if (_useJson) return getJsonData();
  404.  
  405.             List<string> list = new List<string>();
  406.  
  407.             foreach (DataTable dt in _ds.Tables)
  408.             {
  409.                 if (dt == null || dt.Rows.Count == 0) continue;
  410.  
  411.                 List<string> list2 = new List<string>(), result = new List<string>();
  412.  
  413.                 string k, v;
  414.  
  415.                 foreach (DataRow r in dt.Rows)
  416.                 {
  417.                     list2.Clear();
  418.  
  419.                     foreach (DataColumn c in dt.Columns)
  420.                     {
  421.                         k = c.ColumnName;
  422.                         v = testnull(r[k].ToString());
  423.  
  424.                         if (this._useMap) list2.Add(normalize(k) + this._keyValueSep + normalize(v));
  425.  
  426.                         else list2.Add(normalize(v));
  427.                     }
  428.  
  429.                     result.Add(string.Join(_hashEntrySep, list2.ToArray()));
  430.                 }
  431.  
  432.                 list.Add(string.Join(_resultSep, result.ToArray()));
  433.             }
  434.  
  435.             return string.Join(ResultSep, list.ToArray());
  436.         }
  437.  
  438.         private ArrayList getJsonDataRecord()
  439.         {
  440.             ArrayList record = new ArrayList();
  441.  
  442.             string k;
  443.             object v;
  444.  
  445.             Hashtable h = null;
  446.  
  447.             foreach (DataTable dt in _ds.Tables)
  448.             {
  449.                 foreach (DataRow r in dt.Rows)
  450.                 {
  451.                     if (_useMap) h = new Hashtable();
  452.  
  453.                     foreach (DataColumn c in dt.Columns)
  454.                     {
  455.                         double nv;
  456.  
  457.                         k = c.ColumnName;
  458.                         v = r[k];
  459.  
  460.                         if (!double.TryParse(v.ToString(), out nv)) v = testnull(v.ToString());
  461.  
  462.                         if (_useMap) h.Add(k, v);
  463.  
  464.                         else record.Add(v);
  465.                     }
  466.  
  467.                     if (_useMap) record.Add(h);
  468.                 }
  469.             }
  470.  
  471.             return record;
  472.         }
  473.  
  474.         internal object[] getParams(string data, out string query)
  475.         {
  476.             query = null;
  477.  
  478.             ArrayList al = JsonConvert.DeserializeObject<ArrayList>(data);
  479.  
  480.             if (al.Count == 0) return null;
  481.  
  482.             query = (string) al[0];
  483.  
  484.             al.RemoveAt(0);
  485.  
  486.             return al.ToArray();
  487.         }
  488.     }
  489. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement