PageRenderTime 32ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 1ms

/Source/facebook.Linq/Utils/Common.cs

https://bitbucket.org/assaframan/facebooklinq
C# | 942 lines | 666 code | 116 blank | 160 comment | 59 complexity | d0864ea166d9d080e19398b42980517a MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Text;
  6. using System.Reflection;
  7. using System.Collections;
  8. using System.Diagnostics;
  9. using System.Xml;
  10. using System.ComponentModel;
  11. using System.IO;
  12. namespace facebook
  13. {
  14. public class DelegatedTextWriter : TextWriter
  15. {
  16. public DelegatedTextWriter()
  17. {
  18. }
  19. public DelegatedTextWriter(Action<string> writeMethod, Action<string> writeLineMethod)
  20. {
  21. WriteMethod = writeMethod;
  22. WriteLineMethod = writeLineMethod;
  23. }
  24. void InternalWrite(string message)
  25. {
  26. if (WriteMethod != null)
  27. WriteMethod(message);
  28. }
  29. void InternalWriteLine(string message)
  30. {
  31. if (WriteMethod != null)
  32. WriteLineMethod(message);
  33. }
  34. public Action<string> WriteMethod { get; set; }
  35. public Action<string> WriteLineMethod { get; set; }
  36. public override void Write(bool value)
  37. {
  38. InternalWrite(value.ToString());
  39. }
  40. public override void Write(char value)
  41. {
  42. InternalWrite(value.ToString());
  43. }
  44. public override void Write(char[] buffer)
  45. {
  46. InternalWrite(new String(buffer));
  47. }
  48. public override void Write(decimal value)
  49. {
  50. InternalWrite(value.ToString());
  51. }
  52. public override void Write(double value)
  53. {
  54. InternalWrite(value.ToString());
  55. }
  56. public override void Write(float value)
  57. {
  58. InternalWrite(value.ToString());
  59. }
  60. public override void Write(int value)
  61. {
  62. InternalWrite(value.ToString());
  63. }
  64. public override void Write(long value)
  65. {
  66. InternalWrite(value.ToString());
  67. }
  68. public override void Write(object value)
  69. {
  70. InternalWrite(value.ToString());
  71. }
  72. public override void Write(string value)
  73. {
  74. InternalWrite(value.ToString());
  75. }
  76. public override void Write(uint value)
  77. {
  78. InternalWrite(value.ToString());
  79. }
  80. public override void Write(ulong value)
  81. {
  82. InternalWrite(value.ToString());
  83. }
  84. public override void Write(string format, object arg0)
  85. {
  86. InternalWrite(String.Format(format, arg0));
  87. }
  88. public override void Write(string format, params object[] arg)
  89. {
  90. InternalWrite(String.Format(format, arg));
  91. }
  92. public override void Write(char[] buffer, int index, int count)
  93. {
  94. InternalWrite(new String(buffer, index, count));
  95. }
  96. public override void Write(string format, object arg0, object arg1)
  97. {
  98. InternalWrite(String.Format(format, arg0, arg1));
  99. }
  100. public override void Write(string format, object arg0, object arg1, object arg2)
  101. {
  102. InternalWrite(String.Format(format, arg0, arg1, arg2));
  103. }
  104. public override void WriteLine()
  105. {
  106. InternalWriteLine(String.Empty);
  107. }
  108. public override void WriteLine(bool value)
  109. {
  110. InternalWriteLine(value.ToString());
  111. }
  112. public override void WriteLine(char value)
  113. {
  114. InternalWriteLine(value.ToString());
  115. }
  116. public override void WriteLine(char[] buffer)
  117. {
  118. InternalWriteLine(new String(buffer));
  119. }
  120. public override void WriteLine(decimal value)
  121. {
  122. InternalWriteLine(value.ToString());
  123. }
  124. public override void WriteLine(double value)
  125. {
  126. InternalWriteLine(value.ToString());
  127. }
  128. public override void WriteLine(float value)
  129. {
  130. InternalWriteLine(value.ToString());
  131. }
  132. public override void WriteLine(int value)
  133. {
  134. InternalWriteLine(value.ToString());
  135. }
  136. public override void WriteLine(long value)
  137. {
  138. InternalWriteLine(value.ToString());
  139. }
  140. public override void WriteLine(object value)
  141. {
  142. InternalWriteLine(value.ToString());
  143. }
  144. public override void WriteLine(string value)
  145. {
  146. InternalWriteLine(value);
  147. }
  148. public override void WriteLine(uint value)
  149. {
  150. InternalWriteLine(value.ToString());
  151. }
  152. public override void WriteLine(ulong value)
  153. {
  154. InternalWriteLine(value.ToString());
  155. }
  156. public override void WriteLine(string format, object arg0)
  157. {
  158. InternalWriteLine(String.Format(format, arg0));
  159. }
  160. public override void WriteLine(string format, params object[] arg)
  161. {
  162. InternalWriteLine(String.Format(format, arg));
  163. }
  164. public override void WriteLine(char[] buffer, int index, int count)
  165. {
  166. InternalWriteLine(new String(buffer, index, count));
  167. }
  168. public override void WriteLine(string format, object arg0, object arg1)
  169. {
  170. InternalWriteLine(String.Format(format, arg0, arg1));
  171. }
  172. public override void WriteLine(string format, object arg0, object arg1, object arg2)
  173. {
  174. InternalWriteLine(String.Format(format, arg0, arg1, arg2));
  175. }
  176. public override Encoding Encoding
  177. {
  178. get { return Encoding.Default; }
  179. }
  180. public override void Flush()
  181. {
  182. }
  183. public override string NewLine
  184. {
  185. get
  186. {
  187. return "\n";
  188. }
  189. set
  190. {
  191. throw new NotImplementedException("TODO: Implement");
  192. }
  193. }
  194. public override IFormatProvider FormatProvider
  195. {
  196. get
  197. {
  198. return null;
  199. }
  200. }
  201. }
  202. internal static class DateHelper
  203. {
  204. // Methods
  205. internal static double? ConvertDateToDouble(DateTime? dateToConvert)
  206. {
  207. if (!dateToConvert.HasValue)
  208. {
  209. return null;
  210. }
  211. TimeSpan span = dateToConvert.Value - BaseUTCDateTime;
  212. return new double?(span.TotalSeconds);
  213. }
  214. internal static DateTime ConvertDoubleToDate(double secondsSinceEpoch)
  215. {
  216. return TimeZone.CurrentTimeZone.ToLocalTime(BaseUTCDateTime.AddSeconds(secondsSinceEpoch));
  217. }
  218. internal static DateTime ConvertDoubleToEventDate(double secondsSinceEpoch)
  219. {
  220. DateTime time = BaseUTCDateTime.AddSeconds(secondsSinceEpoch);
  221. int num = time.IsDaylightSavingTime() ? -7 : -8;
  222. return time.AddHours((double)num);
  223. }
  224. // Properties
  225. public static DateTime BaseUTCDateTime
  226. {
  227. get
  228. {
  229. return new DateTime(1970, 1, 1, 0, 0, 0);
  230. }
  231. }
  232. }
  233. internal sealed class StringHelper
  234. {
  235. private StringHelper()
  236. {
  237. }
  238. /// <summary>
  239. /// Convert a collection of strings to a comma separated list.
  240. /// </summary>
  241. /// <param name="collection">The collection to convert to a comma separated list.</param>
  242. /// <returns>comma separated string.</returns>
  243. internal static string ConvertToCommaSeparated(IList<string> collection)
  244. {
  245. // assumed that the average string length is 10 and double the buffer multiplying by 2
  246. // if this does not fit in your case, please change the values
  247. int preAllocation = collection.Count * 10 * 2;
  248. var sb = new StringBuilder(preAllocation);
  249. int i = 0;
  250. foreach (string key in collection)
  251. {
  252. sb.Append(key);
  253. if (i < collection.Count - 1)
  254. sb.Append(",");
  255. i++;
  256. }
  257. return sb.ToString();
  258. }
  259. /// <summary>
  260. /// Convert a collection of strings to a comma separated list.
  261. /// </summary>
  262. /// <param name="collection">The collection to convert to a comma separated list.</param>
  263. /// <returns>comma separated string.</returns>
  264. internal static string ConvertToCommaSeparated(IList<int?> collection)
  265. {
  266. //assumed that the average string length is 10 and double the buffer multiplying by 2
  267. // if this does not fit in your case, please change the values
  268. int preAllocation = collection.Count * 10 * 2;
  269. var sb = new StringBuilder(preAllocation);
  270. int i = 0;
  271. foreach (int? key in collection)
  272. {
  273. sb.Append(key.ToString());
  274. if (i < collection.Count - 1)
  275. sb.Append(",");
  276. i++;
  277. }
  278. return sb.ToString();
  279. }
  280. /// <summary>
  281. /// Convert a collection of strings to a comma separated list.
  282. /// </summary>
  283. /// <param name="collection">The collection to convert to a comma separated list.</param>
  284. /// <returns>comma separated string.</returns>
  285. internal static string ConvertToCommaSeparated(IList<int> collection)
  286. {
  287. //assumed that the average string length is 10 and double the buffer multiplying by 2
  288. //if this does not fit in your case, please change the values
  289. int preAllocation = collection.Count * 10 * 2;
  290. var sb = new StringBuilder(preAllocation);
  291. int i = 0;
  292. foreach (int key in collection)
  293. {
  294. sb.Append(key.ToString());
  295. if (i < collection.Count - 1)
  296. sb.Append(",");
  297. i++;
  298. }
  299. return sb.ToString();
  300. }
  301. internal static string ConvertToCommaSeparated(IList<long> collection)
  302. {
  303. //assumed that the average string length is 10 and double the buffer multiplying by 2
  304. //if this does not fit in your case, please change the values
  305. int preAllocation = collection.Count * 10 * 2;
  306. var sb = new StringBuilder(preAllocation);
  307. int i = 0;
  308. foreach (long key in collection)
  309. {
  310. sb.Append(key.ToString());
  311. if (i < collection.Count - 1)
  312. sb.Append(",");
  313. i++;
  314. }
  315. return sb.ToString();
  316. }
  317. internal static IEnumerable<string> SplitByCaps(string text)
  318. {
  319. //TODO: use string builder
  320. var sb = new StringBuilder();
  321. bool first = true;
  322. foreach (char c in text)
  323. {
  324. if (first)
  325. first = false;
  326. else
  327. if (Char.IsUpper(c))
  328. {
  329. yield return sb.ToString();
  330. sb.Length = 0;
  331. }
  332. sb.Append(c);
  333. }
  334. if (sb.Length > 0)
  335. yield return sb.ToString();
  336. }
  337. }
  338. static class EnumerableHelper
  339. {
  340. public static Type GetEnumerableItemType(object typedEnumerable)
  341. {
  342. var type = typedEnumerable.GetType();
  343. return GetEnumerableItemType(type);
  344. }
  345. public static Type GetEnumerableItemType(Type type)
  346. {
  347. var iface = type.GetInterface("System.Collections.Generic.IEnumerable`1");
  348. if (iface != null)
  349. {
  350. var args = iface.GetGenericArguments();
  351. return args[0];
  352. }
  353. return null;
  354. }
  355. }
  356. static class Extensions
  357. {
  358. /// <summary>
  359. /// Concatenates string values that are selected from an IEnumerable (e.g CSV parameter list, with ( and ) )
  360. /// </summary>
  361. /// <typeparam name="T"></typeparam>
  362. /// <param name="list"></param>
  363. /// <param name="stringSelector"></param>
  364. /// <param name="prefix"></param>
  365. /// <param name="delim"></param>
  366. /// <param name="suffix"></param>
  367. /// <returns></returns>
  368. [DebuggerStepThrough]
  369. public static string StringConcat<T>(this IEnumerable<T> list, Func<T, string> stringSelector, string prefix, string delim, string suffix)
  370. {
  371. StringBuilder sb = new StringBuilder();
  372. if (!String.IsNullOrEmpty(prefix))
  373. sb.Append(prefix);
  374. bool first = true, hasDelim = !String.IsNullOrEmpty(delim);
  375. foreach (T item in list)
  376. {
  377. if (hasDelim)
  378. {
  379. if (first)
  380. first = false;
  381. else
  382. sb.Append(delim);
  383. }
  384. string s = stringSelector(item);
  385. if (!String.IsNullOrEmpty(s))
  386. sb.Append(s);
  387. }
  388. if (!String.IsNullOrEmpty(suffix))
  389. sb.Append(suffix);
  390. return sb.ToString();
  391. }
  392. /// <summary>
  393. /// Concatenates an IEnumerable of strings
  394. /// </summary>
  395. /// <param name="list"></param>
  396. /// <param name="prefix"></param>
  397. /// <param name="delim"></param>
  398. /// <param name="suffix"></param>
  399. /// <returns></returns>
  400. [DebuggerStepThrough]
  401. public static string StringConcat(this IEnumerable<string> list, string prefix, string delim, string suffix)
  402. {
  403. StringBuilder sb = new StringBuilder();
  404. if (!String.IsNullOrEmpty(prefix))
  405. sb.Append(prefix);
  406. bool first = true, hasDelim = !String.IsNullOrEmpty(delim);
  407. foreach (string item in list)
  408. {
  409. if (String.IsNullOrEmpty(item))
  410. continue;
  411. if (hasDelim)
  412. {
  413. if (first)
  414. first = false;
  415. else
  416. sb.Append(delim);
  417. }
  418. sb.Append(item);
  419. }
  420. if (!String.IsNullOrEmpty(suffix))
  421. sb.Append(suffix);
  422. return sb.ToString();
  423. }
  424. /// <summary>
  425. /// Concatenates an IEnumerable of strings
  426. /// </summary>
  427. /// <param name="list"></param>
  428. /// <param name="delim"></param>
  429. /// <returns></returns>
  430. [DebuggerStepThrough]
  431. public static string StringConcat(this IEnumerable<string> list, string delim)
  432. {
  433. return StringConcat(list, null, delim, null);
  434. }
  435. /// <summary>
  436. /// Returns true if the collection is empty
  437. /// </summary>
  438. /// <typeparam name="T">Collection item type</typeparam>
  439. /// <param name="collection">a collection of items</param>
  440. /// <returns>true if the collection contains no elements</returns>
  441. public static bool IsEmpty<T>(this IEnumerable<T> collection)
  442. {
  443. foreach (var i in collection)
  444. {
  445. return false;
  446. }
  447. return true;
  448. }
  449. /// <summary>
  450. /// Returns the symmetrical difference between two collections
  451. /// </summary>
  452. /// <remarks>
  453. /// Symmetrical difference is defined as the subtraction of the intersection from the union of the two collections
  454. /// </remarks>
  455. /// <typeparam name="T">Collection item type</typeparam>
  456. /// <param name="a">First collection</param>
  457. /// <param name="b">Second collection</param>
  458. /// <returns>a collection that has items that are exclusively in one of the collections</returns>
  459. public static IEnumerable<T> SymetricalDifference<T>(this IEnumerable<T> a, IEnumerable<T> b)
  460. {
  461. var union = a.Union(b);
  462. var intersection = a.Intersect(b);
  463. return union.Except(intersection);
  464. }
  465. /// <summary>
  466. /// Removes all items in Target that are not present in source, and Adds all items in Source that are not present in target
  467. /// </summary>
  468. /// <typeparam name="T"></typeparam>
  469. /// <param name="target"></param>
  470. /// <param name="source"></param>
  471. public static void SetItems<T>(this IList<T> target, IEnumerable<T> source)
  472. {
  473. var targetHash = new HashSet<T>(target);
  474. var sourceHash = new HashSet<T>(source);
  475. var toDelete = targetHash.Except(sourceHash).ToList();
  476. var toAdd = sourceHash.Except(targetHash).ToList();
  477. foreach (var d in toDelete)
  478. target.Remove(d);
  479. foreach (var a in toAdd)
  480. target.Add(a);
  481. }
  482. ///// <summary>
  483. ///// SelectSingle, but a version that can traverse non-IEnumerables, like hierarchies
  484. ///// </summary>
  485. ///// <typeparam name="T"></typeparam>
  486. ///// <typeparam name="S"></typeparam>
  487. ///// <param name="seed"></param>
  488. ///// <param name="NextSelector"></param>
  489. ///// <param name="ValueSelector"></param>
  490. ///// <returns></returns>
  491. /*public static List<S> AggregateToList<T, S>(this T seed, Func<T, T> NextSelector, Func<T, S> ValueSelector)
  492. {
  493. List<S> ret = new List<S>();
  494. while (seed != null)
  495. {
  496. ret.Add(ValueSelector(seed));
  497. seed = NextSelector(seed);
  498. }
  499. return ret;
  500. }*/
  501. /// <summary>
  502. /// Reverses a list in-place
  503. /// </summary>
  504. /// <typeparam name="T"></typeparam>
  505. /// <param name="list"></param>
  506. /// <returns></returns>
  507. public static List<T> InPlaceReverse<T>(this List<T> list)
  508. {
  509. list.Reverse();
  510. return list;
  511. }
  512. ///// <summary>
  513. ///// Maps a source collection, using a mapping function, into a new List.
  514. ///// </summary>
  515. ///// <example>
  516. ///// object[] src = new object[] {1,"2",3,"4","5"}
  517. ///// List&lt;int&gt; values = src.Map(v=>(v is int) ? (int)v : Int32.Parse(v.ToString()))
  518. ///// </example>
  519. ///// <typeparam name="T"></typeparam>
  520. ///// <typeparam name="S"></typeparam>
  521. ///// <param name="source"></param>
  522. ///// <param name="mapping"></param>
  523. ///// <returns></returns>
  524. //public static List<S> Map<T, S>(this IEnumerable<T> source, Func<T, S> mapping)
  525. //{
  526. // List<S> list = new List<S>();
  527. // if (source != null)
  528. // {
  529. // foreach (T item in source)
  530. // {
  531. // S mappedItem = mapping(item);
  532. // list.Add(mappedItem);
  533. // }
  534. // }
  535. // return list;
  536. //}
  537. /// <summary>
  538. /// Same as Map, but with a condition predicate
  539. /// </summary>
  540. /// <typeparam name="T"></typeparam>
  541. /// <typeparam name="S"></typeparam>
  542. /// <param name="source"></param>
  543. /// <param name="mapping"></param>
  544. /// <param name="condition"></param>
  545. /// <returns></returns>
  546. public static List<S> Map<T, S>(this IEnumerable<T> source, Func<T, S> mapping, Predicate<T> condition)
  547. {
  548. List<S> list = new List<S>();
  549. foreach (T item in source)
  550. {
  551. if (!condition(item))
  552. continue;
  553. S mappedItem = mapping(item);
  554. if (mappedItem != null)
  555. list.Add(mappedItem);
  556. }
  557. return list;
  558. }
  559. public static void AddRange<T>(this HashSet<T> set, IEnumerable<T> list)
  560. {
  561. foreach (T item in list)
  562. set.Add(item);
  563. }
  564. public static Dictionary<T, S> MapToDictionary<T, S>(this IEnumerable<T> source, Func<T, S> valueSelector)
  565. {
  566. Dictionary<T, S> ret = new Dictionary<T, S>();
  567. foreach (T item in source)
  568. {
  569. ret.Add(item, valueSelector(item));
  570. }
  571. return ret;
  572. }
  573. public static void RemoveKeysWithValue<T, S>(this Dictionary<T, S> source, S value)
  574. {
  575. List<T> matchingKeys = new List<T>();
  576. foreach (T key in source.Keys)
  577. {
  578. if (source[key].Equals(value))
  579. matchingKeys.Add(key);
  580. }
  581. foreach (T key in matchingKeys)
  582. source.Remove(key);
  583. }
  584. public static void KeepOnlyKeysWithValue<T, S>(this IDictionary<T, S> source, S value)
  585. {
  586. List<T> matchingKeys = new List<T>();
  587. foreach (T key in source.Keys)
  588. {
  589. if (!source[key].Equals(value))
  590. matchingKeys.Add(key);
  591. }
  592. foreach (T key in matchingKeys)
  593. source.Remove(key);
  594. }
  595. public static T TryGetValue<K, T>(this Dictionary<K, T> dictionary, K key)
  596. {
  597. T value;
  598. dictionary.TryGetValue(key, out value);
  599. return value;
  600. }
  601. public static bool IsNullOrEmpty(this string s)
  602. {
  603. return String.IsNullOrEmpty(s);
  604. }
  605. public static bool IsNotNullOrEmpty(this string s)
  606. {
  607. return !String.IsNullOrEmpty(s);
  608. }
  609. }
  610. static class ReflectionHelper
  611. {
  612. public static T GetCustomAttribute<T>(this Type type) where T : Attribute
  613. {
  614. return (T)type.GetCustomAttributes(typeof(T), false).FirstOrDefault();
  615. }
  616. public static T GetCustomAttribute<T>(this Type type, bool inherit) where T : Attribute
  617. {
  618. return (T)type.GetCustomAttributes(typeof(T), inherit).FirstOrDefault();
  619. }
  620. //public static string Get
  621. public static T CreateSpecificOrDefaultInstance<T>(string typeName, params object[] prms)
  622. {
  623. Type type;
  624. if (typeName != null)
  625. {
  626. type = Type.GetType(typeName);
  627. }
  628. else
  629. {
  630. type = typeof(T);
  631. }
  632. T instance = (T)Activator.CreateInstance(type, prms);
  633. return instance;
  634. }
  635. public static Type ClimbUp(Type type)
  636. {
  637. if (type.IsGenericType && !type.IsGenericTypeDefinition)
  638. {
  639. return type.GetGenericTypeDefinition();
  640. }
  641. return type.BaseType;
  642. }
  643. public static object GetDefaultValue(Type type)
  644. {
  645. if (type.IsValueType)
  646. {
  647. return Activator.CreateInstance(type);
  648. }
  649. else
  650. return null;
  651. }
  652. public static Type GetMemberType(MemberInfo mi)
  653. {
  654. if (mi is FieldInfo)
  655. return ((FieldInfo)mi).FieldType;
  656. return ((PropertyInfo)mi).PropertyType;
  657. }
  658. public static object GetMemberValue(MemberInfo mi, object obj)
  659. {
  660. if (mi is FieldInfo)
  661. return ((FieldInfo)mi).GetValue(obj);
  662. return ((PropertyInfo)mi).GetValue(obj, null);
  663. }
  664. public static void SetMemberValue(MemberInfo mi, object obj, object value)
  665. {
  666. if (mi is FieldInfo)
  667. ((FieldInfo)mi).SetValue(obj, value);
  668. else
  669. ((PropertyInfo)mi).SetValue(obj, value, null);
  670. }
  671. public static object CreateGenericInstance(Type type, object[] args, params Type[] genericParameters)
  672. {
  673. Type genericType = type.MakeGenericType(genericParameters);
  674. object obj = Activator.CreateInstance(genericType, args);
  675. return obj;
  676. }
  677. //private static Type _GetCollectionItemType(Type collectionType)
  678. //{
  679. // PropertyInfo[] pis = collectionType.GetProperties();
  680. // foreach (PropertyInfo pi in pis)
  681. // {
  682. // if (pi.Name == "Item")
  683. // {
  684. // return pi.PropertyType;
  685. // }
  686. // }
  687. // return null;
  688. //}
  689. //public static Type GetCollectionItemType(Type listType)
  690. //{
  691. // if (listType.IsArray)
  692. // {
  693. // return listType.GetElementType();
  694. // }
  695. // else
  696. // {
  697. // return _GetCollectionItemType(listType);
  698. // }
  699. //}
  700. //public static T GetAttributes<T>(Assembly asm)
  701. //{
  702. //}
  703. public static IList<T> GetAttributes<T>(ICustomAttributeProvider mi, bool inherit) where T : Attribute //TODO: Optimize (cache attribute access)
  704. {
  705. object[] attributes = mi.GetCustomAttributes(typeof(T), inherit);
  706. List<T> list = new List<T>();
  707. foreach (T attribute in attributes)
  708. {
  709. list.Add(attribute);
  710. }
  711. return list;
  712. }
  713. public static T GetAttribute<T>(ICustomAttributeProvider mi, bool inherit) where T : Attribute //TODO: Optimize (cache attribute access)
  714. {
  715. IList<T> list = GetAttributes<T>(mi, inherit);
  716. if (list.Count == 0)
  717. return null;
  718. return list[0];
  719. }
  720. public static T GetAttribute<T>(ICustomAttributeProvider mi) where T : Attribute //TODO: Optimize (cache attribute access)
  721. {
  722. return GetAttribute<T>(mi, true);
  723. }
  724. public static bool IsCollection(Type realType)
  725. {
  726. if (typeof(IList).IsAssignableFrom(realType))
  727. return true;
  728. return false;
  729. }
  730. public static bool IsNullable(Type type)
  731. {
  732. if (type.IsValueType)
  733. {
  734. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable))
  735. return true;
  736. return false;
  737. }
  738. return true;
  739. }
  740. public static T GetAttribute<T>(Assembly asm) where T : Attribute
  741. {
  742. object[] list = asm.GetCustomAttributes(typeof(T), false);
  743. if (list.Length > 0)
  744. return (T)list[0];
  745. return null;
  746. }
  747. public static Type GetFirstGenericType(Type type)
  748. {
  749. Type[] types = type.GetGenericArguments();
  750. if (types.Length == 0)
  751. {
  752. type = type.BaseType;
  753. if (type != null)
  754. return GetFirstGenericType(type);
  755. return null;
  756. }
  757. return types[0];
  758. }
  759. public static object InvokeMethod(object instance, string methodName, object[] prms)
  760. {
  761. MethodInfo mi = instance.GetType().GetMethod(methodName);
  762. object result = mi.Invoke(instance, prms);
  763. return result;
  764. }
  765. public static object TryInvokeMethodWithParams(object obj, string methodName, object[] prms)
  766. {
  767. var types = Type.GetTypeArray(prms);
  768. MethodInfo mi = obj.GetType().GetMethod(methodName, types);
  769. if (mi == null)
  770. return null;
  771. object result = mi.Invoke(obj, prms);
  772. return result;
  773. }
  774. //Instance
  775. public static object GetPropertyValue(object instance, string propertyName)
  776. {
  777. return instance.GetType().GetProperty(propertyName).GetValue(instance, null);
  778. }
  779. //Static
  780. public static object GetPropertyValue(Type T, string propertyName)
  781. {
  782. return T.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null, null);
  783. }
  784. public static object GetFieldValue(object instance, string fieldName)
  785. {
  786. return instance.GetType().GetField(fieldName).GetValue(instance);
  787. }
  788. public static void SetFieldValue(object obj, string fieldName, object value)
  789. {
  790. obj.GetType().GetField(fieldName).SetValue(obj, value);
  791. }
  792. public static bool IsStatic(MemberInfo mi)
  793. {
  794. PropertyInfo pi = mi as PropertyInfo;
  795. if (pi != null)
  796. {
  797. return pi.GetAccessors()[0].IsStatic;
  798. }
  799. FieldInfo fi = mi as FieldInfo;
  800. if (fi != null)
  801. {
  802. return fi.IsStatic;
  803. }
  804. throw new NotSupportedException("couldn't determine if memberinfo is static");
  805. }
  806. public static bool IsPublic(MemberInfo mi)
  807. {
  808. PropertyInfo pi = mi as PropertyInfo;
  809. if (pi != null)
  810. {
  811. return pi.GetAccessors()[0].IsPublic;
  812. }
  813. FieldInfo fi = mi as FieldInfo;
  814. if (fi != null)
  815. {
  816. return fi.IsPublic;
  817. }
  818. throw new NotSupportedException("couldn't determine if memberinfo is public");
  819. }
  820. public static bool IsDefaultValue(Type type, object value)
  821. {
  822. var def = GetDefaultValue(type);
  823. return Object.Equals(def, value);
  824. }
  825. }
  826. }