SqlCommandTest.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  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 CloneObjTest ()
  1280. {
  1281. SqlCommand cmd = new SqlCommand();
  1282. cmd.CommandText = "sp_insert";
  1283. cmd.CommandType = CommandType.StoredProcedure;
  1284. Object TestPar = DBNull.Value;
  1285. cmd.Parameters.Add ("@TestPar1", SqlDbType.Int);
  1286. cmd.Parameters ["@TestPar1"].Value = TestPar;
  1287. #if NET_2_0
  1288. cmd.Parameters.AddWithValue ("@BirthDate", DateTime.Now);
  1289. #else
  1290. cmd.Parameters.Add ("@BirthDate", DateTime.Now);
  1291. #endif
  1292. cmd.DesignTimeVisible = true;
  1293. cmd.CommandTimeout = 100;
  1294. SqlCommand cmd1 = cmd.Clone ();
  1295. Assert.AreEqual (2, cmd1.Parameters.Count);
  1296. Assert.AreEqual (100, cmd1.CommandTimeout);
  1297. #if NET_2_0
  1298. cmd1.Parameters.AddWithValue ("@test", DateTime.Now);
  1299. #else
  1300. cmd1.Parameters.Add ("@test", DateTime.Now);
  1301. #endif
  1302. Assert.AreEqual (3, cmd1.Parameters.Count);
  1303. Assert.AreEqual (2, cmd.Parameters.Count);
  1304. }
  1305. #endif
  1306. private enum Status {
  1307. OK = 0,
  1308. Error = 3
  1309. }
  1310. 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";
  1311. private readonly string DROP_TMP_SP_PARAM_TEST = "drop procedure #tmp_sp_param_test";
  1312. private readonly string CREATE_TMP_SP_TEMP_INSERT_PERSON = ("create procedure #sp_temp_insert_employee ( " + Environment.NewLine +
  1313. "@fname varchar (20)) " + Environment.NewLine +
  1314. "as " + Environment.NewLine +
  1315. "begin" + Environment.NewLine +
  1316. "declare @id int;" + Environment.NewLine +
  1317. "select @id = max (id) from employee;" + Environment.NewLine +
  1318. "set @id = @id + 6000 + 1;" + Environment.NewLine +
  1319. "insert into employee (id, fname, dob, doj) values (@id, @fname, '1980-02-11', getdate ());" + Environment.NewLine +
  1320. "return @id;" + Environment.NewLine +
  1321. "end");
  1322. private readonly string DROP_TMP_SP_TEMP_INSERT_PERSON = ("if exists (select name from sysobjects where " + Environment.NewLine +
  1323. "name = '#sp_temp_insert_employee' and type = 'P') " + Environment.NewLine +
  1324. "drop procedure #sp_temp_insert_employee; ");
  1325. }
  1326. }