ObjectDataSourceView.cs 37 KB

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