SqlCommandTest.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. //
  2. // SqlCommandTest.cs - NUnit Test Cases for testing the
  3. // SqlCommand class
  4. // Author:
  5. // Umadevi S ([email protected])
  6. // Sureshkumar T ([email protected])
  7. // Senganal T ([email protected])
  8. //
  9. // Copyright (c) 2004 Novell Inc., and the individuals listed
  10. // on the ChangeLog entries.
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Data;
  33. using System.Data.Common;
  34. using System.Data.SqlClient;
  35. #if NET_2_0
  36. using System.Data.Sql;
  37. using System.Xml;
  38. #endif
  39. using NUnit.Framework;
  40. namespace MonoTests.System.Data.SqlClient
  41. {
  42. [TestFixture]
  43. [Category ("sqlserver")]
  44. public class SqlCommandTest
  45. {
  46. public SqlConnection conn = null ;
  47. SqlCommand cmd = null;
  48. string connectionString = ConnectionManager.Singleton.ConnectionString;
  49. [SetUp]
  50. public void Setup ()
  51. {
  52. }
  53. [TearDown]
  54. public void TearDown ()
  55. {
  56. if (conn != null)
  57. conn.Close ();
  58. }
  59. [Test]
  60. public void ConstructorTest ()
  61. {
  62. // Test Default Constructor
  63. cmd = new SqlCommand ();
  64. Assert.AreEqual (String.Empty, cmd.CommandText,
  65. "#1 Command Test should be empty");
  66. Assert.AreEqual (30, cmd.CommandTimeout,
  67. "#2 CommandTimeout should be 30");
  68. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  69. "#3 CommandType should be text");
  70. Assert.IsNull (cmd.Connection, "#4 Connection Should be null");
  71. Assert.AreEqual (0, cmd.Parameters.Count,
  72. "#5 Parameter shud be empty");
  73. // Test Overloaded Constructor
  74. String cmdText = "select * from tbl1" ;
  75. cmd = new SqlCommand (cmdText);
  76. Assert.AreEqual (cmdText, cmd.CommandText,
  77. "#5 CommandText should be the same as passed");
  78. Assert.AreEqual (30, cmd.CommandTimeout,
  79. "#6 CommandTimeout should be 30");
  80. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  81. "#7 CommandType should be text");
  82. Assert.IsNull (cmd.Connection , "#8 Connection Should be null");
  83. // Test Overloaded Constructor
  84. SqlConnection conn = new SqlConnection ();
  85. cmd = new SqlCommand (cmdText , conn);
  86. Assert.AreEqual (cmdText, cmd.CommandText,
  87. "#9 CommandText should be the same as passed");
  88. Assert.AreEqual (30, cmd.CommandTimeout,
  89. "#10 CommandTimeout should be 30");
  90. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  91. "#11 CommandType should be text");
  92. Assert.AreSame (cmd.Connection, conn, "#12 Connection Should be same");
  93. // Test Overloaded Constructor
  94. SqlTransaction trans = null ;
  95. try {
  96. conn = new SqlConnection (connectionString);
  97. conn.Open ();
  98. trans = conn.BeginTransaction ();
  99. cmd = new SqlCommand (cmdText, conn, trans);
  100. Assert.AreEqual (cmdText, cmd.CommandText,
  101. "#9 CommandText should be the same as passed");
  102. Assert.AreEqual (30, cmd.CommandTimeout,
  103. "#10 CommandTimeout should be 30");
  104. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  105. "#11 CommandType should be text");
  106. Assert.AreEqual (cmd.Connection, conn,
  107. "#12 Connection Should be null");
  108. Assert.AreEqual (cmd.Transaction, trans,
  109. "#13 Transaction Property should be set");
  110. // Test if parameters are reset to Default Values
  111. cmd = new SqlCommand ();
  112. Assert.AreEqual (String.Empty, cmd.CommandText,
  113. "#1 Command Test should be empty");
  114. Assert.AreEqual (30, cmd.CommandTimeout,
  115. "#2 CommandTimeout should be 30");
  116. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  117. "#3 CommandType should be text");
  118. Assert.IsNull (cmd.Connection, "#4 Connection Should be null");
  119. }finally {
  120. trans.Rollback ();
  121. }
  122. }
  123. [Test]
  124. public void ExecuteScalarTest ()
  125. {
  126. conn = new SqlConnection (connectionString);
  127. cmd = new SqlCommand ("" , conn);
  128. cmd.CommandText = "Select count(*) from numeric_family where id<=4";
  129. //Check Exception is thrown when executed on a closed connection
  130. try {
  131. cmd.ExecuteScalar ();
  132. Assert.Fail ("#1 InvalidOperation Exception must be thrown");
  133. }catch (AssertionException e) {
  134. throw e;
  135. }catch (Exception e) {
  136. #if NET_2_0
  137. Assert.AreEqual (typeof (NullReferenceException), e.GetType (),
  138. "#2 Incorrect Exception : " + e.StackTrace);
  139. #else
  140. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  141. "#2 Incorrect Exception : " + e.StackTrace);
  142. #endif
  143. }
  144. // Check the Return value for a Correct Query
  145. object result = 0;
  146. conn.Open ();
  147. result = cmd.ExecuteScalar ();
  148. Assert.AreEqual (4, (int)result, "#3 Query Result returned is incorrect");
  149. cmd.CommandText = "select id , type_bit from numeric_family order by id asc" ;
  150. result = Convert.ToInt32 (cmd.ExecuteScalar ());
  151. Assert.AreEqual (1, result,
  152. "#4 ExecuteScalar Should return (1,1) the result set" );
  153. cmd.CommandText = "select id from numeric_family where id=-1";
  154. result = cmd.ExecuteScalar ();
  155. Assert.IsNull (result, "#5 Null should be returned if result set is empty");
  156. // Check SqlException is thrown for Invalid Query
  157. cmd.CommandText = "select count* from numeric_family";
  158. try {
  159. result = cmd.ExecuteScalar ();
  160. Assert.Fail ("#6 InCorrect Query should cause an SqlException");
  161. }catch (AssertionException e) {
  162. throw e;
  163. }catch (Exception e) {
  164. Assert.AreEqual (typeof(SqlException), e.GetType(),
  165. "#7 Incorrect Exception : " + e.StackTrace);
  166. }
  167. // Parameterized stored procedure calls
  168. int int_value = 20;
  169. string string_value = "output value changed";
  170. string return_value = "first column of first rowset";
  171. cmd.CommandText =
  172. "create procedure #tmp_executescalar_outparams "+
  173. " (@p1 int, @p2 int out, @p3 varchar(200) out) "+
  174. "as " +
  175. "select '" + return_value + "' as 'col1', @p1 as 'col2' "+
  176. "set @p2 = @p2 * 2 "+
  177. "set @p3 = N'" + string_value + "' "+
  178. "select 'second rowset' as 'col1', 2 as 'col2' "+
  179. "return 1";
  180. cmd.CommandType = CommandType.Text;
  181. cmd.ExecuteNonQuery ();
  182. cmd.CommandText = "#tmp_executescalar_outparams";
  183. cmd.CommandType = CommandType.StoredProcedure;
  184. SqlParameter p1 = new SqlParameter ();
  185. p1.ParameterName = "@p1";
  186. p1.Direction = ParameterDirection.Input;
  187. p1.DbType = DbType.Int32;
  188. p1.Value = int_value;
  189. cmd.Parameters.Add (p1);
  190. SqlParameter p2 = new SqlParameter ();
  191. p2.ParameterName = "@p2";
  192. p2.Direction = ParameterDirection.InputOutput;
  193. p2.DbType = DbType.Int32;
  194. p2.Value = int_value;
  195. cmd.Parameters.Add (p2);
  196. SqlParameter p3 = new SqlParameter ();
  197. p3.ParameterName = "@p3";
  198. p3.Direction = ParameterDirection.Output;
  199. p3.DbType = DbType.String;
  200. p3.Size = 200;
  201. cmd.Parameters.Add (p3);
  202. result = cmd.ExecuteScalar ();
  203. Assert.AreEqual (return_value, result, "#8 ExecuteScalar Should return 'first column of first rowset'");
  204. Assert.AreEqual (int_value * 2, p2.Value, "#9 ExecuteScalar should fill the parameter collection with the outputted values");
  205. Assert.AreEqual (string_value, p3.Value, "#10 ExecuteScalar should fill the parameter collection with the outputted values");
  206. p3.Size = 0;
  207. p3.Value = null;
  208. try {
  209. cmd.ExecuteScalar ();
  210. Assert.Fail ("#11 Query should throw System.InvalidOperationException due to size = 0 and value = null");
  211. }
  212. catch (AssertionException e) {
  213. throw e;
  214. }
  215. catch (Exception e) {
  216. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  217. "#12 Incorrect Exception : " + e.StackTrace);
  218. }
  219. conn.Close ();
  220. }
  221. [Test]
  222. public void ExecuteNonQuery ()
  223. {
  224. conn = new SqlConnection (connectionString);
  225. cmd = new SqlCommand ("", conn);
  226. int result = 0;
  227. // Test for exceptions
  228. // Test exception is thrown if connection is closed
  229. cmd.CommandText = "Select id from numeric_family where id=1";
  230. try {
  231. cmd.ExecuteNonQuery ();
  232. Assert.Fail ("#1 Connextion shud be open");
  233. }catch (AssertionException e) {
  234. throw e;
  235. }catch (Exception e) {
  236. #if NET_2_0
  237. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  238. "#2 Incorrect Exception : " + e);
  239. #else
  240. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  241. "#2 Incorrect Exception : " + e);
  242. #endif
  243. }
  244. // Test Exception is thrown if Query is incorrect
  245. conn.Open ();
  246. cmd.CommandText = "Select id1 from numeric_family";
  247. try {
  248. cmd.ExecuteNonQuery ();
  249. Assert.Fail ("#1 invalid Query");
  250. }catch (AssertionException e) {
  251. throw e;
  252. }catch (Exception e) {
  253. Assert.AreEqual (typeof(SqlException), e.GetType(),
  254. "#2 Incorrect Exception : " + e);
  255. }
  256. // Test Select/Insert/Update/Delete Statements
  257. SqlTransaction trans = conn.BeginTransaction ();
  258. cmd.Transaction = trans;
  259. try {
  260. cmd.CommandText = "Select id from numeric_family where id=1";
  261. result = cmd.ExecuteNonQuery ();
  262. Assert.AreEqual (-1, result, "#1");
  263. cmd.CommandText = "Insert into numeric_family (id,type_int) values (100,200)";
  264. result = cmd.ExecuteNonQuery ();
  265. Assert.AreEqual (1, result, "#2 One row shud be inserted");
  266. cmd.CommandText = "Update numeric_family set type_int=300 where id=100";
  267. result = cmd.ExecuteNonQuery ();
  268. Assert.AreEqual (1, result, "#3 One row shud be updated");
  269. // Test Batch Commands
  270. cmd.CommandText = "Select id from numeric_family where id=1;";
  271. cmd.CommandText += "update numeric_family set type_int=10 where id=1000";
  272. cmd.CommandText += "update numeric_family set type_int=10 where id=100";
  273. result = cmd.ExecuteNonQuery ();
  274. Assert.AreEqual (1, result, "#4 One row shud be updated");
  275. cmd.CommandText = "Delete from numeric_family where id=100";
  276. result = cmd.ExecuteNonQuery ();
  277. Assert.AreEqual (1, result, "#5 One row shud be deleted");
  278. }finally {
  279. trans.Rollback ();
  280. }
  281. // Parameterized stored procedure calls
  282. int int_value = 20;
  283. string string_value = "output value changed";
  284. cmd.CommandText =
  285. "create procedure #tmp_executescalar_outparams " +
  286. " (@p1 int, @p2 int out, @p3 varchar(200) out) " +
  287. "as " +
  288. "select 'test' as 'col1', @p1 as 'col2' " +
  289. "set @p2 = @p2 * 2 " +
  290. "set @p3 = N'" + string_value + "' " +
  291. "select 'second rowset' as 'col1', 2 as 'col2' " +
  292. "return 1";
  293. cmd.CommandType = CommandType.Text;
  294. cmd.ExecuteNonQuery ();
  295. cmd.CommandText = "#tmp_executescalar_outparams";
  296. cmd.CommandType = CommandType.StoredProcedure;
  297. SqlParameter p1 = new SqlParameter ();
  298. p1.ParameterName = "@p1";
  299. p1.Direction = ParameterDirection.Input;
  300. p1.DbType = DbType.Int32;
  301. p1.Value = int_value;
  302. cmd.Parameters.Add (p1);
  303. SqlParameter p2 = new SqlParameter ();
  304. p2.ParameterName = "@p2";
  305. p2.Direction = ParameterDirection.InputOutput;
  306. p2.DbType = DbType.Int32;
  307. p2.Value = int_value;
  308. cmd.Parameters.Add (p2);
  309. SqlParameter p3 = new SqlParameter ();
  310. p3.ParameterName = "@p3";
  311. p3.Direction = ParameterDirection.Output;
  312. p3.DbType = DbType.String;
  313. p3.Size = 200;
  314. cmd.Parameters.Add (p3);
  315. cmd.ExecuteNonQuery ();
  316. Assert.AreEqual (int_value * 2, p2.Value, "#6 ExecuteNonQuery should fill the parameter collection with the outputted values");
  317. Assert.AreEqual (string_value, p3.Value, "#7 ExecuteNonQuery should fill the parameter collection with the outputted values");
  318. }
  319. [Test]
  320. public void ExecuteReaderTest ()
  321. {
  322. //SqlDataReader reader = null;
  323. conn = new SqlConnection (connectionString);
  324. // Test exception is thrown if conn is closed
  325. cmd = new SqlCommand ("Select count(*) from numeric_family");
  326. try {
  327. /*reader = */cmd.ExecuteReader ();
  328. }catch (AssertionException e) {
  329. throw e;
  330. }catch (Exception e) {
  331. #if NET_2_0
  332. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  333. "#1 Incorrect Exception");
  334. #else
  335. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  336. "#1 Incorrect Exception");
  337. #endif
  338. }
  339. conn.Open ();
  340. // Test exception is thrown for Invalid Query
  341. cmd = new SqlCommand ("InvalidQuery", conn);
  342. try {
  343. /*reader = */cmd.ExecuteReader ();
  344. Assert.Fail ("#1 Exception shud be thrown");
  345. }catch (AssertionException e) {
  346. throw e;
  347. }catch (Exception e) {
  348. Assert.AreEqual (typeof(SqlException), e.GetType (),
  349. "#2 Incorrect Exception : " + e);
  350. }
  351. // NOTE
  352. // Test SqlException is thrown if a row is locked
  353. // should lock a particular row and then modify it
  354. /*
  355. */
  356. // Test Connection cannot be modified when reader is in use
  357. // NOTE : msdotnet contradicts documented behavior
  358. /*
  359. cmd.CommandText = "select * from numeric_family where id=1";
  360. reader = cmd.ExecuteReader ();
  361. reader.Read ();
  362. conn.Close (); // valid operation
  363. conn = new SqlConnection (connectionString);
  364. */
  365. /*
  366. // NOTE msdotnet contradcits documented behavior
  367. // If the above testcase fails, then this shud be tested
  368. // Test connection can be modified once reader is closed
  369. conn.Close ();
  370. reader.Close ();
  371. conn = new SqlConnection (connectionString); // valid operation
  372. */
  373. }
  374. [Test]
  375. public void ExecuteReaderCommandBehaviorTest ()
  376. {
  377. // Test for command behaviors
  378. DataTable schemaTable = null;
  379. SqlDataReader reader = null;
  380. conn = new SqlConnection (connectionString);
  381. conn.Open ();
  382. cmd = new SqlCommand ("", conn);
  383. cmd.CommandText = "Select id from numeric_family where id <=4 order by id asc;";
  384. cmd.CommandText += "Select type_bit from numeric_family where id <=4 order by id asc";
  385. // Test for default command behavior
  386. reader = cmd.ExecuteReader ();
  387. int rows = 0;
  388. int results = 0;
  389. do {
  390. while (reader.Read ())
  391. rows++ ;
  392. Assert.AreEqual (4, rows, "#1 Multiple rows shud be returned");
  393. results++;
  394. rows = 0;
  395. }while (reader.NextResult());
  396. Assert.AreEqual (2, results, "#2 Multiple result sets shud be returned");
  397. reader.Close ();
  398. // Test if closing reader, closes the connection
  399. reader = cmd.ExecuteReader (CommandBehavior.CloseConnection);
  400. reader.Close ();
  401. Assert.AreEqual (ConnectionState.Closed, conn.State,
  402. "#3 Command Behavior is not followed");
  403. conn.Open();
  404. // Test if row info and primary Key info is returned
  405. reader = cmd.ExecuteReader (CommandBehavior.KeyInfo);
  406. schemaTable = reader.GetSchemaTable ();
  407. Assert.IsTrue(reader.HasRows, "#4 Data Rows shud also be returned");
  408. Assert.IsTrue ((bool)schemaTable.Rows[0]["IsKey"],
  409. "#5 Primary Key info shud be returned");
  410. reader.Close ();
  411. // Test only column information is returned
  412. reader = cmd.ExecuteReader (CommandBehavior.SchemaOnly);
  413. schemaTable = reader.GetSchemaTable ();
  414. Assert.IsFalse (reader.HasRows, "#6 row data shud not be returned");
  415. Assert.AreEqual(DBNull.Value, schemaTable.Rows[0]["IsKey"],
  416. "#7 Primary Key info shud not be returned");
  417. Assert.AreEqual ("id", schemaTable.Rows[0]["ColumnName"],
  418. "#8 Schema Data is Incorrect");
  419. reader.Close ();
  420. // Test only one result set (first) is returned
  421. reader = cmd.ExecuteReader (CommandBehavior.SingleResult);
  422. schemaTable = reader.GetSchemaTable ();
  423. Assert.IsFalse (reader.NextResult(),
  424. "#9 Only one result set shud be returned");
  425. Assert.AreEqual ("id", schemaTable.Rows[0]["ColumnName"],
  426. "#10 The result set returned shud be the first result set");
  427. reader.Close ();
  428. // Test only one row is returned for all result sets
  429. // msdotnet doesnt work correctly.. returns only one result set
  430. reader = cmd.ExecuteReader (CommandBehavior.SingleRow);
  431. rows=0;
  432. results=0;
  433. do {
  434. while (reader.Read ())
  435. rows++ ;
  436. Assert.AreEqual (1, rows, "#11 Only one row shud be returned");
  437. results++;
  438. rows = 0;
  439. }while (reader.NextResult());
  440. // NOTE msdotnet contradicts documented behavior.
  441. // Multiple result sets shud be returned , and in this case : 2
  442. //Assert.AreEqual (2, results, "# Multiple result sets shud be returned");
  443. Assert.AreEqual (2, results, "#12 Multiple result sets shud be returned");
  444. reader.Close ();
  445. }
  446. [Test]
  447. public void PrepareTest_CheckValidStatement ()
  448. {
  449. cmd = new SqlCommand ();
  450. conn = new SqlConnection (connectionString);
  451. conn.Open ();
  452. cmd.CommandText = "Select id from numeric_family where id=@ID" ;
  453. cmd.Connection = conn ;
  454. // Test if Parameters are correctly populated
  455. cmd.Parameters.Clear ();
  456. cmd.Parameters.Add ("@ID", SqlDbType.TinyInt);
  457. cmd.Parameters["@ID"].Value = 2 ;
  458. cmd.Prepare ();
  459. Assert.AreEqual (2, cmd.ExecuteScalar (), "#3 Prepared Stmt not working");
  460. cmd.Parameters[0].Value = 3;
  461. Assert.AreEqual (3, cmd.ExecuteScalar (), "#4 Prep Stmt not working");
  462. conn.Close ();
  463. }
  464. [Test]
  465. public void PrepareTest ()
  466. {
  467. cmd = new SqlCommand ();
  468. conn = new SqlConnection (connectionString);
  469. conn.Open ();
  470. cmd.CommandText = "Select id from numeric_family where id=@ID" ;
  471. cmd.Connection = conn ;
  472. // Test InvalidOperation Exception is thrown if Parameter Type
  473. // is not explicitly set
  474. #if NET_2_0
  475. cmd.Parameters.AddWithValue ("@ID", 2);
  476. #else
  477. cmd.Parameters.Add ("@ID", 2);
  478. #endif
  479. try {
  480. cmd.Prepare ();
  481. Assert.Fail ("#1 Parameter Type shud be explicitly Set");
  482. }catch (AssertionException e) {
  483. throw e;
  484. }catch (Exception e) {
  485. Assert.AreEqual (typeof(InvalidOperationException), e.GetType (),
  486. "#2 Incorrect Exception : " + e.StackTrace);
  487. }
  488. // Test Exception is thrown for variable size data if precision/scale
  489. // is not set
  490. cmd.CommandText = "select type_varchar from string_family where type_varchar=@p1";
  491. cmd.Parameters.Clear ();
  492. cmd.Parameters.Add ("@p1", SqlDbType.VarChar);
  493. cmd.Parameters["@p1"].Value = "afasasadadada";
  494. try {
  495. cmd.Prepare ();
  496. Assert.Fail ("#5 Exception shud be thrown");
  497. }catch (AssertionException e) {
  498. throw e;
  499. }catch (Exception e) {
  500. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  501. "#6 Incorrect Exception " + e.StackTrace);
  502. }
  503. // Test Exception is not thrown for Stored Procs
  504. try {
  505. cmd.CommandType = CommandType.StoredProcedure;
  506. cmd.CommandText = "ABFSDSFSF" ;
  507. cmd.Prepare ();
  508. }catch {
  509. Assert.Fail ("#7 Exception shud not be thrown for Stored Procs");
  510. }
  511. cmd.CommandType = CommandType.Text;
  512. conn.Close ();
  513. //Test InvalidOperation Exception is thrown if connection is not set
  514. cmd.Connection = null;
  515. try {
  516. cmd.Prepare ();
  517. #if NET_2_0
  518. Assert.Fail ("#8 NullReferenceException should be thrown");
  519. #else
  520. Assert.Fail ("#8 InvalidOperation Exception should be thrown");
  521. #endif
  522. }
  523. catch (AssertionException e) {
  524. throw e;
  525. }catch (Exception e) {
  526. #if NET_2_0
  527. Assert.AreEqual (typeof (NullReferenceException), e.GetType (),
  528. "#9 Incorrect Exception : " + e.StackTrace);
  529. #else
  530. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  531. "#9 Incorrect Exception : " + e.StackTrace);
  532. #endif
  533. }
  534. //Test InvalidOperation Exception is thrown if connection is closed
  535. cmd.Connection = conn ;
  536. try{
  537. cmd.Prepare ();
  538. Assert.Fail ("#4 InvalidOperation Exception shud be thrown");
  539. }catch (AssertionException e) {
  540. throw e;
  541. }catch (Exception e) {
  542. #if NET_2_0
  543. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  544. "Incorrect Exception : " + e.StackTrace);
  545. #else
  546. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  547. "Incorrect Exception : " + e.StackTrace);
  548. #endif
  549. }
  550. }
  551. [Test]
  552. public void ResetTimeOut ()
  553. {
  554. SqlCommand cmd = new SqlCommand ();
  555. cmd.CommandTimeout = 50 ;
  556. Assert.AreEqual ( cmd.CommandTimeout, 50,
  557. "#1 CommandTimeout should be modfiable");
  558. cmd.ResetCommandTimeout ();
  559. Assert.AreEqual (cmd.CommandTimeout, 30,
  560. "#2 Reset Should set the Timeout to default value");
  561. }
  562. [Test]
  563. [ExpectedException (typeof(ArgumentException))]
  564. public void CommandTimeout ()
  565. {
  566. cmd = new SqlCommand ();
  567. cmd.CommandTimeout = 10;
  568. Assert.AreEqual (10, cmd.CommandTimeout, "#1");
  569. cmd.CommandTimeout = -1;
  570. }
  571. [Test]
  572. #if NET_2_0
  573. [ExpectedException (typeof(ArgumentOutOfRangeException))]
  574. #else
  575. [ExpectedException (typeof(ArgumentException))]
  576. #endif
  577. public void CommandTypeTest ()
  578. {
  579. cmd = new SqlCommand ();
  580. Assert.AreEqual (CommandType.Text ,cmd.CommandType,
  581. "Default CommandType is text");
  582. cmd.CommandType = (CommandType)(-1);
  583. }
  584. [Test]
  585. [Ignore ("msdotnet contradicts documented behavior")]
  586. [ExpectedException (typeof(InvalidOperationException))]
  587. public void ConnectionTest ()
  588. {
  589. SqlTransaction trans = null;
  590. try {
  591. conn = new SqlConnection (connectionString);
  592. conn.Open ();
  593. trans = conn.BeginTransaction ();
  594. cmd = new SqlCommand ("", conn,trans);
  595. cmd.CommandText = "Select id from numeric_family where id=1";
  596. cmd.Connection = new SqlConnection ();
  597. }finally {
  598. trans.Rollback();
  599. conn.Close ();
  600. }
  601. }
  602. [Test]
  603. public void TransactionTest ()
  604. {
  605. conn = new SqlConnection (connectionString);
  606. cmd = new SqlCommand ("", conn);
  607. Assert.IsNull (cmd.Transaction, "#1 Default value is null");
  608. SqlConnection conn1 = new SqlConnection (connectionString);
  609. conn1.Open ();
  610. SqlTransaction trans1 = conn1.BeginTransaction ();
  611. cmd.Transaction = trans1 ;
  612. try {
  613. cmd.ExecuteNonQuery ();
  614. Assert.Fail ("#2 Connection cannot be different");
  615. }catch (Exception e) {
  616. #if NET_2_0
  617. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  618. "#3 Incorrect Exception : " + e);
  619. #else
  620. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  621. "#3 Incorrect Exception : " + e);
  622. #endif
  623. }finally {
  624. conn1.Close ();
  625. conn.Close ();
  626. }
  627. }
  628. // Need to add more tests
  629. [Test]
  630. #if NET_2_0
  631. [ExpectedException (typeof(ArgumentOutOfRangeException))]
  632. #else
  633. [ExpectedException (typeof(ArgumentException))]
  634. #endif
  635. public void UpdatedRowSourceTest ()
  636. {
  637. cmd = new SqlCommand ();
  638. Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource,
  639. "#1 Default value is both");
  640. cmd.UpdatedRowSource = UpdateRowSource.None;
  641. Assert.AreEqual (UpdateRowSource.None, cmd.UpdatedRowSource,
  642. "#2");
  643. cmd.UpdatedRowSource = (UpdateRowSource) (-1);
  644. }
  645. [Test]
  646. public void ExecuteNonQueryTempProcedureTest () {
  647. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  648. try {
  649. ConnectionManager.Singleton.OpenConnection ();
  650. // create temp sp here, should normally be created in Setup of test
  651. // case, but cannot be done right now because of ug #68978
  652. DBHelper.ExecuteNonQuery (conn, CREATE_TMP_SP_TEMP_INSERT_PERSON);
  653. SqlCommand cmd = new SqlCommand();
  654. cmd.Connection = conn;
  655. cmd.CommandText = "#sp_temp_insert_employee";
  656. cmd.CommandType = CommandType.StoredProcedure;
  657. Object TestPar = "test";
  658. cmd.Parameters.Add("@fname", SqlDbType.VarChar);
  659. cmd.Parameters ["@fname"].Value = TestPar;
  660. Assert.AreEqual(1,cmd.ExecuteNonQuery());
  661. } finally {
  662. DBHelper.ExecuteNonQuery (conn, DROP_TMP_SP_TEMP_INSERT_PERSON);
  663. DBHelper.ExecuteSimpleSP (conn, "sp_clean_person_table");
  664. ConnectionManager.Singleton.CloseConnection ();
  665. }
  666. }
  667. // Test for bug #76778
  668. // Test for a case, when query size is greater than the block size
  669. [Test]
  670. public void LongQueryTest ()
  671. {
  672. SqlConnection conn = new SqlConnection (
  673. connectionString + ";Pooling=false");
  674. using (conn) {
  675. conn.Open ();
  676. SqlCommand cmd = conn.CreateCommand ();
  677. String value = new String ('a', 10000);
  678. cmd.CommandText = String.Format ("Select '{0}'", value);
  679. cmd.ExecuteNonQuery ();
  680. }
  681. }
  682. // Test for bug #76778
  683. // To make sure RPC (when implemented) works ok..
  684. [Test]
  685. public void LongStoredProcTest()
  686. {
  687. SqlConnection conn = new SqlConnection (
  688. connectionString + ";Pooling=false");
  689. using (conn) {
  690. conn.Open ();
  691. /*int size = conn.PacketSize ; */
  692. SqlCommand cmd = conn.CreateCommand ();
  693. // create a temp stored proc ..
  694. cmd.CommandText = "Create Procedure #sp_tmp_long_params ";
  695. cmd.CommandText += "@p1 nvarchar (4000), ";
  696. cmd.CommandText += "@p2 nvarchar (4000), ";
  697. cmd.CommandText += "@p3 nvarchar (4000), ";
  698. cmd.CommandText += "@p4 nvarchar (4000) out ";
  699. cmd.CommandText += "As ";
  700. cmd.CommandText += "Begin ";
  701. cmd.CommandText += "Set @p4 = N'Hello' ";
  702. cmd.CommandText += "Return 2 ";
  703. cmd.CommandText += "End";
  704. cmd.ExecuteNonQuery ();
  705. //execute the proc
  706. cmd.CommandType = CommandType.StoredProcedure;
  707. cmd.CommandText = "#sp_tmp_long_params";
  708. String value = new String ('a', 4000);
  709. SqlParameter p1 = new SqlParameter ("@p1",
  710. SqlDbType.NVarChar,4000);
  711. p1.Value = value;
  712. SqlParameter p2 = new SqlParameter ("@p2",
  713. SqlDbType.NVarChar,4000);
  714. p2.Value = value;
  715. SqlParameter p3 = new SqlParameter ("@p3",
  716. SqlDbType.NVarChar,4000);
  717. p3.Value = value;
  718. SqlParameter p4 = new SqlParameter ("@p4",
  719. SqlDbType.NVarChar,4000);
  720. p4.Direction = ParameterDirection.Output;
  721. // for now, name shud be @RETURN_VALUE
  722. // can be changed once RPC is implemented
  723. SqlParameter p5 = new SqlParameter ("@RETURN_VALUE", SqlDbType.Int);
  724. p5.Direction = ParameterDirection.ReturnValue ;
  725. cmd.Parameters.Add (p1);
  726. cmd.Parameters.Add (p2);
  727. cmd.Parameters.Add (p3);
  728. cmd.Parameters.Add (p4);
  729. cmd.Parameters.Add (p5);
  730. cmd.ExecuteNonQuery ();
  731. Assert.AreEqual ("Hello", p4.Value, "#1");
  732. Assert.AreEqual (2, p5.Value, "#2");
  733. }
  734. }
  735. // Test for bug #76880
  736. [Test]
  737. public void DateTimeParameterTest ()
  738. {
  739. SqlConnection conn = new SqlConnection (connectionString);
  740. using (conn) {
  741. conn.Open ();
  742. SqlCommand cmd = conn.CreateCommand ();
  743. cmd.CommandText = "select * from datetime_family where type_datetime=@p1";
  744. cmd.Parameters.Add ("@p1", SqlDbType.DateTime).Value= "10-10-2005";
  745. // shudnt cause and exception
  746. SqlDataReader rdr = cmd.ExecuteReader ();
  747. rdr.Close ();
  748. }
  749. }
  750. /**
  751. * Verifies whether an enum value is converted to a numeric value when
  752. * used as value for a numeric parameter (bug #66630)
  753. */
  754. [Test]
  755. public void EnumParameterTest() {
  756. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  757. try {
  758. ConnectionManager.Singleton.OpenConnection ();
  759. // create temp sp here, should normally be created in Setup of test
  760. // case, but cannot be done right now because of ug #68978
  761. DBHelper.ExecuteNonQuery (conn, "CREATE PROCEDURE #Bug66630 ("
  762. + "@Status smallint = 7"
  763. + ")"
  764. + "AS" + Environment.NewLine
  765. + "BEGIN" + Environment.NewLine
  766. + "SELECT CAST(5 AS int), @Status" + Environment.NewLine
  767. + "END");
  768. SqlCommand cmd = new SqlCommand("#Bug66630", conn);
  769. cmd.CommandType = CommandType.StoredProcedure;
  770. cmd.Parameters.Add("@Status", SqlDbType.Int).Value = Status.Error;
  771. using (SqlDataReader dr = cmd.ExecuteReader()) {
  772. // one record should be returned
  773. Assert.IsTrue(dr.Read(), "EnumParameterTest#1");
  774. // we should get two field in the result
  775. Assert.AreEqual(2, dr.FieldCount, "EnumParameterTest#2");
  776. // field 1
  777. Assert.AreEqual("int", dr.GetDataTypeName(0), "EnumParameterTest#3");
  778. Assert.AreEqual(5, dr.GetInt32(0), "EnumParameterTest#4");
  779. // field 2
  780. Assert.AreEqual("smallint", dr.GetDataTypeName(1), "EnumParameterTest#5");
  781. Assert.AreEqual((short) Status.Error, dr.GetInt16(1), "EnumParameterTest#6");
  782. // only one record should be returned
  783. Assert.IsFalse(dr.Read(), "EnumParameterTest#7");
  784. }
  785. } finally {
  786. DBHelper.ExecuteNonQuery (conn, "if exists (select name from sysobjects " +
  787. " where name like '#temp_Bug66630' and type like 'P') " +
  788. " drop procedure #temp_Bug66630; ");
  789. ConnectionManager.Singleton.CloseConnection ();
  790. }
  791. }
  792. /**
  793. * The below test does not need a connection but since the setup opens
  794. * the connection i will need to close it
  795. */
  796. [Test]
  797. public void CloneTest() {
  798. ConnectionManager.Singleton.OpenConnection ();
  799. SqlCommand cmd = new SqlCommand();
  800. cmd.Connection = null;
  801. cmd.CommandText = "sp_insert";
  802. cmd.CommandType = CommandType.StoredProcedure;
  803. Object TestPar = DBNull.Value;
  804. cmd.Parameters.Add("@TestPar1", SqlDbType.Int);
  805. cmd.Parameters["@TestPar1"].Value = TestPar;
  806. #if NET_2_0
  807. cmd.Parameters.AddWithValue ("@BirthDate", DateTime.Now);
  808. #else
  809. cmd.Parameters.Add ("@BirthDate", DateTime.Now);
  810. #endif
  811. cmd.DesignTimeVisible = true;
  812. cmd.CommandTimeout = 100;
  813. Object clone1 = ((ICloneable)(cmd)).Clone();
  814. SqlCommand cmd1 = (SqlCommand) clone1;
  815. Assert.AreEqual(2, cmd1.Parameters.Count);
  816. Assert.AreEqual(100, cmd1.CommandTimeout);
  817. #if NET_2_0
  818. cmd1.Parameters.AddWithValue ("@test", DateTime.Now);
  819. #else
  820. cmd1.Parameters.Add ("@test", DateTime.Now);
  821. #endif
  822. // to check that it is deep copy and not a shallow copy of the
  823. // parameter collection
  824. Assert.AreEqual(3, cmd1.Parameters.Count);
  825. Assert.AreEqual(2, cmd.Parameters.Count);
  826. }
  827. [Test]
  828. public void StoredProc_NoParameterTest ()
  829. {
  830. string query = "create procedure #tmp_sp_proc as begin";
  831. query += " select 'data' end";
  832. SqlConnection conn = new SqlConnection (connectionString);
  833. SqlCommand cmd = conn.CreateCommand ();
  834. cmd.CommandText = query ;
  835. conn.Open ();
  836. cmd.ExecuteNonQuery ();
  837. cmd.CommandType = CommandType.StoredProcedure;
  838. cmd.CommandText = "#tmp_sp_proc";
  839. using (SqlDataReader reader = cmd.ExecuteReader()) {
  840. if (reader.Read ())
  841. Assert.AreEqual ("data", reader.GetString(0),"#1");
  842. else
  843. Assert.Fail ("#2 Select shud return data");
  844. }
  845. conn.Close ();
  846. }
  847. [Test]
  848. public void StoredProc_ParameterTest ()
  849. {
  850. string create_query = CREATE_TMP_SP_PARAM_TEST;
  851. string drop_query = DROP_TMP_SP_PARAM_TEST;
  852. SqlConnection conn = new SqlConnection (connectionString);
  853. conn.Open ();
  854. SqlCommand cmd = conn.CreateCommand ();
  855. int label = 0 ;
  856. string error = "";
  857. while (label != -1) {
  858. try {
  859. switch (label) {
  860. case 0 :
  861. // Test BigInt Param
  862. DBHelper.ExecuteNonQuery (conn,
  863. String.Format(create_query, "bigint"));
  864. rpc_helper_function (cmd, SqlDbType.BigInt, 0, Int64.MaxValue);
  865. rpc_helper_function (cmd, SqlDbType.BigInt, 0, Int64.MinValue);
  866. break;
  867. case 1 :
  868. // Test Binary Param
  869. DBHelper.ExecuteNonQuery (conn,
  870. String.Format(create_query, "binary(5)"));
  871. //rpc_helper_function (cmd, SqlDbType.Binary, 0, new byte[] {});
  872. rpc_helper_function (cmd, SqlDbType.Binary, 5, new byte[] {1,2,3,4,5});
  873. break;
  874. case 2 :
  875. // Test Bit Param
  876. DBHelper.ExecuteNonQuery (conn,
  877. String.Format(create_query, "bit"));
  878. rpc_helper_function (cmd, SqlDbType.Bit, 0, true);
  879. rpc_helper_function (cmd, SqlDbType.Bit, 0, false);
  880. break;
  881. case 3 :
  882. // Testing Char
  883. DBHelper.ExecuteNonQuery (conn,
  884. String.Format(create_query, "char(10)"));
  885. rpc_helper_function (cmd, SqlDbType.Char, 10, "characters");
  886. /*
  887. rpc_helper_function (cmd, SqlDbType.Char, 10, "");
  888. rpc_helper_function (cmd, SqlDbType.Char, 10, null);
  889. */
  890. break;
  891. case 4 :
  892. // Testing DateTime
  893. DBHelper.ExecuteNonQuery (conn,
  894. String.Format(create_query, "datetime"));
  895. rpc_helper_function (cmd, SqlDbType.DateTime, 0, "2079-06-06 23:59:00");
  896. /*
  897. rpc_helper_function (cmd, SqlDbType.DateTime, 10, "");
  898. rpc_helper_function (cmd, SqlDbType.DateTime, 10, null);
  899. */
  900. break;
  901. case 5 :
  902. // Test Decimal Param
  903. DBHelper.ExecuteNonQuery (conn,
  904. String.Format(create_query,"decimal(10,2)"));
  905. /*
  906. rpc_helper_function (cmd, SqlDbType.Decimal, 0, 10.01);
  907. rpc_helper_function (cmd, SqlDbType.Decimal, 0, -10.01);
  908. */
  909. break;
  910. case 6 :
  911. // Test Float Param
  912. DBHelper.ExecuteNonQuery (conn,
  913. String.Format(create_query,"float"));
  914. rpc_helper_function (cmd, SqlDbType.Float, 0, 10.0);
  915. rpc_helper_function (cmd, SqlDbType.Float, 0, 0);
  916. /*
  917. rpc_helper_function (cmd, SqlDbType.Float, 0, null);
  918. */
  919. break;
  920. case 7 :
  921. // Testing Image
  922. /* NOT WORKING
  923. DBHelper.ExecuteNonQuery (conn,
  924. String.Format(create_query, "image"));
  925. rpc_helper_function (cmd, SqlDbType.Image, 0, );
  926. rpc_helper_function (cmd, SqlDbType.Image, 0, );
  927. rpc_helper_function (cmd, SqlDbType.Image, 0, );
  928. /* NOT WORKING*/
  929. break;
  930. case 8 :
  931. // Test Integer Param
  932. DBHelper.ExecuteNonQuery (conn,
  933. String.Format(create_query,"int"));
  934. rpc_helper_function (cmd, SqlDbType.Int, 0, 10);
  935. /*
  936. rpc_helper_function (cmd, SqlDbType.Int, 0, null);
  937. */
  938. break;
  939. case 9 :
  940. // Test Money Param
  941. DBHelper.ExecuteNonQuery (conn,
  942. String.Format(create_query,"money"));
  943. /*
  944. rpc_helper_function (cmd, SqlDbType.Money, 0, 10.0);
  945. rpc_helper_function (cmd, SqlDbType.Money, 0, null);
  946. */
  947. break;
  948. case 23 :
  949. // Test NChar Param
  950. DBHelper.ExecuteNonQuery (conn,
  951. String.Format(create_query,"nchar(10)"));
  952. /*
  953. rpc_helper_function (cmd, SqlDbType.NChar, 10, "nchar");
  954. rpc_helper_function (cmd, SqlDbType.NChar, 10, "");
  955. rpc_helper_function (cmd, SqlDbType.NChar, 10, null);
  956. */
  957. break;
  958. case 10 :
  959. // Test NText Param
  960. DBHelper.ExecuteNonQuery (conn,
  961. String.Format(create_query,"ntext"));
  962. /*
  963. rpc_helper_function (cmd, SqlDbType.NText, 0, "ntext");
  964. rpc_helper_function (cmd, SqlDbType.NText, 0, "");
  965. rpc_helper_function (cmd, SqlDbType.NText, 0, null);
  966. */
  967. break;
  968. case 11 :
  969. // Test NVarChar Param
  970. DBHelper.ExecuteNonQuery (conn,
  971. String.Format(create_query,"nvarchar(10)"));
  972. rpc_helper_function (cmd, SqlDbType.NVarChar, 10, "nvarchar");
  973. rpc_helper_function (cmd, SqlDbType.NVarChar, 10, "");
  974. //rpc_helper_function (cmd, SqlDbType.NVarChar, 10, null);
  975. break;
  976. case 12 :
  977. // Test Real Param
  978. DBHelper.ExecuteNonQuery (conn,
  979. String.Format(create_query,"real"));
  980. rpc_helper_function (cmd, SqlDbType.Real, 0, 10.0);
  981. //rpc_helper_function (cmd, SqlDbType.Real, 0, null);
  982. break;
  983. case 13 :
  984. // Test SmallDateTime Param
  985. DBHelper.ExecuteNonQuery (conn,
  986. String.Format(create_query,"smalldatetime"));
  987. rpc_helper_function (cmd, SqlDbType.SmallDateTime, 0, "6/6/2079 11:59:00 PM");
  988. /*
  989. rpc_helper_function (cmd, SqlDbType.SmallDateTime, 0, "");
  990. rpc_helper_function (cmd, SqlDbType.SmallDateTime, 0, null);
  991. */
  992. break;
  993. case 14 :
  994. // Test SmallInt Param
  995. DBHelper.ExecuteNonQuery (conn,
  996. String.Format(create_query,"smallint"));
  997. rpc_helper_function (cmd, SqlDbType.SmallInt, 0, 10);
  998. rpc_helper_function (cmd, SqlDbType.SmallInt, 0, -10);
  999. //rpc_helper_function (cmd, SqlDbType.SmallInt, 0, null);
  1000. break;
  1001. case 15 :
  1002. // Test SmallMoney Param
  1003. DBHelper.ExecuteNonQuery (conn,
  1004. String.Format(create_query,"smallmoney"));
  1005. /*
  1006. rpc_helper_function (cmd, SqlDbType.SmallMoney, 0, 10.0);
  1007. rpc_helper_function (cmd, SqlDbType.SmallMoney, 0, -10.0);
  1008. rpc_helper_function (cmd, SqlDbType.SmallMoney, 0, null);
  1009. */
  1010. break;
  1011. case 16 :
  1012. // Test Text Param
  1013. DBHelper.ExecuteNonQuery (conn,
  1014. String.Format(create_query,"text"));
  1015. /*
  1016. rpc_helper_function (cmd, SqlDbType.Text, 0, "text");
  1017. rpc_helper_function (cmd, SqlDbType.Text, 0, "");
  1018. rpc_helper_function (cmd, SqlDbType.Text, 0, null);
  1019. */
  1020. break;
  1021. case 17 :
  1022. // Test TimeStamp Param
  1023. /* NOT WORKING
  1024. DBHelper.ExecuteNonQuery (conn,
  1025. String.Format(create_query,"timestamp"));
  1026. rpc_helper_function (cmd, SqlDbType.TimeStamp, 0, "");
  1027. rpc_helper_function (cmd, SqlDbType.TimeStamp, 0, "");
  1028. rpc_helper_function (cmd, SqlDbType.TimeStamp, 0, null);
  1029. */
  1030. break;
  1031. case 18 :
  1032. // Test TinyInt Param
  1033. DBHelper.ExecuteNonQuery (conn,
  1034. String.Format(create_query,"tinyint"));
  1035. /*
  1036. rpc_helper_function (cmd, SqlDbType.TinyInt, 0, 10);
  1037. rpc_helper_function (cmd, SqlDbType.TinyInt, 0, -10);
  1038. rpc_helper_function (cmd, SqlDbType.TinyInt, 0, null);
  1039. */
  1040. break;
  1041. case 19 :
  1042. // Test UniqueIdentifier Param
  1043. /*
  1044. DBHelper.ExecuteNonQuery (conn,
  1045. String.Format(create_query,"uniqueidentifier"));
  1046. rpc_helper_function (cmd, SqlDbType.UniqueIdentifier, 0, "0f159bf395b1d04f8c2ef5c02c3add96");
  1047. rpc_helper_function (cmd, SqlDbType.UniqueIdentifier, 0, null);
  1048. */
  1049. break;
  1050. case 20 :
  1051. // Test VarBinary Param
  1052. /* NOT WORKING
  1053. DBHelper.ExecuteNonQuery (conn,
  1054. String.Format(create_query,"varbinary (10)"));
  1055. rpc_helper_function (cmd, SqlDbType.VarBinary, 0,);
  1056. rpc_helper_function (cmd, SqlDbType.VarBinary, 0,);
  1057. rpc_helper_function (cmd, SqlDbType.VarBinary, 0, null);
  1058. */
  1059. break;
  1060. case 21 :
  1061. // Test Varchar Param
  1062. DBHelper.ExecuteNonQuery (conn,
  1063. String.Format(create_query,"varchar(10)"));
  1064. rpc_helper_function (cmd, SqlDbType.VarChar, 10, "VarChar");
  1065. break;
  1066. case 22 :
  1067. // Test Variant Param
  1068. /* NOT WORKING
  1069. DBHelper.ExecuteNonQuery (conn,
  1070. String.Format(create_query,"variant"));
  1071. rpc_helper_function (cmd, SqlDbType.Variant, 0, );
  1072. rpc_helper_function (cmd, SqlDbType.Variant, 0, );
  1073. rpc_helper_function (cmd, SqlDbType.Variant, 0, null);
  1074. */
  1075. break;
  1076. default :
  1077. label = -2;
  1078. break;
  1079. }
  1080. }catch (AssertionException e) {
  1081. error += String.Format (" Case {0} INCORRECT VALUE : {1}\n",label, e.Message);
  1082. }catch (Exception e) {
  1083. error += String.Format (" Case {0} NOT WORKING : {1}\n",label, e.Message);
  1084. }
  1085. label++;
  1086. if (label != -1)
  1087. DBHelper.ExecuteNonQuery (conn, drop_query);
  1088. }
  1089. if (error != String.Empty)
  1090. Assert.Fail (error);
  1091. }
  1092. private void rpc_helper_function (SqlCommand cmd, SqlDbType type, int size, object val)
  1093. {
  1094. cmd.Parameters.Clear ();
  1095. SqlParameter param1 ;
  1096. SqlParameter param2 ;
  1097. if (size != 0) {
  1098. param1 = new SqlParameter ("@param1", type, size);
  1099. param2 = new SqlParameter ("@param2", type, size);
  1100. }
  1101. else {
  1102. param1 = new SqlParameter ("@param1", type);
  1103. param2 = new SqlParameter ("@param2", type);
  1104. }
  1105. SqlParameter retval = new SqlParameter ("retval", SqlDbType.Int);
  1106. param1.Value = val;
  1107. param1.Direction = ParameterDirection.Input;
  1108. param2.Direction = ParameterDirection.Output;
  1109. retval.Direction = ParameterDirection.ReturnValue;
  1110. cmd.Parameters.Add (param1);
  1111. cmd.Parameters.Add (param2);
  1112. cmd.Parameters.Add (retval);
  1113. cmd.CommandText = "#tmp_sp_param_test";
  1114. cmd.CommandType = CommandType.StoredProcedure;
  1115. using (SqlDataReader reader = cmd.ExecuteReader ()) {
  1116. while (reader.Read ()) {
  1117. if (param1.Value != null && param1.Value.GetType () == typeof (string))
  1118. Assert.AreEqual (param1.Value,
  1119. reader.GetValue(0).ToString (),"#1");
  1120. else
  1121. Assert.AreEqual (param1.Value,
  1122. reader.GetValue(0),"#1");
  1123. }
  1124. }
  1125. if (param1.Value != null && param1.Value.GetType () == typeof (string) && param2.Value != null)
  1126. Assert.AreEqual (param1.Value.ToString (), param2.Value.ToString (), "#2");
  1127. else
  1128. Assert.AreEqual (param1.Value, param2.Value, "#2");
  1129. Assert.AreEqual (5, retval.Value, "#3");
  1130. }
  1131. [Test]
  1132. [ExpectedException (typeof (InvalidOperationException))]
  1133. public void OutputParamSizeTest1 ()
  1134. {
  1135. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  1136. ConnectionManager.Singleton.OpenConnection ();
  1137. cmd = new SqlCommand ();
  1138. cmd.Connection = conn;
  1139. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  1140. cmd.CommandType = CommandType.Text;
  1141. cmd.ExecuteNonQuery ();
  1142. cmd.CommandText = "#testsize";
  1143. cmd.CommandType = CommandType.StoredProcedure;
  1144. SqlParameter p1 = new SqlParameter ();
  1145. p1.ParameterName = "@p1";
  1146. p1.Direction = ParameterDirection.InputOutput;
  1147. p1.DbType = DbType.String;
  1148. p1.IsNullable = false;
  1149. cmd.Parameters.Add (p1);
  1150. cmd.ExecuteNonQuery ();
  1151. }
  1152. [Test]
  1153. [ExpectedException (typeof (InvalidOperationException))]
  1154. public void OutputParamSizeTest2 ()
  1155. {
  1156. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  1157. ConnectionManager.Singleton.OpenConnection ();
  1158. cmd = new SqlCommand ();
  1159. cmd.Connection = conn;
  1160. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  1161. cmd.CommandType = CommandType.Text;
  1162. cmd.ExecuteNonQuery ();
  1163. cmd.CommandText = "#testsize";
  1164. cmd.CommandType = CommandType.StoredProcedure;
  1165. SqlParameter p1 = new SqlParameter ();
  1166. p1.ParameterName = "@p1";
  1167. p1.Direction = ParameterDirection.Output;
  1168. p1.DbType = DbType.String;
  1169. p1.IsNullable = false;
  1170. cmd.Parameters.Add (p1);
  1171. cmd.ExecuteNonQuery ();
  1172. }
  1173. [Test]
  1174. [ExpectedException (typeof (InvalidOperationException))]
  1175. public void OutputParamSizeTest3 ()
  1176. {
  1177. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  1178. ConnectionManager.Singleton.OpenConnection ();
  1179. cmd = new SqlCommand ();
  1180. cmd.Connection = conn;
  1181. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  1182. cmd.CommandType = CommandType.Text;
  1183. cmd.ExecuteNonQuery ();
  1184. cmd.CommandText = "#testsize";
  1185. cmd.CommandType = CommandType.StoredProcedure;
  1186. SqlParameter p1 = new SqlParameter ();
  1187. p1.ParameterName = "@p1";
  1188. p1.Direction = ParameterDirection.InputOutput;
  1189. p1.DbType = DbType.String;
  1190. p1.IsNullable = true;
  1191. cmd.Parameters.Add (p1);
  1192. cmd.ExecuteNonQuery ();
  1193. }
  1194. [Test]
  1195. [ExpectedException (typeof (InvalidOperationException))]
  1196. public void OutputParamSizeTest4 ()
  1197. {
  1198. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  1199. ConnectionManager.Singleton.OpenConnection ();
  1200. cmd = new SqlCommand ();
  1201. cmd.Connection = conn;
  1202. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  1203. cmd.CommandType = CommandType.Text;
  1204. cmd.ExecuteNonQuery ();
  1205. cmd.CommandText = "#testsize";
  1206. cmd.CommandType = CommandType.StoredProcedure;
  1207. SqlParameter p1 = new SqlParameter ();
  1208. p1.ParameterName = "@p1";
  1209. p1.Direction = ParameterDirection.Output;
  1210. p1.DbType = DbType.String;
  1211. p1.IsNullable = true;
  1212. cmd.Parameters.Add (p1);
  1213. cmd.ExecuteNonQuery ();
  1214. }
  1215. #if NET_2_0
  1216. [Test]
  1217. public void NotificationTest ()
  1218. {
  1219. cmd = new SqlCommand ();
  1220. SqlNotificationRequest notification = new SqlNotificationRequest("MyNotification","MyService",15);
  1221. Assert.AreEqual (null, cmd.Notification, "#1 The default value for this property should be null");
  1222. cmd.Notification = notification;
  1223. Assert.AreEqual ("MyService", cmd.Notification.Options, "#2 The value should be MyService as the constructor is initiated with this value");
  1224. Assert.AreEqual (15, cmd.Notification.Timeout, "#2 The value should be 15 as the constructor is initiated with this value");
  1225. }
  1226. [Test]
  1227. public void NotificationAutoEnlistTest ()
  1228. {
  1229. cmd = new SqlCommand ();
  1230. Assert.AreEqual (true, cmd.NotificationAutoEnlist, "#1 Default value of the property should be true");
  1231. cmd.NotificationAutoEnlist = false;
  1232. Assert.AreEqual (false, cmd.NotificationAutoEnlist, "#2 The value of the property should be false after setting it to false");
  1233. }
  1234. [Test]
  1235. public void BeginExecuteXmlReaderTest ()
  1236. {
  1237. cmd = new SqlCommand ();
  1238. string connectionString1 = null;
  1239. connectionString1 = ConnectionManager.Singleton.ConnectionString + "Asynchronous Processing=true";
  1240. try {
  1241. SqlConnection conn1 = new SqlConnection (connectionString1);
  1242. conn1.Open ();
  1243. cmd.CommandText = "Select lname from employee where id<2 FOR XML AUTO, XMLDATA" ;
  1244. cmd.Connection = conn1;
  1245. IAsyncResult result = cmd.BeginExecuteXmlReader ();
  1246. XmlReader reader = cmd.EndExecuteXmlReader (result);
  1247. while (reader.Read ())
  1248. {
  1249. if (reader.LocalName.ToString () == "employee")
  1250. {
  1251. Assert.AreEqual ("kumar", reader["lname"], "#1 ");
  1252. }
  1253. }
  1254. } finally {
  1255. ConnectionManager.Singleton.CloseConnection ();
  1256. }
  1257. }
  1258. [Test]
  1259. public void BeginExecuteXmlReaderExceptionTest ()
  1260. {
  1261. cmd = new SqlCommand ();
  1262. try {
  1263. SqlConnection conn = new SqlConnection (connectionString);
  1264. conn.Open ();
  1265. cmd.CommandText = "Select lname from employee where id<2 FOR XML AUTO, XMLDATA" ;
  1266. cmd.Connection = conn;
  1267. try {
  1268. /*IAsyncResult result = */cmd.BeginExecuteXmlReader ();
  1269. } catch (InvalidOperationException) {
  1270. Assert.AreEqual (ConnectionManager.Singleton.ConnectionString, connectionString, "#1 Connection string has changed");
  1271. return;
  1272. }
  1273. Assert.Fail ("Expected Exception InvalidOperationException not thrown");
  1274. } finally {
  1275. ConnectionManager.Singleton.CloseConnection ();
  1276. }
  1277. }
  1278. [Test]
  1279. public void SqlCommandDisposeTest ()
  1280. {
  1281. IDataReader reader = null;
  1282. try {
  1283. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  1284. ConnectionManager.Singleton.OpenConnection ();
  1285. IDbCommand command = conn.CreateCommand ();
  1286. try {
  1287. string sql = "SELECT * FROM employee";
  1288. command.CommandText = sql;
  1289. reader = command.ExecuteReader();
  1290. } finally {
  1291. command.Dispose();
  1292. }
  1293. while (reader.Read());
  1294. } finally {
  1295. reader.Dispose();
  1296. ConnectionManager.Singleton.CloseConnection ();
  1297. }
  1298. }
  1299. [Test]
  1300. public void CloneObjTest ()
  1301. {
  1302. SqlCommand cmd = new SqlCommand();
  1303. cmd.CommandText = "sp_insert";
  1304. cmd.CommandType = CommandType.StoredProcedure;
  1305. Object TestPar = DBNull.Value;
  1306. cmd.Parameters.Add ("@TestPar1", SqlDbType.Int);
  1307. cmd.Parameters ["@TestPar1"].Value = TestPar;
  1308. #if NET_2_0
  1309. cmd.Parameters.AddWithValue ("@BirthDate", DateTime.Now);
  1310. #else
  1311. cmd.Parameters.Add ("@BirthDate", DateTime.Now);
  1312. #endif
  1313. cmd.DesignTimeVisible = true;
  1314. cmd.CommandTimeout = 100;
  1315. SqlCommand cmd1 = cmd.Clone ();
  1316. Assert.AreEqual (2, cmd1.Parameters.Count);
  1317. Assert.AreEqual (100, cmd1.CommandTimeout);
  1318. #if NET_2_0
  1319. cmd1.Parameters.AddWithValue ("@test", DateTime.Now);
  1320. #else
  1321. cmd1.Parameters.Add ("@test", DateTime.Now);
  1322. #endif
  1323. Assert.AreEqual (3, cmd1.Parameters.Count);
  1324. Assert.AreEqual (2, cmd.Parameters.Count);
  1325. }
  1326. #endif
  1327. private enum Status {
  1328. OK = 0,
  1329. Error = 3
  1330. }
  1331. private readonly string CREATE_TMP_SP_PARAM_TEST = "create procedure #tmp_sp_param_test (@param1 {0}, @param2 {0} output) as begin select @param1 set @param2=@param1 return 5 end";
  1332. private readonly string DROP_TMP_SP_PARAM_TEST = "drop procedure #tmp_sp_param_test";
  1333. private readonly string CREATE_TMP_SP_TEMP_INSERT_PERSON = ("create procedure #sp_temp_insert_employee ( " + Environment.NewLine +
  1334. "@fname varchar (20)) " + Environment.NewLine +
  1335. "as " + Environment.NewLine +
  1336. "begin" + Environment.NewLine +
  1337. "declare @id int;" + Environment.NewLine +
  1338. "select @id = max (id) from employee;" + Environment.NewLine +
  1339. "set @id = @id + 6000 + 1;" + Environment.NewLine +
  1340. "insert into employee (id, fname, dob, doj) values (@id, @fname, '1980-02-11', getdate ());" + Environment.NewLine +
  1341. "return @id;" + Environment.NewLine +
  1342. "end");
  1343. private readonly string DROP_TMP_SP_TEMP_INSERT_PERSON = ("if exists (select name from sysobjects where " + Environment.NewLine +
  1344. "name = '#sp_temp_insert_employee' and type = 'P') " + Environment.NewLine +
  1345. "drop procedure #sp_temp_insert_employee; ");
  1346. }
  1347. }