Advertisement
Anaristos

sqlServer (DataProvider)

Dec 11th, 2011
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.85 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 © 2009-11 Gomez & Associates
  22. /************************************************************************/
  23.  
  24. using System;
  25. using System.Collections;
  26. using System.Collections.Generic;
  27. using System.Data;
  28. using System.Data.SqlClient;
  29. using System.Text;
  30. using System.Text.RegularExpressions;
  31. using System.Windows.Forms;
  32.  
  33. namespace sqlServer
  34. {
  35.     public partial class DataProvider
  36.     {
  37.         internal string defaultInstance = Properties.Settings.Default.MachineName + @"\" +
  38.                                           Properties.Settings.Default.DefaultInstance;
  39.  
  40.         internal bool   _cmudFormat      = Properties.Settings.Default.cmudFormat;
  41.         internal string _currConn        = "";
  42.         internal string _dQuote          = @"""";
  43.         internal string _hashEntrySep    = Properties.Settings.Default.hashEntrySep;
  44.         internal string _keyValueSep     = Properties.Settings.Default.keyValueSep;
  45.         internal string _errormsg        = "";
  46.         internal string _null            = @"""""";
  47.         internal bool   _open            = false;
  48.         internal string _dbName          = "";
  49.         internal string _instance        = "";
  50.         internal string _machineName     =  Properties.Settings.Default.MachineName;
  51.         internal string _defaultInstance = Properties.Settings.Default.DefaultInstance;
  52.         internal string _provider        = Properties.Settings.Default.Provider;
  53.         internal string _resultSep       = Properties.Settings.Default.resultSep;
  54.         internal bool   _useJson         = Properties.Settings.Default.jsonFormat;
  55.         internal bool   _useMap          = Properties.Settings.Default.useMap;
  56.         internal bool   _debug           = Properties.Settings.Default.Debug;
  57.         internal string _version         = "00.00.0000.00";
  58.  
  59.         SqlConnection _conn = null; // sqlServer connection reference.
  60.  
  61.         SqlCommand cmd = null;
  62.  
  63.         string connStr = null;
  64.  
  65.         private void getOpenParms(string input)
  66.         {
  67. /*
  68.             string[] temp = input.Split(new char[] { '\\' });
  69.  
  70.             if (temp.Length < 1 || temp.Length > 2) throw new Exception("Invalid parameter passed to Open method");
  71.  
  72.             if (temp.Length == 1)
  73.             {
  74.                 _instance = defaultInstance;
  75.                 _dbName = temp[0];
  76.             }
  77.  
  78.             else
  79.             {
  80.                 _instance = temp[0];
  81.                 _dbName = temp[1];
  82.             }
  83.  
  84.             _currConn = _instance + @"\" + _dbName;
  85. */
  86.             // Added on 12/05/2011 to allow connections to LocalDB instances.
  87.             int i = input.LastIndexOf(@"\");
  88.  
  89.             if (i != -1)
  90.             {
  91.                 _instance = input.Substring(0, i);
  92.                 _dbName   = input.Substring(i + 1);
  93.             }
  94.  
  95.             else          
  96.             {
  97.                 _instance = defaultInstance;
  98.                 _dbName   = input;
  99.             }
  100.  
  101.             _currConn = _instance + @"\" + _dbName;
  102.         }
  103.  
  104.         private void init(string dbName, bool json)
  105.         {
  106.             if (dbName != null) this.open(dbName);
  107.  
  108.             this.JSONFormat = json;
  109.  
  110.             initDelegateTable();
  111.         }
  112.  
  113.         public void open(string dbName)
  114.         {
  115.             getOpenParms(dbName);
  116.  
  117.             if (_open)
  118.             {
  119.                 if (_currConn != dbName)
  120.                 {
  121.                     close();
  122.  
  123.                     open();
  124.                 }
  125.             }
  126.  
  127.             else open();
  128.         }
  129.  
  130.         public void open()
  131.         {
  132.             _errormsg = "";
  133.  
  134.  //           connStr = Properties.Settings.Default.connectionString.Replace(defaultInstance, _instance) + _dbName + @";";
  135.             connStr = "Server=" + _instance + Properties.Settings.Default.connectionString + _dbName + @";"; // 12/05/2011
  136.  
  137.             try
  138.             {
  139.                 _conn = new SqlConnection(connStr);
  140.  
  141.                 _conn.Open();
  142.             }
  143.  
  144.             catch (SqlException e)
  145.             {
  146.                 _errormsg = e.Message;
  147.  
  148.                 if (_conn != null) _conn.Close();
  149.             }
  150.  
  151.             if (_conn.State.ToString() == "Open")
  152.             {
  153.                 _open = true;
  154.             }
  155.         }
  156.  
  157.         public void close()
  158.         {
  159.             _errormsg = "";
  160.  
  161.             if (_open)
  162.             {
  163.                 try
  164.                 {
  165.                     _conn.Close();
  166.                 }
  167.  
  168.                 catch (SqlException e)
  169.                 {
  170.                     _errormsg = e.Message;
  171.                 }
  172.             }
  173.  
  174.             else _errormsg = "Database is not open.";
  175.  
  176.             _open = false;
  177.         }
  178.  
  179.         internal object execOpen(string sql, Hashtable args)
  180.         {
  181.             _errormsg = "";
  182.  
  183.             _instance = (string) args["instance"];
  184.  
  185.             _dbName = (string) args["dbName"];
  186.  
  187.             connStr = Properties.Settings.Default.connectionString.Replace(defaultInstance, _instance) + _dbName + @";";
  188.  
  189.             try
  190.             {
  191.                 _conn = new SqlConnection(connStr);
  192.  
  193.                 _conn.Open();
  194.             }
  195.  
  196.             catch (SqlException e)
  197.             {
  198.                 _errormsg = e.Message;
  199.  
  200.                 if (_conn != null) _conn.Close();
  201.             }
  202.  
  203.             if (_conn.State.ToString() == "Open") _open = true;
  204.  
  205.             return null;
  206.         }
  207.  
  208.         internal object execClose(string sql, Hashtable args)
  209.         {
  210.             _errormsg = "";
  211.  
  212.             if (_open)
  213.             {
  214.                 try
  215.                 {
  216.                     _conn.Close();
  217.                 }
  218.  
  219.                 catch (SqlException e)
  220.                 {
  221.                     _errormsg = e.Message;
  222.                 }
  223.             }
  224.  
  225.             else _errormsg = "Database is not open.";
  226.  
  227.             _open = false;
  228.  
  229.             return null;
  230.         }
  231.  
  232.         internal object execInsert(string sql, Hashtable args)
  233.         {
  234.             return null;
  235.         }
  236.  
  237.         internal object execDelete(string sql, Hashtable args)
  238.         {
  239.             return null;
  240.         }
  241.  
  242.         internal object execNonQuery(string sql, Hashtable args)
  243.         {
  244.             _errormsg = "";
  245.  
  246.             cmd = new SqlCommand(sql, _conn);
  247.  
  248.             cmd.CommandType = CommandType.Text;
  249.  
  250.             cmd.Parameters.Clear();
  251.  
  252.             try
  253.             {
  254.                 if (args != null)
  255.                 {
  256.                     foreach (DictionaryEntry kv in args)
  257.                     {
  258.                         if (kv.Value.GetType() == typeof(String)) cmd.Parameters.AddWithValue((string) kv.Key, kv.Value);
  259.  
  260.                         else cmd.Parameters.AddWithValue((string) kv.Key, kv.Value.ToString());
  261.                     }
  262.                 }
  263.  
  264.                 return cmd.ExecuteNonQuery();
  265.             }
  266.  
  267.             catch (Exception e)
  268.             {
  269.                 _errormsg = e.Message;
  270.  
  271.                 return 0;
  272.             }
  273.         }
  274.  
  275.         internal object execProc(string sql, Hashtable args)
  276.         {
  277.             _errormsg = "";
  278.  
  279.             SqlDataReader dr = null;
  280.  
  281.             cmd = new SqlCommand(sql, _conn);
  282.  
  283.             cmd.CommandType = CommandType.StoredProcedure;
  284.  
  285.             cmd.Parameters.Clear();
  286.  
  287.             try
  288.             {
  289.                 if (args != null)
  290.                 {
  291.                     foreach (DictionaryEntry kv in args)
  292.                     {
  293.                         if (kv.Value.GetType() == typeof(String)) cmd.Parameters.AddWithValue((string) kv.Key, kv.Value);
  294.  
  295.                         else cmd.Parameters.AddWithValue((string) kv.Key, kv.Value.ToString());
  296.                     }
  297.                 }
  298.  
  299.                 dr = cmd.ExecuteReader();
  300.  
  301.                 return getData(dr);
  302.             }
  303.  
  304.             catch (Exception e)
  305.             {
  306.                 _errormsg = e.Message;
  307.  
  308.                 return null;
  309.             }
  310.  
  311.             finally
  312.             {
  313.                 if (!(dr == null || dr.IsClosed)) dr.Close();
  314.             }
  315.         }
  316.  
  317.         internal object execProcNR(string sql, Hashtable args)
  318.         {
  319.             _errormsg = "";
  320.  
  321.             cmd = new SqlCommand(sql, _conn);
  322.  
  323.             cmd.CommandType = CommandType.StoredProcedure;
  324.  
  325.             cmd.Parameters.Clear();
  326.  
  327.             try
  328.             {
  329.                 if (args != null)
  330.                 {
  331.                     foreach (DictionaryEntry kv in args)
  332.                     {
  333.                         if (kv.Value.GetType() == typeof(String)) cmd.Parameters.AddWithValue((string) kv.Key, kv.Value);
  334.  
  335.                         else cmd.Parameters.AddWithValue((string) kv.Key, kv.Value.ToString());
  336.                     }
  337.                 }
  338.  
  339.                 return cmd.ExecuteNonQuery();
  340.             }
  341.  
  342.             catch (Exception e)
  343.             {
  344.                 _errormsg = e.Message;
  345.  
  346.                 return 0;
  347.             }
  348.         }
  349.  
  350.         internal object execSelect(string sql, Hashtable args)
  351.         {
  352.             _errormsg = "";
  353.  
  354.             cmd = new SqlCommand(sql, _conn);
  355.  
  356.             cmd.CommandType = CommandType.Text;
  357.  
  358.             cmd.Parameters.Clear();
  359.  
  360.             try
  361.             {
  362.                 if (args != null)
  363.                 {
  364.                     foreach (DictionaryEntry kv in args)
  365.                     {
  366.                         if (kv.Value.GetType() == typeof(String)) cmd.Parameters.AddWithValue((string) kv.Key, kv.Value);
  367.  
  368.                         else cmd.Parameters.AddWithValue((string) kv.Key, kv.Value.ToString());
  369.                     }
  370.                 }
  371.  
  372.                 SqlDataReader dr = cmd.ExecuteReader();
  373.  
  374.                 return getData(dr);
  375.             }
  376.  
  377.             catch (Exception e)
  378.             {
  379.                 _errormsg = e.Message;
  380.  
  381.                 return null;
  382.             }
  383.         }
  384.  
  385.         internal string execScalar(string sql, Hashtable args)
  386.         {
  387.             _errormsg = "";
  388.  
  389.             cmd = new SqlCommand(sql, _conn);
  390.  
  391.             cmd.CommandType = CommandType.Text;
  392.  
  393.             cmd.Parameters.Clear();
  394.  
  395.             try
  396.             {
  397.                 if (args != null)
  398.                 {
  399.                     foreach (DictionaryEntry kv in args)
  400.                     {
  401.                         if (kv.Value.GetType() == typeof(String)) cmd.Parameters.AddWithValue((string) kv.Key, kv.Value);
  402.  
  403.                         else cmd.Parameters.AddWithValue((string) kv.Key, kv.Value.ToString());
  404.                     }
  405.                 }
  406.                
  407.                 object result = cmd.ExecuteScalar();
  408.  
  409. //                if (_useJson) return JsonConvert.SerializeObject(result);
  410.  
  411.                 if (_useJson) return JSON.JSON.JsonEncode(result);
  412.  
  413.                 return result.ToString();
  414.             }
  415.  
  416.             catch (Exception e)
  417.             {
  418.                 _errormsg = e.Message;
  419.  
  420. //                if (_useJson) return JsonConvert.SerializeObject("");
  421.  
  422.                 if (_useJson) return JSON.JSON.JsonEncode("");
  423.  
  424.                 return null;
  425.             }
  426.         }
  427.  
  428.         internal object execUpdate(string sql, Hashtable args)
  429.         {
  430.             return null;
  431.         }
  432.  
  433.         private string testnull(string arg)
  434.         {
  435.             return (arg != null) ? arg : _null;
  436.         }
  437.  
  438.         private string normalize(string arg)
  439.         {
  440.             string m = @"\""|\|";
  441.             string s = arg.Replace("\"", "\"\"");
  442.  
  443.             return Regex.IsMatch(s, m) == false ? s : "\"" + s + "\"";
  444.         }
  445.  
  446.         private string getJsonData(SqlDataReader dr)
  447.         {
  448.             return JSON.JSON.JsonEncode(getJsonDataRecord(dr));
  449.         }
  450.  
  451.         private string getData(SqlDataReader dr)
  452.         {
  453.             if (_useJson) return getJsonData(dr);
  454.  
  455.             List<string> list = new List<string>(), result = new List<string>();
  456.  
  457.             if (dr.HasRows)
  458.             {
  459.                 do
  460.                 {
  461.                     while (dr.Read())
  462.                     {
  463.                         string k, v;
  464.  
  465.                         for (int i = 0; i < dr.FieldCount; i++)
  466.                         {
  467.                             k = dr.GetName(i);
  468.                             v = testnull(dr.GetValue(i).ToString());
  469.  
  470.                             if (this._useMap) list.Add(normalize(k) + this._keyValueSep + normalize(v));
  471.  
  472.                             else list.Add(normalize(v));
  473.                         }
  474.  
  475.                         result.Add(string.Join(_hashEntrySep, list.ToArray()));
  476.                     }
  477.                 }
  478.  
  479.                 while (dr.NextResult());
  480.             }
  481.  
  482.             dr.Close();
  483.  
  484.             return string.Join(ResultSep, list.ToArray());
  485.         }
  486.  
  487.         private ArrayList getJsonDataRecord(SqlDataReader dr)
  488.         {
  489.             ArrayList record = new ArrayList();
  490.  
  491.             Hashtable h = null;
  492.  
  493.             if (dr.HasRows)
  494.             {
  495.                 do
  496.                 {
  497.                     while (dr.Read())
  498.                     {
  499.                         string k;
  500.                         object v;
  501.  
  502.                         double nv;
  503.  
  504.                         if (_useMap) h = new Hashtable();
  505.  
  506.                         for (int i = 0; i < dr.FieldCount; i++)
  507.                         {
  508.                             k = dr.GetName(i);
  509.                             v = dr.GetValue(i);
  510.  
  511.                             if (!double.TryParse(v.ToString(), out nv)) v = testnull(v.ToString());
  512.  
  513.                             else v = (Int64) Math.Floor(nv);
  514.  
  515.                             if (_useMap) h.Add(k, v);
  516.  
  517.                             else record.Add(v);
  518.                         }
  519.  
  520.                         if (_useMap) record.Add(h);
  521.                     }
  522.                 }
  523.  
  524.                 while (dr.NextResult());
  525.             }
  526.  
  527.             dr.Close();
  528.  
  529.             return record;
  530.         }
  531.     }
  532. }
  533.  
  534.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement