ObjectDataSourceView.cs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. //
  2. // System.Web.UI.WebControls.ObjectDataSourceView
  3. //
  4. // Authors:
  5. // Lluis Sanchez Gual ([email protected])
  6. //
  7. // (C) 2005 Novell, Inc. (http://www.novell.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_2_0
  30. using System;
  31. using System.Reflection;
  32. using System.Collections;
  33. using System.Collections.Specialized;
  34. using System.ComponentModel;
  35. using System.IO;
  36. using System.Data;
  37. using System.Web.Compilation;
  38. namespace System.Web.UI.WebControls
  39. {
  40. public class ObjectDataSourceView : DataSourceView, IStateManager
  41. {
  42. ObjectDataSource owner;
  43. HttpContext context;
  44. Type objectType;
  45. Type dataObjectType;
  46. bool convertNullToDBNull = false;
  47. bool enablePaging = false;
  48. string dataObjectTypeName = null;
  49. string filterExpression = null;
  50. string maximumRowsParameterName = null;
  51. string oldValuesParameterFormatString = null;
  52. string deleteMethod = null;
  53. string insertMethod = null;
  54. string selectCountMethod = null;
  55. string selectMethod = null;
  56. string sortParameterName = null;
  57. string startRowIndexParameterName = null;
  58. string typeName = null;
  59. string updateMethod = null;
  60. private static string privateBinPath = null;
  61. bool isTrackingViewState = false;
  62. ParameterCollection selectParameters;
  63. ParameterCollection updateParameters;
  64. ParameterCollection deleteParameters;
  65. ParameterCollection insertParameters;
  66. ParameterCollection filterParameters;
  67. private static readonly object DeletedEvent = new object();
  68. private static readonly object DeletingEvent = new object();
  69. private static readonly object FilteringEvent = new object();
  70. private static readonly object InsertedEvent = new object();
  71. private static readonly object InsertingEvent = new object();
  72. private static readonly object ObjectCreatedEvent = new object();
  73. private static readonly object ObjectCreatingEvent = new object();
  74. private static readonly object ObjectDisposingEvent = new object();
  75. // private static readonly object ResolvingMethodEvent = new object();
  76. private static readonly object SelectedEvent = new object();
  77. private static readonly object SelectingEvent = new object();
  78. private static readonly object UpdatedEvent = new object();
  79. private static readonly object UpdatingEvent = new object();
  80. public ObjectDataSourceView (ObjectDataSource owner, string name, HttpContext context): base (owner, name)
  81. {
  82. this.owner = owner;
  83. this.context = context;
  84. }
  85. public event ObjectDataSourceStatusEventHandler Deleted {
  86. add { Events.AddHandler (DeletedEvent, value); }
  87. remove { Events.RemoveHandler (DeletedEvent, value); }
  88. }
  89. public event ObjectDataSourceMethodEventHandler Deleting {
  90. add { Events.AddHandler (DeletingEvent, value); }
  91. remove { Events.RemoveHandler (DeletingEvent, value); }
  92. }
  93. public event ObjectDataSourceFilteringEventHandler Filtering {
  94. add { Events.AddHandler (FilteringEvent, value); }
  95. remove { Events.RemoveHandler (FilteringEvent, value); }
  96. }
  97. public event ObjectDataSourceStatusEventHandler Inserted {
  98. add { Events.AddHandler (InsertedEvent, value); }
  99. remove { Events.RemoveHandler (InsertedEvent, value); }
  100. }
  101. public event ObjectDataSourceMethodEventHandler Inserting {
  102. add { Events.AddHandler (InsertingEvent, value); }
  103. remove { Events.RemoveHandler (InsertingEvent, value); }
  104. }
  105. public event ObjectDataSourceObjectEventHandler ObjectCreated {
  106. add { Events.AddHandler (ObjectCreatedEvent, value); }
  107. remove { Events.RemoveHandler (ObjectCreatedEvent, value); }
  108. }
  109. public event ObjectDataSourceObjectEventHandler ObjectCreating {
  110. add { Events.AddHandler (ObjectCreatingEvent, value); }
  111. remove { Events.RemoveHandler (ObjectCreatingEvent, value); }
  112. }
  113. public event ObjectDataSourceDisposingEventHandler ObjectDisposing {
  114. add { Events.AddHandler (ObjectDisposingEvent, value); }
  115. remove { Events.RemoveHandler (ObjectDisposingEvent, value); }
  116. }
  117. /* public event ObjectDataSourceResolvingMethodEventHandler ResolvingMethod {
  118. add { Events.AddHandler (ResolvingMethodEvent, value); }
  119. remove { Events.RemoveHandler (ResolvingMethodEvent, value); }
  120. }
  121. */
  122. public event ObjectDataSourceStatusEventHandler Selected {
  123. add { Events.AddHandler (SelectedEvent, value); }
  124. remove { Events.RemoveHandler (SelectedEvent, value); }
  125. }
  126. public event ObjectDataSourceSelectingEventHandler Selecting {
  127. add { Events.AddHandler (SelectingEvent, value); }
  128. remove { Events.RemoveHandler (SelectingEvent, value); }
  129. }
  130. public event ObjectDataSourceStatusEventHandler Updated {
  131. add { Events.AddHandler (UpdatedEvent, value); }
  132. remove { Events.RemoveHandler (UpdatedEvent, value); }
  133. }
  134. public event ObjectDataSourceMethodEventHandler Updating {
  135. add { Events.AddHandler (UpdatingEvent, value); }
  136. remove { Events.RemoveHandler (UpdatingEvent, value); }
  137. }
  138. protected virtual void OnDeleted (ObjectDataSourceStatusEventArgs e)
  139. {
  140. if (Events != null) {
  141. ObjectDataSourceStatusEventHandler eh = (ObjectDataSourceStatusEventHandler) Events [DeletedEvent];
  142. if (eh != null) eh (this, e);
  143. }
  144. }
  145. protected virtual void OnDeleting (ObjectDataSourceMethodEventArgs e)
  146. {
  147. if (Events != null) {
  148. ObjectDataSourceMethodEventHandler eh = (ObjectDataSourceMethodEventHandler) Events [DeletingEvent];
  149. if (eh != null) eh (this, e);
  150. }
  151. }
  152. protected virtual void OnFiltering (ObjectDataSourceFilteringEventArgs e)
  153. {
  154. if (Events != null) {
  155. ObjectDataSourceFilteringEventHandler eh = (ObjectDataSourceFilteringEventHandler) Events [FilteringEvent];
  156. if (eh != null) eh (this, e);
  157. }
  158. }
  159. protected virtual void OnInserted (ObjectDataSourceStatusEventArgs e)
  160. {
  161. if (Events != null) {
  162. ObjectDataSourceStatusEventHandler eh = (ObjectDataSourceStatusEventHandler) Events [InsertedEvent];
  163. if (eh != null) eh (this, e);
  164. }
  165. }
  166. protected virtual void OnInserting (ObjectDataSourceMethodEventArgs e)
  167. {
  168. if (Events != null) {
  169. ObjectDataSourceMethodEventHandler eh = (ObjectDataSourceMethodEventHandler) Events [InsertingEvent];
  170. if (eh != null) eh (this, e);
  171. }
  172. }
  173. protected virtual void OnObjectCreated (ObjectDataSourceEventArgs e)
  174. {
  175. if (Events != null) {
  176. ObjectDataSourceObjectEventHandler eh = (ObjectDataSourceObjectEventHandler) Events [ObjectCreatedEvent];
  177. if (eh != null) eh (this, e);
  178. }
  179. }
  180. protected virtual void OnObjectCreating (ObjectDataSourceEventArgs e)
  181. {
  182. if (Events != null) {
  183. ObjectDataSourceObjectEventHandler eh = (ObjectDataSourceObjectEventHandler) Events [ObjectCreatingEvent];
  184. if (eh != null) eh (this, e);
  185. }
  186. }
  187. protected virtual void OnObjectDisposing (ObjectDataSourceDisposingEventArgs e)
  188. {
  189. if (Events != null) {
  190. ObjectDataSourceDisposingEventHandler eh = (ObjectDataSourceDisposingEventHandler) Events [ObjectDisposingEvent];
  191. if (eh != null) eh (this, e);
  192. }
  193. }
  194. /* protected virtual void OnResolvingMethod (ObjectDataSourceResolvingMethodEventArgs e)
  195. {
  196. if (Events != null) {
  197. ObjectDataSourceResolvingMethodEventHandler eh = (ObjectDataSourceResolvingMethodEventHandler) Events [ResolvingMethodEvent];
  198. if (eh != null) eh (this, e);
  199. }
  200. }
  201. */
  202. protected virtual void OnSelected (ObjectDataSourceStatusEventArgs e)
  203. {
  204. if (Events != null) {
  205. ObjectDataSourceStatusEventHandler eh = (ObjectDataSourceStatusEventHandler) Events [SelectedEvent];
  206. if (eh != null) eh (this, e);
  207. }
  208. }
  209. protected virtual void OnSelecting (ObjectDataSourceSelectingEventArgs e)
  210. {
  211. if (Events != null) {
  212. ObjectDataSourceSelectingEventHandler eh = (ObjectDataSourceSelectingEventHandler) Events [SelectingEvent];
  213. if (eh != null) eh (this, e);
  214. }
  215. }
  216. protected virtual void OnUpdated (ObjectDataSourceStatusEventArgs e)
  217. {
  218. if (Events != null) {
  219. ObjectDataSourceStatusEventHandler eh = (ObjectDataSourceStatusEventHandler) Events [UpdatedEvent];
  220. if (eh != null) eh (this, e);
  221. }
  222. }
  223. protected virtual void OnUpdating (ObjectDataSourceMethodEventArgs e)
  224. {
  225. if (Events != null) {
  226. ObjectDataSourceMethodEventHandler eh = (ObjectDataSourceMethodEventHandler) Events [UpdatingEvent];
  227. if (eh != null) eh (this, e);
  228. }
  229. }
  230. public override bool CanDelete {
  231. get { return DeleteMethod.Length > 0; }
  232. }
  233. public override bool CanInsert {
  234. get { return InsertMethod.Length > 0; }
  235. }
  236. public override bool CanPage {
  237. get { return EnablePaging; }
  238. }
  239. public override bool CanRetrieveTotalRowCount {
  240. get {
  241. if( SelectCountMethod.Length > 0)
  242. return true;
  243. return !EnablePaging;
  244. }
  245. }
  246. public override bool CanSort {
  247. get { return true; }
  248. }
  249. public override bool CanUpdate {
  250. get { return UpdateMethod.Length > 0; }
  251. }
  252. // LAME SPEC: MSDN says value should be stored in ViewState but tests show otherwise.
  253. private ConflictOptions conflictDetection = ConflictOptions.OverwriteChanges;
  254. public ConflictOptions ConflictDetection {
  255. get { return conflictDetection; }
  256. set { conflictDetection = value; }
  257. }
  258. public bool ConvertNullToDBNull {
  259. get { return convertNullToDBNull; }
  260. set { convertNullToDBNull = value; }
  261. }
  262. public string DataObjectTypeName {
  263. get {
  264. return dataObjectTypeName != null ? dataObjectTypeName : string.Empty;
  265. }
  266. set {
  267. dataObjectTypeName = value;
  268. dataObjectType = null;
  269. }
  270. }
  271. public string DeleteMethod {
  272. get {
  273. return deleteMethod != null ? deleteMethod : string.Empty;
  274. }
  275. set {
  276. deleteMethod = value;
  277. }
  278. }
  279. public ParameterCollection DeleteParameters {
  280. get {
  281. if (deleteParameters == null) {
  282. deleteParameters = new ParameterCollection ();
  283. }
  284. return deleteParameters;
  285. }
  286. }
  287. public bool EnablePaging {
  288. get {
  289. return enablePaging;
  290. }
  291. set {
  292. enablePaging = value;
  293. }
  294. }
  295. public string FilterExpression {
  296. get {
  297. return filterExpression != null ? filterExpression : string.Empty;
  298. }
  299. set {
  300. filterExpression = value;
  301. }
  302. }
  303. public ParameterCollection FilterParameters {
  304. get {
  305. if (filterParameters == null) {
  306. filterParameters = new ParameterCollection ();
  307. filterParameters.ParametersChanged += new EventHandler (OnParametersChanged);
  308. if (IsTrackingViewState)
  309. ((IStateManager)filterParameters).TrackViewState ();
  310. }
  311. return filterParameters;
  312. }
  313. }
  314. public string InsertMethod {
  315. get {
  316. return insertMethod != null ? insertMethod : string.Empty;
  317. }
  318. set {
  319. insertMethod = value;
  320. }
  321. }
  322. public ParameterCollection InsertParameters {
  323. get {
  324. if (insertParameters == null) {
  325. insertParameters = new ParameterCollection ();
  326. }
  327. return insertParameters;
  328. }
  329. }
  330. public string MaximumRowsParameterName {
  331. get {
  332. return maximumRowsParameterName != null ? maximumRowsParameterName : "maximumRows";
  333. }
  334. set {
  335. maximumRowsParameterName = value;
  336. }
  337. }
  338. public string OldValuesParameterFormatString {
  339. get {
  340. return oldValuesParameterFormatString != null ? oldValuesParameterFormatString : "{0}";
  341. }
  342. set {
  343. oldValuesParameterFormatString = value;
  344. }
  345. }
  346. public string SelectCountMethod {
  347. get {
  348. return selectCountMethod != null ? selectCountMethod : string.Empty;
  349. }
  350. set {
  351. selectCountMethod = value;
  352. }
  353. }
  354. public string SelectMethod {
  355. get {
  356. return selectMethod != null ? selectMethod : string.Empty;
  357. }
  358. set {
  359. selectMethod = value;
  360. }
  361. }
  362. public ParameterCollection SelectParameters {
  363. get {
  364. if (selectParameters == null) {
  365. selectParameters = new ParameterCollection ();
  366. selectParameters.ParametersChanged += new EventHandler (OnParametersChanged);
  367. if (IsTrackingViewState)
  368. ((IStateManager)selectParameters).TrackViewState ();
  369. }
  370. return selectParameters;
  371. }
  372. }
  373. public string SortParameterName {
  374. get {
  375. return sortParameterName != null ? sortParameterName : string.Empty;
  376. }
  377. set {
  378. sortParameterName = value;
  379. }
  380. }
  381. public string StartRowIndexParameterName {
  382. get {
  383. return startRowIndexParameterName != null ? startRowIndexParameterName : "startRowIndex";
  384. }
  385. set {
  386. startRowIndexParameterName = value;
  387. }
  388. }
  389. public string TypeName {
  390. get {
  391. return typeName != null ? typeName : string.Empty;
  392. }
  393. set {
  394. typeName = value;
  395. objectType = null;
  396. }
  397. }
  398. public string UpdateMethod {
  399. get {
  400. return updateMethod != null ? updateMethod : string.Empty;
  401. }
  402. set {
  403. updateMethod = value;
  404. }
  405. }
  406. public ParameterCollection UpdateParameters {
  407. get {
  408. if (updateParameters == null) {
  409. updateParameters = new ParameterCollection ();
  410. }
  411. return updateParameters;
  412. }
  413. }
  414. private static string PrivateBinPath {
  415. get {
  416. if (privateBinPath != null)
  417. return privateBinPath;
  418. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  419. privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  420. return privateBinPath;
  421. }
  422. }
  423. Type ObjectType {
  424. get {
  425. if (objectType == null) {
  426. objectType = HttpApplication.LoadType (TypeName);
  427. if (objectType == null)
  428. throw new InvalidOperationException ("Type not found: " + TypeName);
  429. }
  430. return objectType;
  431. }
  432. }
  433. Type DataObjectType {
  434. get {
  435. if (dataObjectType == null) {
  436. dataObjectType = HttpApplication.LoadType (DataObjectTypeName);
  437. if (dataObjectType == null)
  438. throw new InvalidOperationException ("Type not found: " + DataObjectTypeName);
  439. }
  440. return dataObjectType;
  441. }
  442. }
  443. public IEnumerable Select (DataSourceSelectArguments arguments)
  444. {
  445. return ExecuteSelect (arguments);
  446. }
  447. public int Update (IDictionary keys, IDictionary values, IDictionary oldValues)
  448. {
  449. return ExecuteUpdate (keys, values, oldValues);
  450. }
  451. public int Delete (IDictionary keys, IDictionary oldValues)
  452. {
  453. return ExecuteDelete (keys, oldValues);
  454. }
  455. public int Insert (IDictionary values)
  456. {
  457. return ExecuteInsert (values);
  458. }
  459. protected override int ExecuteInsert (IDictionary values)
  460. {
  461. if (!CanInsert)
  462. throw new NotSupportedException ("Insert operation not supported.");
  463. IOrderedDictionary paramValues;
  464. MethodInfo method;
  465. if (DataObjectTypeName.Length == 0) {
  466. paramValues = MergeParameterValues (InsertParameters, values, null);
  467. method = GetObjectMethod (InsertMethod, paramValues, DataObjectMethodType.Insert);
  468. } else {
  469. method = ResolveDataObjectMethod (InsertMethod, values, null, out paramValues);
  470. }
  471. ObjectDataSourceMethodEventArgs args = new ObjectDataSourceMethodEventArgs (paramValues);
  472. OnInserting (args);
  473. if (args.Cancel)
  474. return -1;
  475. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  476. OnInserted (rargs);
  477. if (rargs.Exception != null && !rargs.ExceptionHandled)
  478. throw rargs.Exception;
  479. if (owner.EnableCaching)
  480. owner.Cache.Expire ();
  481. OnDataSourceViewChanged (EventArgs.Empty);
  482. return -1;
  483. }
  484. protected override int ExecuteDelete (IDictionary keys, IDictionary oldValues)
  485. {
  486. if (!CanDelete)
  487. throw new NotSupportedException ("Delete operation not supported.");
  488. if (ConflictDetection == ConflictOptions.CompareAllValues && (oldValues == null || oldValues.Count == 0))
  489. throw new InvalidOperationException ("ConflictDetection is set to CompareAllValues and oldValues collection is null or empty.");
  490. IDictionary oldDataValues;
  491. oldDataValues = BuildOldValuesList (keys, oldValues, false);
  492. IOrderedDictionary paramValues;
  493. MethodInfo method;
  494. if (DataObjectTypeName.Length == 0) {
  495. paramValues = MergeParameterValues (DeleteParameters, null, oldDataValues);
  496. method = GetObjectMethod (DeleteMethod, paramValues, DataObjectMethodType.Delete);
  497. } else {
  498. method = ResolveDataObjectMethod (DeleteMethod, oldDataValues, null, out paramValues);
  499. }
  500. ObjectDataSourceMethodEventArgs args = new ObjectDataSourceMethodEventArgs (paramValues);
  501. OnDeleting (args);
  502. if (args.Cancel)
  503. return -1;
  504. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  505. OnDeleted (rargs);
  506. if (rargs.Exception != null && !rargs.ExceptionHandled)
  507. throw rargs.Exception;
  508. if (owner.EnableCaching)
  509. owner.Cache.Expire ();
  510. OnDataSourceViewChanged (EventArgs.Empty);
  511. return -1;
  512. }
  513. protected override int ExecuteUpdate (IDictionary keys, IDictionary values, IDictionary oldValues)
  514. {
  515. IOrderedDictionary paramValues;
  516. MethodInfo method;
  517. IDictionary oldDataValues;
  518. oldDataValues = BuildOldValuesList (keys, oldValues, true);
  519. if (DataObjectTypeName.Length == 0)
  520. {
  521. IDictionary dataValues;
  522. dataValues = values;
  523. paramValues = MergeParameterValues (UpdateParameters, dataValues, oldDataValues);
  524. method = GetObjectMethod (UpdateMethod, paramValues, DataObjectMethodType.Update);
  525. }
  526. else
  527. {
  528. if (ConflictDetection != ConflictOptions.CompareAllValues) {
  529. oldDataValues = null;
  530. }
  531. IDictionary dataValues = new Hashtable ();
  532. if (keys != null) {
  533. foreach (DictionaryEntry de in keys)
  534. dataValues [de.Key] = de.Value;
  535. }
  536. if (values != null) {
  537. foreach (DictionaryEntry de in values)
  538. dataValues [de.Key] = de.Value;
  539. }
  540. method = ResolveDataObjectMethod (UpdateMethod, dataValues, oldDataValues, out paramValues);
  541. }
  542. ObjectDataSourceMethodEventArgs args = new ObjectDataSourceMethodEventArgs (paramValues);
  543. OnUpdating (args);
  544. if (args.Cancel)
  545. return -1;
  546. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  547. OnUpdated (rargs);
  548. if (rargs.Exception != null && !rargs.ExceptionHandled)
  549. throw rargs.Exception;
  550. if (owner.EnableCaching)
  551. owner.Cache.Expire ();
  552. OnDataSourceViewChanged (EventArgs.Empty);
  553. return -1;
  554. }
  555. private IDictionary BuildOldValuesList (IDictionary keys, IDictionary oldValues, bool keysWin)
  556. {
  557. IDictionary oldDataValues;
  558. if (ConflictDetection == ConflictOptions.CompareAllValues) {
  559. oldDataValues = new Hashtable ();
  560. if (keys != null && !keysWin) {
  561. foreach (DictionaryEntry de in keys)
  562. oldDataValues [de.Key] = de.Value;
  563. }
  564. if (oldValues != null) {
  565. foreach (DictionaryEntry de in oldValues)
  566. oldDataValues [de.Key] = de.Value;
  567. }
  568. if (keys != null && keysWin) {
  569. foreach (DictionaryEntry de in keys)
  570. oldDataValues [de.Key] = de.Value;
  571. }
  572. }
  573. else {
  574. oldDataValues = keys;
  575. }
  576. return oldDataValues;
  577. }
  578. protected internal override IEnumerable ExecuteSelect (DataSourceSelectArguments arguments)
  579. {
  580. arguments.RaiseUnsupportedCapabilitiesError (this);
  581. IOrderedDictionary paramValues = MergeParameterValues (SelectParameters, null, null);
  582. ObjectDataSourceSelectingEventArgs args = new ObjectDataSourceSelectingEventArgs (paramValues, arguments, false);
  583. object result = null;
  584. if (owner.EnableCaching)
  585. result = owner.Cache.GetCachedObject (SelectMethod, SelectParameters);
  586. if (result == null) {
  587. OnSelecting (args);
  588. if (args.Cancel)
  589. return new ArrayList ();
  590. if (CanRetrieveTotalRowCount && arguments.RetrieveTotalRowCount)
  591. arguments.TotalRowCount = QueryTotalRowCount (paramValues, arguments);
  592. if (CanPage) {
  593. if (StartRowIndexParameterName.Length == 0)
  594. throw new InvalidOperationException ("Paging is enabled, but the StartRowIndexParameterName property is not set.");
  595. if (MaximumRowsParameterName.Length == 0)
  596. throw new InvalidOperationException ("Paging is enabled, but the MaximumRowsParameterName property is not set.");
  597. paramValues [StartRowIndexParameterName] = arguments.StartRowIndex;
  598. paramValues [MaximumRowsParameterName] = arguments.MaximumRows;
  599. }
  600. if (SortParameterName.Length > 0)
  601. paramValues [SortParameterName] = arguments.SortExpression;
  602. result = InvokeSelect (SelectMethod, paramValues);
  603. if (owner.EnableCaching)
  604. owner.Cache.SetCachedObject (SelectMethod, SelectParameters, result);
  605. }
  606. if (FilterExpression.Length > 0 && !(result is DataGrid || result is DataView || result is DataTable))
  607. throw new NotSupportedException ("The FilterExpression property was set and the Select method does not return a DataSet, DataTable, or DataView.");
  608. if (owner.EnableCaching && result is IDataReader)
  609. throw new NotSupportedException ("Data source does not support caching objects that implement IDataReader");
  610. if (result is DataSet) {
  611. DataSet dset = (DataSet) result;
  612. if (dset.Tables.Count == 0)
  613. throw new InvalidOperationException ("The select method returnet a DataSet which doesn't contain any table.");
  614. result = dset.Tables [0];
  615. }
  616. if (result is DataTable) {
  617. DataView dview = new DataView ((DataTable)result);
  618. if (arguments.SortExpression != null && arguments.SortExpression.Length > 0) {
  619. dview.Sort = arguments.SortExpression;
  620. }
  621. if (FilterExpression.Length > 0) {
  622. IOrderedDictionary fparams = FilterParameters.GetValues (context, owner);
  623. ObjectDataSourceFilteringEventArgs fargs = new ObjectDataSourceFilteringEventArgs (fparams);
  624. OnFiltering (fargs);
  625. if (!fargs.Cancel) {
  626. object[] formatValues = new object [fparams.Count];
  627. for (int n=0; n<formatValues.Length; n++) {
  628. formatValues [n] = fparams [n];
  629. if (formatValues [n] == null) return dview;
  630. }
  631. dview.RowFilter = string.Format (FilterExpression, formatValues);
  632. }
  633. }
  634. return dview;
  635. }
  636. if (result is IEnumerable)
  637. return (IEnumerable) result;
  638. else
  639. return new object[] { result };
  640. }
  641. int QueryTotalRowCount (IOrderedDictionary mergedParameters, DataSourceSelectArguments arguments)
  642. {
  643. ObjectDataSourceSelectingEventArgs countArgs = new ObjectDataSourceSelectingEventArgs (mergedParameters, arguments, true);
  644. OnSelecting (countArgs);
  645. if (countArgs.Cancel)
  646. return 0;
  647. object count = InvokeSelect (SelectCountMethod, mergedParameters);
  648. return (int) Convert.ChangeType (count, typeof(int));
  649. }
  650. object InvokeSelect (string methodName, IOrderedDictionary paramValues)
  651. {
  652. MethodInfo method = GetObjectMethod (methodName, paramValues, DataObjectMethodType.Select);
  653. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  654. OnSelected (rargs);
  655. if (rargs.Exception != null && !rargs.ExceptionHandled)
  656. throw rargs.Exception;
  657. return rargs.ReturnValue;
  658. }
  659. ObjectDataSourceStatusEventArgs InvokeMethod (MethodInfo method, IOrderedDictionary paramValues)
  660. {
  661. object instance = null;
  662. if (!method.IsStatic)
  663. instance = CreateObjectInstance ();
  664. ParameterInfo[] pars = method.GetParameters ();
  665. ArrayList outParamInfos;
  666. object[] methodArgs = GetParameterArray (pars, paramValues, out outParamInfos);
  667. if (methodArgs == null)
  668. throw CreateMethodException (method.Name, paramValues);
  669. object result = null;
  670. Hashtable outParams = null;
  671. try {
  672. result = method.Invoke (instance, methodArgs);
  673. if (outParamInfos != null) {
  674. outParams = new Hashtable ();
  675. foreach (ParameterInfo op in outParamInfos)
  676. outParams [op.Name] = methodArgs [op.Position];
  677. }
  678. return new ObjectDataSourceStatusEventArgs (result, outParams, null);
  679. }
  680. catch (Exception ex) {
  681. return new ObjectDataSourceStatusEventArgs (result, outParams, ex);
  682. }
  683. finally {
  684. if (instance != null)
  685. DisposeObjectInstance (instance);
  686. }
  687. }
  688. MethodInfo GetObjectMethod (string methodName, IOrderedDictionary parameters, DataObjectMethodType methodType)
  689. {
  690. MemberInfo[] methods = ObjectType.GetMember (methodName, MemberTypes.Method, BindingFlags.Instance |
  691. BindingFlags.Static |
  692. BindingFlags.Public |
  693. BindingFlags.IgnoreCase |
  694. BindingFlags.FlattenHierarchy);
  695. if (methods.Length > 1) {
  696. // MSDN: The ObjectDataSource resolves method overloads by method name and number
  697. // of parameters; the names and types of the parameters are not considered.
  698. // LAMESPEC: the tests show otherwise
  699. DataObjectMethodAttribute methodAttribute = null;
  700. MethodInfo methodInfo = null;
  701. bool hasConflict = false;
  702. foreach (MethodInfo me in methods) { // we look for methods only
  703. ParameterInfo [] pinfos = me.GetParameters ();
  704. if (pinfos.Length == parameters.Count) {
  705. object [] attrs = me.GetCustomAttributes (typeof (DataObjectMethodAttribute), true);
  706. DataObjectMethodAttribute domAttr = (attrs != null && attrs.Length > 0) ? (DataObjectMethodAttribute) attrs [0] : null;
  707. if (domAttr != null && domAttr.MethodType != methodType)
  708. continue;
  709. bool paramsMatch = true;
  710. foreach (ParameterInfo pinfo in pinfos) {
  711. if (!parameters.Contains (pinfo.Name)) {
  712. paramsMatch = false;
  713. break;
  714. }
  715. }
  716. if (!paramsMatch)
  717. continue;
  718. if (domAttr != null) {
  719. if (methodAttribute != null) {
  720. if (methodAttribute.IsDefault) {
  721. if (domAttr.IsDefault) {
  722. methodInfo = null;
  723. break; //fail due to a conflict
  724. }
  725. else
  726. continue; //existing matches better
  727. }
  728. else {
  729. methodInfo = null; //we override
  730. hasConflict = !domAttr.IsDefault;
  731. }
  732. }
  733. else
  734. methodInfo = null; //we override
  735. }
  736. if (methodInfo == null) {
  737. methodAttribute = domAttr;
  738. methodInfo = me;
  739. continue;
  740. }
  741. hasConflict = true;
  742. }
  743. }
  744. if (!hasConflict && methodInfo != null)
  745. return methodInfo;
  746. }
  747. else if (methods.Length == 1) {
  748. MethodInfo me = methods[0] as MethodInfo;
  749. if (me != null && me.GetParameters().Length == parameters.Count)
  750. return me;
  751. }
  752. throw CreateMethodException (methodName, parameters);
  753. }
  754. MethodInfo ResolveDataObjectMethod (string methodName, IDictionary values, IDictionary oldValues, out IOrderedDictionary paramValues)
  755. {
  756. MethodInfo method;
  757. if (oldValues != null)
  758. method = ObjectType.GetMethod (methodName, new Type[] { DataObjectType, DataObjectType });
  759. else
  760. method = ObjectType.GetMethod (methodName, new Type[] { DataObjectType });
  761. if (method == null)
  762. throw new InvalidOperationException ("ObjectDataSource " + owner.ID + " could not find a method named '" + methodName + "' with parameters of type '" + DataObjectType + "' in '" + ObjectType + "'.");
  763. paramValues = new OrderedDictionary (StringComparer.InvariantCultureIgnoreCase);
  764. ParameterInfo[] ps = method.GetParameters ();
  765. if (oldValues != null) {
  766. if (FormatOldParameter (ps[0].Name) == ps[1].Name) {
  767. paramValues [ps[0].Name] = CreateDataObject (values);
  768. paramValues [ps[1].Name] = CreateDataObject (oldValues);
  769. } else if (FormatOldParameter (ps[1].Name) == ps[0].Name) {
  770. paramValues [ps[0].Name] = CreateDataObject (oldValues);
  771. paramValues [ps[1].Name] = CreateDataObject (values);
  772. } else
  773. throw new InvalidOperationException ("Method '" + methodName + "' does not have any parameter that fits the value of OldValuesParameterFormatString.");
  774. } else {
  775. paramValues [ps[0].Name] = CreateDataObject (values);
  776. }
  777. return method;
  778. }
  779. Exception CreateMethodException (string methodName, IOrderedDictionary parameters)
  780. {
  781. string s = "";
  782. foreach (string p in parameters.Keys) {
  783. s += p + ", ";
  784. }
  785. return new InvalidOperationException ("ObjectDataSource " + owner.ID + " could not find a method named '" + methodName + "' with parameters " + s + "in type '" + ObjectType + "'.");
  786. }
  787. object CreateDataObject (IDictionary values)
  788. {
  789. object ob = Activator.CreateInstance (DataObjectType);
  790. foreach (DictionaryEntry de in values) {
  791. PropertyInfo p = DataObjectType.GetProperty ((string)de.Key);
  792. if (p == null) throw new InvalidOperationException ("Property " + de.Key + " not found in type '" +DataObjectType + "'.");
  793. p.SetValue (ob, ConvertParameter (p.PropertyType, de.Value), null);
  794. }
  795. return ob;
  796. }
  797. object CreateObjectInstance ()
  798. {
  799. ObjectDataSourceEventArgs args = new ObjectDataSourceEventArgs (null);
  800. OnObjectCreating (args);
  801. if (args.ObjectInstance != null)
  802. return args.ObjectInstance;
  803. object ob = Activator.CreateInstance (ObjectType);
  804. args.ObjectInstance = ob;
  805. OnObjectCreated (args);
  806. return args.ObjectInstance;
  807. }
  808. void DisposeObjectInstance (object obj)
  809. {
  810. ObjectDataSourceDisposingEventArgs args = new ObjectDataSourceDisposingEventArgs (obj);
  811. OnObjectDisposing (args);
  812. if (!args.Cancel) {
  813. IDisposable disp = obj as IDisposable;
  814. if (disp != null) disp.Dispose ();
  815. }
  816. }
  817. object FindValueByName (string name, IDictionary values, bool format)
  818. {
  819. if (values == null)
  820. return null;
  821. foreach (DictionaryEntry de in values) {
  822. string valueName = format == true ? FormatOldParameter (de.Key.ToString ()) : de.Key.ToString ();
  823. if (String.Compare (name, valueName, StringComparison.InvariantCultureIgnoreCase) == 0)
  824. return values [de.Key];
  825. }
  826. return null;
  827. }
  828. /// <summary>
  829. /// Merge the current data item fields with view parameter default values
  830. /// </summary>
  831. /// <param name="viewParams">default parameters</param>
  832. /// <param name="values">new parameters for update and insert</param>
  833. /// <param name="oldValues">old parameters for update and delete</param>
  834. /// <param name="allwaysAddNewValues">true for insert, as current item is
  835. /// irrelevant for insert</param>
  836. /// <returns>merged values</returns>
  837. IOrderedDictionary MergeParameterValues (ParameterCollection viewParams, IDictionary values, IDictionary oldValues)
  838. {
  839. IOrderedDictionary parametersValues = viewParams.GetValues (context, owner);
  840. OrderedDictionary mergedValues = new OrderedDictionary (StringComparer.InvariantCultureIgnoreCase);
  841. foreach (string parameterName in parametersValues.Keys) {
  842. mergedValues [parameterName] = parametersValues [parameterName];
  843. if (oldValues != null) {
  844. object value = FindValueByName (parameterName, oldValues, true);
  845. if (value != null) {
  846. object dataValue = viewParams [parameterName].ConvertValue (value);
  847. mergedValues [parameterName] = dataValue;
  848. }
  849. }
  850. if (values != null) {
  851. object value = FindValueByName (parameterName, values, false);
  852. if (value != null) {
  853. object dataValue = viewParams [parameterName].ConvertValue (value);
  854. mergedValues [parameterName] = dataValue;
  855. }
  856. }
  857. }
  858. if (values != null) {
  859. foreach (DictionaryEntry de in values)
  860. if (FindValueByName ((string) de.Key, mergedValues, false) == null)
  861. mergedValues [de.Key] = de.Value;
  862. }
  863. if (oldValues != null) {
  864. foreach (DictionaryEntry de in oldValues) {
  865. string oldValueKey = FormatOldParameter ((string) de.Key);
  866. if (FindValueByName (oldValueKey, mergedValues, false) == null)
  867. mergedValues [oldValueKey] = de.Value;
  868. }
  869. }
  870. return mergedValues;
  871. }
  872. object[] GetParameterArray (ParameterInfo[] methodParams, IOrderedDictionary viewParams, out ArrayList outParamInfos)
  873. {
  874. // FIXME: make this case insensitive
  875. outParamInfos = null;
  876. object[] values = new object [methodParams.Length];
  877. foreach (ParameterInfo mp in methodParams) {
  878. // Parameter names must match
  879. if (!viewParams.Contains (mp.Name)) return null;
  880. values [mp.Position] = ConvertParameter (mp.ParameterType, viewParams [mp.Name]);
  881. if (mp.ParameterType.IsByRef) {
  882. if (outParamInfos == null) outParamInfos = new ArrayList ();
  883. outParamInfos.Add (mp);
  884. }
  885. }
  886. return values;
  887. }
  888. object ConvertParameter (Type targetType, object value)
  889. {
  890. return ConvertParameter (Type.GetTypeCode (targetType), value);
  891. }
  892. object ConvertParameter (TypeCode targetType, object value)
  893. {
  894. if (value == null) {
  895. if (targetType != TypeCode.Object && targetType != TypeCode.String)
  896. value = 0;
  897. else if (ConvertNullToDBNull)
  898. return DBNull.Value;
  899. }
  900. if (targetType == TypeCode.Object || targetType == TypeCode.Empty)
  901. return value;
  902. else
  903. return Convert.ChangeType (value, targetType);
  904. }
  905. string FormatOldParameter (string name)
  906. {
  907. string f = OldValuesParameterFormatString;
  908. if (f.Length > 0)
  909. return String.Format (f, name);
  910. else
  911. return name;
  912. }
  913. void OnParametersChanged (object sender, EventArgs args)
  914. {
  915. OnDataSourceViewChanged (EventArgs.Empty);
  916. }
  917. protected virtual void LoadViewState (object savedState)
  918. {
  919. object[] state = (savedState == null) ? new object [5] : (object[]) savedState;
  920. ((IStateManager)SelectParameters).LoadViewState (state[0]);
  921. ((IStateManager)UpdateParameters).LoadViewState (state[1]);
  922. ((IStateManager)DeleteParameters).LoadViewState (state[2]);
  923. ((IStateManager)InsertParameters).LoadViewState (state[3]);
  924. ((IStateManager)FilterParameters).LoadViewState (state[4]);
  925. }
  926. protected virtual object SaveViewState()
  927. {
  928. object[] state = new object [5];
  929. if (selectParameters != null)
  930. state [0] = ((IStateManager)selectParameters).SaveViewState ();
  931. if (updateParameters != null)
  932. state [1] = ((IStateManager)updateParameters).SaveViewState ();
  933. if (deleteParameters != null)
  934. state [2] = ((IStateManager)deleteParameters).SaveViewState ();
  935. if (insertParameters != null)
  936. state [3] = ((IStateManager)insertParameters).SaveViewState ();
  937. if (filterParameters != null)
  938. state [4] = ((IStateManager)filterParameters).SaveViewState ();
  939. foreach (object ob in state)
  940. if (ob != null) return state;
  941. return null;
  942. }
  943. protected virtual void TrackViewState()
  944. {
  945. isTrackingViewState = true;
  946. if (selectParameters != null) ((IStateManager)selectParameters).TrackViewState ();
  947. if (filterParameters != null) ((IStateManager)filterParameters).TrackViewState ();
  948. }
  949. protected bool IsTrackingViewState
  950. {
  951. get { return isTrackingViewState; }
  952. }
  953. bool IStateManager.IsTrackingViewState
  954. {
  955. get { return IsTrackingViewState; }
  956. }
  957. void IStateManager.TrackViewState()
  958. {
  959. TrackViewState ();
  960. }
  961. void IStateManager.LoadViewState (object savedState)
  962. {
  963. LoadViewState (savedState);
  964. }
  965. object IStateManager.SaveViewState()
  966. {
  967. return SaveViewState ();
  968. }
  969. }
  970. }
  971. #endif