ObjectDataSourceView.cs 36 KB

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