ObjectDataSourceView.cs 35 KB

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