ObjectDataSourceView.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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. }
  269. }
  270. public string DeleteMethod {
  271. get {
  272. return deleteMethod != null ? deleteMethod : string.Empty;
  273. }
  274. set {
  275. deleteMethod = value;
  276. }
  277. }
  278. public ParameterCollection DeleteParameters {
  279. get {
  280. if (deleteParameters == null) {
  281. deleteParameters = new ParameterCollection ();
  282. deleteParameters.ParametersChanged += new EventHandler (OnParametersChanged);
  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. insertParameters.ParametersChanged += new EventHandler (OnParametersChanged);
  327. }
  328. return insertParameters;
  329. }
  330. }
  331. public string MaximumRowsParameterName {
  332. get {
  333. return maximumRowsParameterName != null ? maximumRowsParameterName : "maximumRows";
  334. }
  335. set {
  336. maximumRowsParameterName = value;
  337. }
  338. }
  339. public string OldValuesParameterFormatString {
  340. get {
  341. return oldValuesParameterFormatString != null ? oldValuesParameterFormatString : "{0}";
  342. }
  343. set {
  344. oldValuesParameterFormatString = value;
  345. }
  346. }
  347. public string SelectCountMethod {
  348. get {
  349. return selectCountMethod != null ? selectCountMethod : string.Empty;
  350. }
  351. set {
  352. selectCountMethod = value;
  353. }
  354. }
  355. public string SelectMethod {
  356. get {
  357. return selectMethod != null ? selectMethod : string.Empty;
  358. }
  359. set {
  360. selectMethod = value;
  361. }
  362. }
  363. public ParameterCollection SelectParameters {
  364. get {
  365. if (selectParameters == null) {
  366. selectParameters = new ParameterCollection ();
  367. selectParameters.ParametersChanged += new EventHandler (OnParametersChanged);
  368. if (IsTrackingViewState)
  369. ((IStateManager)selectParameters).TrackViewState ();
  370. }
  371. return selectParameters;
  372. }
  373. }
  374. public string SortParameterName {
  375. get {
  376. return sortParameterName != null ? sortParameterName : string.Empty;
  377. }
  378. set {
  379. sortParameterName = value;
  380. }
  381. }
  382. public string StartRowIndexParameterName {
  383. get {
  384. return startRowIndexParameterName != null ? startRowIndexParameterName : "startRowIndex";
  385. }
  386. set {
  387. startRowIndexParameterName = value;
  388. }
  389. }
  390. public string TypeName {
  391. get {
  392. return typeName != null ? typeName : string.Empty;
  393. }
  394. set {
  395. typeName = value;
  396. objectType = null;
  397. }
  398. }
  399. public string UpdateMethod {
  400. get {
  401. return updateMethod != null ? updateMethod : string.Empty;
  402. }
  403. set {
  404. updateMethod = value;
  405. }
  406. }
  407. public ParameterCollection UpdateParameters {
  408. get {
  409. if (updateParameters == null) {
  410. updateParameters = new ParameterCollection ();
  411. updateParameters.ParametersChanged += new EventHandler (OnParametersChanged);
  412. }
  413. return updateParameters;
  414. }
  415. }
  416. private static string PrivateBinPath {
  417. get {
  418. if (privateBinPath != null)
  419. return privateBinPath;
  420. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  421. privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
  422. return privateBinPath;
  423. }
  424. }
  425. private Type LoadType (string typeName)
  426. {
  427. Type type = Type.GetType (typeName);
  428. if (type != null)
  429. return type;
  430. #if !TARGET_JVM
  431. IList tla;
  432. if ((tla = BuildManager.TopLevelAssemblies) != null) {
  433. foreach (Assembly asm in tla) {
  434. if (asm == null)
  435. continue;
  436. type = asm.GetType (typeName);
  437. if (type != null)
  438. return type;
  439. }
  440. }
  441. #endif
  442. if (!Directory.Exists (PrivateBinPath))
  443. return null;
  444. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  445. foreach (string s in binDlls) {
  446. Assembly binA = Assembly.LoadFrom (s);
  447. type = binA.GetType (typeName);
  448. if (type == null)
  449. continue;
  450. return type;
  451. }
  452. return null;
  453. }
  454. Type ObjectType {
  455. get {
  456. if (objectType == null) {
  457. objectType = LoadType (TypeName);
  458. if (objectType == null)
  459. throw new InvalidOperationException ("Type not found: " + TypeName);
  460. }
  461. return objectType;
  462. }
  463. }
  464. Type DataObjectType {
  465. get {
  466. if (dataObjectType == null) {
  467. dataObjectType = LoadType (DataObjectTypeName);
  468. if (objectType == null)
  469. throw new InvalidOperationException ("Type not found: " + DataObjectTypeName);
  470. }
  471. return dataObjectType;
  472. }
  473. }
  474. public IEnumerable Select (DataSourceSelectArguments arguments)
  475. {
  476. return ExecuteSelect (arguments);
  477. }
  478. public int Update (IDictionary keys, IDictionary values, IDictionary oldValues)
  479. {
  480. return ExecuteUpdate (keys, values, oldValues);
  481. }
  482. public int Delete (IDictionary keys, IDictionary oldValues)
  483. {
  484. return ExecuteDelete (keys, oldValues);
  485. }
  486. public int Insert (IDictionary values)
  487. {
  488. return ExecuteInsert (values);
  489. }
  490. protected override int ExecuteInsert (IDictionary values)
  491. {
  492. if (!CanInsert)
  493. throw new NotSupportedException ("Insert operation not supported.");
  494. IOrderedDictionary paramValues;
  495. MethodInfo method;
  496. if (DataObjectTypeName.Length == 0) {
  497. paramValues = MergeParameterValues (InsertParameters, values, null, true);
  498. method = GetObjectMethod (InsertMethod, paramValues, DataObjectMethodType.Insert);
  499. } else {
  500. method = ResolveDataObjectMethod (InsertMethod, values, null, out paramValues);
  501. }
  502. ObjectDataSourceMethodEventArgs args = new ObjectDataSourceMethodEventArgs (paramValues);
  503. OnInserting (args);
  504. if (args.Cancel)
  505. return -1;
  506. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  507. OnInserted (rargs);
  508. if (rargs.Exception != null && !rargs.ExceptionHandled)
  509. throw rargs.Exception;
  510. if (owner.EnableCaching)
  511. owner.Cache.Expire ();
  512. OnDataSourceViewChanged (EventArgs.Empty);
  513. return -1;
  514. }
  515. protected override int ExecuteDelete (IDictionary keys, IDictionary oldValues)
  516. {
  517. if (!CanDelete)
  518. throw new NotSupportedException ("Delete operation not supported.");
  519. if (ConflictDetection == ConflictOptions.CompareAllValues && (oldValues == null || oldValues.Count == 0))
  520. throw new InvalidOperationException ("ConflictDetection is set to CompareAllValues and oldValues collection is null or empty.");
  521. IDictionary oldDataValues;
  522. oldDataValues = BuildOldValuesList (keys, oldValues, false);
  523. IOrderedDictionary paramValues;
  524. MethodInfo method;
  525. if (DataObjectTypeName.Length == 0) {
  526. paramValues = MergeParameterValues (DeleteParameters, null, oldDataValues, true);
  527. method = GetObjectMethod (DeleteMethod, paramValues, DataObjectMethodType.Delete);
  528. } else {
  529. method = ResolveDataObjectMethod (DeleteMethod, oldDataValues, null, out paramValues);
  530. }
  531. ObjectDataSourceMethodEventArgs args = new ObjectDataSourceMethodEventArgs (paramValues);
  532. OnDeleting (args);
  533. if (args.Cancel)
  534. return -1;
  535. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  536. OnDeleted (rargs);
  537. if (rargs.Exception != null && !rargs.ExceptionHandled)
  538. throw rargs.Exception;
  539. if (owner.EnableCaching)
  540. owner.Cache.Expire ();
  541. OnDataSourceViewChanged (EventArgs.Empty);
  542. return -1;
  543. }
  544. protected override int ExecuteUpdate (IDictionary keys, IDictionary values, IDictionary oldValues)
  545. {
  546. IOrderedDictionary paramValues;
  547. MethodInfo method;
  548. IDictionary oldDataValues;
  549. oldDataValues = BuildOldValuesList (keys, oldValues, true);
  550. if (DataObjectTypeName.Length == 0)
  551. {
  552. IDictionary dataValues;
  553. dataValues = values;
  554. paramValues = MergeParameterValues (UpdateParameters, dataValues, oldDataValues, false);
  555. method = GetObjectMethod (UpdateMethod, paramValues, DataObjectMethodType.Update);
  556. }
  557. else
  558. {
  559. if (ConflictDetection != ConflictOptions.CompareAllValues) {
  560. oldDataValues = null;
  561. }
  562. IDictionary dataValues = new Hashtable ();
  563. if (keys != null) {
  564. foreach (DictionaryEntry de in keys)
  565. dataValues [de.Key] = de.Value;
  566. }
  567. if (values != null) {
  568. foreach (DictionaryEntry de in values)
  569. dataValues [de.Key] = de.Value;
  570. }
  571. method = ResolveDataObjectMethod (UpdateMethod, dataValues, oldDataValues, out paramValues);
  572. }
  573. ObjectDataSourceMethodEventArgs args = new ObjectDataSourceMethodEventArgs (paramValues);
  574. OnUpdating (args);
  575. if (args.Cancel)
  576. return -1;
  577. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  578. OnUpdated (rargs);
  579. if (rargs.Exception != null && !rargs.ExceptionHandled)
  580. throw rargs.Exception;
  581. if (owner.EnableCaching)
  582. owner.Cache.Expire ();
  583. OnDataSourceViewChanged (EventArgs.Empty);
  584. return -1;
  585. }
  586. private IDictionary BuildOldValuesList (IDictionary keys, IDictionary oldValues, bool keysWin)
  587. {
  588. IDictionary oldDataValues;
  589. if (ConflictDetection == ConflictOptions.CompareAllValues) {
  590. oldDataValues = new Hashtable ();
  591. if (keys != null && !keysWin) {
  592. foreach (DictionaryEntry de in keys)
  593. oldDataValues [de.Key] = de.Value;
  594. }
  595. if (oldValues != null) {
  596. foreach (DictionaryEntry de in oldValues)
  597. oldDataValues [de.Key] = de.Value;
  598. }
  599. if (keys != null && keysWin) {
  600. foreach (DictionaryEntry de in keys)
  601. oldDataValues [de.Key] = de.Value;
  602. }
  603. }
  604. else {
  605. oldDataValues = keys;
  606. }
  607. return oldDataValues;
  608. }
  609. protected internal override IEnumerable ExecuteSelect (DataSourceSelectArguments arguments)
  610. {
  611. arguments.RaiseUnsupportedCapabilitiesError (this);
  612. IOrderedDictionary paramValues = MergeParameterValues (SelectParameters, null, null, true);
  613. ObjectDataSourceSelectingEventArgs args = new ObjectDataSourceSelectingEventArgs (paramValues, arguments, false);
  614. object result = null;
  615. if (owner.EnableCaching)
  616. result = owner.Cache.GetCachedObject (SelectMethod, SelectParameters);
  617. if (result == null) {
  618. OnSelecting (args);
  619. if (args.Cancel)
  620. return new ArrayList ();
  621. if (CanRetrieveTotalRowCount && arguments.RetrieveTotalRowCount)
  622. arguments.TotalRowCount = QueryTotalRowCount (paramValues, arguments);
  623. if (CanPage) {
  624. if (StartRowIndexParameterName.Length == 0)
  625. throw new InvalidOperationException ("Paging is enabled, but the StartRowIndexParameterName property is not set.");
  626. if (MaximumRowsParameterName.Length == 0)
  627. throw new InvalidOperationException ("Paging is enabled, but the MaximumRowsParameterName property is not set.");
  628. paramValues [StartRowIndexParameterName] = arguments.StartRowIndex;
  629. paramValues [MaximumRowsParameterName] = arguments.MaximumRows;
  630. }
  631. if (SortParameterName.Length > 0)
  632. paramValues [SortParameterName] = arguments.SortExpression;
  633. result = InvokeSelect (SelectMethod, paramValues);
  634. if (owner.EnableCaching)
  635. owner.Cache.SetCachedObject (SelectMethod, SelectParameters, result);
  636. }
  637. if (FilterExpression.Length > 0 && !(result is DataGrid || result is DataView || result is DataTable))
  638. throw new NotSupportedException ("The FilterExpression property was set and the Select method does not return a DataSet, DataTable, or DataView.");
  639. if (owner.EnableCaching && result is IDataReader)
  640. throw new NotSupportedException ("Data source does not support caching objects that implement IDataReader");
  641. if (result is DataSet) {
  642. DataSet dset = (DataSet) result;
  643. if (dset.Tables.Count == 0)
  644. throw new InvalidOperationException ("The select method returnet a DataSet which doesn't contain any table.");
  645. result = dset.Tables [0];
  646. }
  647. if (result is DataTable) {
  648. DataView dview = new DataView ((DataTable)result);
  649. if (arguments.SortExpression != null && arguments.SortExpression.Length > 0) {
  650. dview.Sort = arguments.SortExpression;
  651. }
  652. if (FilterExpression.Length > 0) {
  653. IOrderedDictionary fparams = FilterParameters.GetValues (context, owner);
  654. ObjectDataSourceFilteringEventArgs fargs = new ObjectDataSourceFilteringEventArgs (fparams);
  655. OnFiltering (fargs);
  656. if (!fargs.Cancel) {
  657. object[] formatValues = new object [fparams.Count];
  658. for (int n=0; n<formatValues.Length; n++) {
  659. formatValues [n] = fparams [n];
  660. if (formatValues [n] == null) return dview;
  661. }
  662. dview.RowFilter = string.Format (FilterExpression, formatValues);
  663. }
  664. }
  665. return dview;
  666. }
  667. if (result is IEnumerable)
  668. return (IEnumerable) result;
  669. else
  670. return new object[] { result };
  671. }
  672. int QueryTotalRowCount (IOrderedDictionary mergedParameters, DataSourceSelectArguments arguments)
  673. {
  674. ObjectDataSourceSelectingEventArgs countArgs = new ObjectDataSourceSelectingEventArgs (mergedParameters, arguments, true);
  675. OnSelecting (countArgs);
  676. if (countArgs.Cancel)
  677. return 0;
  678. object count = InvokeSelect (SelectCountMethod, mergedParameters);
  679. return (int) Convert.ChangeType (count, typeof(int));
  680. }
  681. object InvokeSelect (string methodName, IOrderedDictionary paramValues)
  682. {
  683. MethodInfo method = GetObjectMethod (methodName, paramValues, DataObjectMethodType.Select);
  684. ObjectDataSourceStatusEventArgs rargs = InvokeMethod (method, paramValues);
  685. OnSelected (rargs);
  686. if (rargs.Exception != null && !rargs.ExceptionHandled)
  687. throw rargs.Exception;
  688. return rargs.ReturnValue;
  689. }
  690. ObjectDataSourceStatusEventArgs InvokeMethod (MethodInfo method, IOrderedDictionary paramValues)
  691. {
  692. object instance = null;
  693. if (!method.IsStatic)
  694. instance = CreateObjectInstance ();
  695. ParameterInfo[] pars = method.GetParameters ();
  696. ArrayList outParamInfos;
  697. object[] methodArgs = GetParameterArray (pars, paramValues, out outParamInfos);
  698. if (methodArgs == null)
  699. throw CreateMethodException (method.Name, paramValues);
  700. object result = null;
  701. Hashtable outParams = null;
  702. try {
  703. result = method.Invoke (instance, methodArgs);
  704. if (outParamInfos != null) {
  705. outParams = new Hashtable ();
  706. foreach (ParameterInfo op in outParamInfos)
  707. outParams [op.Name] = methodArgs [op.Position];
  708. }
  709. return new ObjectDataSourceStatusEventArgs (result, outParams, null);
  710. }
  711. catch (Exception ex) {
  712. return new ObjectDataSourceStatusEventArgs (result, outParams, ex);
  713. }
  714. finally {
  715. if (instance != null)
  716. DisposeObjectInstance (instance);
  717. }
  718. }
  719. MethodInfo GetObjectMethod (string methodName, IOrderedDictionary parameters, DataObjectMethodType methodType)
  720. {
  721. MemberInfo[] methods = ObjectType.GetMember (methodName, MemberTypes.Method, BindingFlags.Instance |
  722. BindingFlags.Static |
  723. BindingFlags.Public |
  724. BindingFlags.IgnoreCase |
  725. BindingFlags.FlattenHierarchy);
  726. if (methods.Length > 1) {
  727. // MSDN: The ObjectDataSource resolves method overloads by method name and number
  728. // of parameters; the names and types of the parameters are not considered.
  729. // LAMESPEC: the tests show otherwise
  730. DataObjectMethodAttribute methodAttribute = null;
  731. MethodInfo methodInfo = null;
  732. bool hasConflict = false;
  733. foreach (MethodInfo me in methods) { // we look for methods only
  734. ParameterInfo [] pinfos = me.GetParameters ();
  735. if (pinfos.Length == parameters.Count) {
  736. object [] attrs = me.GetCustomAttributes (typeof (DataObjectMethodAttribute), true);
  737. DataObjectMethodAttribute domAttr = (attrs != null && attrs.Length > 0) ? (DataObjectMethodAttribute) attrs [0] : null;
  738. if (domAttr != null && domAttr.MethodType != methodType)
  739. continue;
  740. bool paramsMatch = true;
  741. foreach (ParameterInfo pinfo in pinfos) {
  742. if (!parameters.Contains (pinfo.Name)) {
  743. paramsMatch = false;
  744. break;
  745. }
  746. }
  747. if (!paramsMatch)
  748. continue;
  749. if (domAttr != null) {
  750. if (methodAttribute != null) {
  751. if (methodAttribute.IsDefault) {
  752. if (domAttr.IsDefault) {
  753. methodInfo = null;
  754. break; //fail due to a conflict
  755. }
  756. else
  757. continue; //existing matches better
  758. }
  759. else {
  760. methodInfo = null; //we override
  761. hasConflict = !domAttr.IsDefault;
  762. }
  763. }
  764. else
  765. methodInfo = null; //we override
  766. }
  767. if (methodInfo == null) {
  768. methodAttribute = domAttr;
  769. methodInfo = me;
  770. continue;
  771. }
  772. hasConflict = true;
  773. }
  774. }
  775. if (!hasConflict && methodInfo != null)
  776. return methodInfo;
  777. }
  778. else if (methods.Length == 1) {
  779. MethodInfo me = methods[0] as MethodInfo;
  780. if (me != null && me.GetParameters().Length == parameters.Count)
  781. return me;
  782. }
  783. throw CreateMethodException (methodName, parameters);
  784. }
  785. MethodInfo ResolveDataObjectMethod (string methodName, IDictionary values, IDictionary oldValues, out IOrderedDictionary paramValues)
  786. {
  787. MethodInfo method;
  788. if (oldValues != null)
  789. method = ObjectType.GetMethod (methodName, new Type[] { DataObjectType, DataObjectType });
  790. else
  791. method = ObjectType.GetMethod (methodName, new Type[] { DataObjectType });
  792. if (method == null)
  793. throw new InvalidOperationException ("ObjectDataSource " + owner.ID + " could not find a method named '" + methodName + "' with parameters of type '" + DataObjectType + "' in '" + ObjectType + "'.");
  794. paramValues = new OrderedDictionary (StringComparer.InvariantCultureIgnoreCase);
  795. ParameterInfo[] ps = method.GetParameters ();
  796. if (oldValues != null) {
  797. if (FormatOldParameter (ps[0].Name) == ps[1].Name) {
  798. paramValues [ps[0].Name] = CreateDataObject (values);
  799. paramValues [ps[1].Name] = CreateDataObject (oldValues);
  800. } else if (FormatOldParameter (ps[1].Name) == ps[0].Name) {
  801. paramValues [ps[0].Name] = CreateDataObject (oldValues);
  802. paramValues [ps[1].Name] = CreateDataObject (values);
  803. } else
  804. throw new InvalidOperationException ("Method '" + methodName + "' does not have any parameter that fits the value of OldValuesParameterFormatString.");
  805. } else {
  806. paramValues [ps[0].Name] = CreateDataObject (values);
  807. }
  808. return method;
  809. }
  810. Exception CreateMethodException (string methodName, IOrderedDictionary parameters)
  811. {
  812. string s = "";
  813. foreach (string p in parameters.Keys) {
  814. s += p + ", ";
  815. }
  816. return new InvalidOperationException ("ObjectDataSource " + owner.ID + " could not find a method named '" + methodName + "' with parameters " + s + "in type '" + ObjectType + "'.");
  817. }
  818. object CreateDataObject (IDictionary values)
  819. {
  820. object ob = Activator.CreateInstance (DataObjectType);
  821. foreach (DictionaryEntry de in values) {
  822. PropertyInfo p = DataObjectType.GetProperty ((string)de.Key);
  823. if (p == null) throw new InvalidOperationException ("Property " + de.Key + " not found in type '" +DataObjectType + "'.");
  824. p.SetValue (ob, ConvertParameter (p.PropertyType, de.Value), null);
  825. }
  826. return ob;
  827. }
  828. object CreateObjectInstance ()
  829. {
  830. ObjectDataSourceEventArgs args = new ObjectDataSourceEventArgs (null);
  831. OnObjectCreating (args);
  832. if (args.ObjectInstance != null)
  833. return args.ObjectInstance;
  834. object ob = Activator.CreateInstance (ObjectType);
  835. args.ObjectInstance = ob;
  836. OnObjectCreated (args);
  837. return args.ObjectInstance;
  838. }
  839. void DisposeObjectInstance (object obj)
  840. {
  841. ObjectDataSourceDisposingEventArgs args = new ObjectDataSourceDisposingEventArgs (obj);
  842. OnObjectDisposing (args);
  843. if (!args.Cancel) {
  844. IDisposable disp = obj as IDisposable;
  845. if (disp != null) disp.Dispose ();
  846. }
  847. }
  848. object FindValueByName (string name, IDictionary values, bool format)
  849. {
  850. if (values == null)
  851. return null;
  852. foreach (DictionaryEntry de in values) {
  853. string valueName = format == true ? FormatOldParameter (de.Key.ToString ()) : de.Key.ToString ();
  854. if (name == valueName)
  855. return values [de.Key];
  856. }
  857. foreach (DictionaryEntry de in values) {
  858. string valueName = format == true ? FormatOldParameter (de.Key.ToString ()) : de.Key.ToString ();
  859. valueName = valueName.ToLower ();
  860. if (name.ToLower () == valueName)
  861. return values [de.Key];
  862. }
  863. return null;
  864. }
  865. /// <summary>
  866. /// Merge the current data item fields with view parameter default values
  867. /// </summary>
  868. /// <param name="viewParams">default parameters</param>
  869. /// <param name="values">new parameters for update and insert</param>
  870. /// <param name="oldValues">old parameters for update and delete</param>
  871. /// <param name="allwaysAddNewValues">true for insert, as current item is
  872. /// irrelevant for insert</param>
  873. /// <returns>merged values</returns>
  874. IOrderedDictionary MergeParameterValues (ParameterCollection viewParams, IDictionary values, IDictionary oldValues, bool allwaysAddNewValues)
  875. {
  876. OrderedDictionary mergedValues = new OrderedDictionary (StringComparer.InvariantCultureIgnoreCase);
  877. foreach (Parameter p in viewParams) {
  878. bool oldAdded = false;
  879. if (oldValues != null) {
  880. object value = FindValueByName (p.Name, oldValues, true);
  881. if (value != null) {
  882. object dataValue = p.ConvertValue (value);
  883. mergedValues [p.Name] = dataValue;
  884. oldAdded = true;
  885. }
  886. }
  887. bool newAdded = false;
  888. if (values != null) {
  889. object value = FindValueByName (p.Name, values, false);
  890. if (value != null) {
  891. object dataValue = p.ConvertValue (value);
  892. mergedValues [p.Name] = dataValue;
  893. newAdded = true;
  894. }
  895. }
  896. if ((!newAdded && !oldAdded) || allwaysAddNewValues) {
  897. object val = p.GetValue (context, owner);
  898. mergedValues [p.Name] = val;
  899. }
  900. }
  901. if (values != null) {
  902. foreach (DictionaryEntry de in values)
  903. if (FindValueByName ((string) de.Key, mergedValues, false) == null)
  904. mergedValues [de.Key] = de.Value;
  905. }
  906. if (oldValues != null) {
  907. foreach (DictionaryEntry de in oldValues)
  908. if (FindValueByName ((string) de.Key, mergedValues, true) == null)
  909. mergedValues [FormatOldParameter ((string) de.Key)] = de.Value;
  910. }
  911. return mergedValues;
  912. }
  913. object[] GetParameterArray (ParameterInfo[] methodParams, IOrderedDictionary viewParams, out ArrayList outParamInfos)
  914. {
  915. // FIXME: make this case insensitive
  916. outParamInfos = null;
  917. object[] values = new object [methodParams.Length];
  918. foreach (ParameterInfo mp in methodParams) {
  919. // Parameter names must match
  920. if (!viewParams.Contains (mp.Name)) return null;
  921. values [mp.Position] = ConvertParameter (mp.ParameterType, viewParams [mp.Name]);
  922. if (mp.ParameterType.IsByRef) {
  923. if (outParamInfos == null) outParamInfos = new ArrayList ();
  924. outParamInfos.Add (mp);
  925. }
  926. }
  927. return values;
  928. }
  929. object ConvertParameter (Type targetType, object value)
  930. {
  931. return ConvertParameter (Type.GetTypeCode (targetType), value);
  932. }
  933. object ConvertParameter (TypeCode targetType, object value)
  934. {
  935. if (value == null) {
  936. if (targetType != TypeCode.Object && targetType != TypeCode.String)
  937. value = 0;
  938. else if (ConvertNullToDBNull)
  939. return DBNull.Value;
  940. }
  941. if (targetType == TypeCode.Object || targetType == TypeCode.Empty)
  942. return value;
  943. else
  944. return Convert.ChangeType (value, targetType);
  945. }
  946. string FormatOldParameter (string name)
  947. {
  948. string f = OldValuesParameterFormatString;
  949. if (f.Length > 0)
  950. return String.Format (f, name);
  951. else
  952. return name;
  953. }
  954. void OnParametersChanged (object sender, EventArgs args)
  955. {
  956. OnDataSourceViewChanged (EventArgs.Empty);
  957. }
  958. protected virtual void LoadViewState (object savedState)
  959. {
  960. object[] state = (savedState == null) ? new object [5] : (object[]) savedState;
  961. ((IStateManager)SelectParameters).LoadViewState (state[0]);
  962. ((IStateManager)UpdateParameters).LoadViewState (state[1]);
  963. ((IStateManager)DeleteParameters).LoadViewState (state[2]);
  964. ((IStateManager)InsertParameters).LoadViewState (state[3]);
  965. ((IStateManager)FilterParameters).LoadViewState (state[4]);
  966. }
  967. protected virtual object SaveViewState()
  968. {
  969. object[] state = new object [5];
  970. if (selectParameters != null)
  971. state [0] = ((IStateManager)selectParameters).SaveViewState ();
  972. if (updateParameters != null)
  973. state [1] = ((IStateManager)updateParameters).SaveViewState ();
  974. if (deleteParameters != null)
  975. state [2] = ((IStateManager)deleteParameters).SaveViewState ();
  976. if (insertParameters != null)
  977. state [3] = ((IStateManager)insertParameters).SaveViewState ();
  978. if (filterParameters != null)
  979. state [4] = ((IStateManager)filterParameters).SaveViewState ();
  980. foreach (object ob in state)
  981. if (ob != null) return state;
  982. return null;
  983. }
  984. protected virtual void TrackViewState()
  985. {
  986. isTrackingViewState = true;
  987. if (selectParameters != null) ((IStateManager)selectParameters).TrackViewState ();
  988. if (filterParameters != null) ((IStateManager)filterParameters).TrackViewState ();
  989. }
  990. protected bool IsTrackingViewState
  991. {
  992. get { return isTrackingViewState; }
  993. }
  994. bool IStateManager.IsTrackingViewState
  995. {
  996. get { return IsTrackingViewState; }
  997. }
  998. void IStateManager.TrackViewState()
  999. {
  1000. TrackViewState ();
  1001. }
  1002. void IStateManager.LoadViewState (object savedState)
  1003. {
  1004. LoadViewState (savedState);
  1005. }
  1006. object IStateManager.SaveViewState()
  1007. {
  1008. return SaveViewState ();
  1009. }
  1010. }
  1011. }
  1012. #endif