Advertisement
Guest User

Untitled

a guest
May 9th, 2016
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Linq;
  5. using EasyNetQ;
  6. using EasyNetQ.ConnectionString;
  7. using EasyNetQ.Consumer;
  8. using EasyNetQ.Interception;
  9. using EasyNetQ.Loggers;
  10. using EasyNetQ.Producer;
  11. using EasyNetQ.Scheduling;
  12.  
  13. namespace EasyNetQAvoidStaticFactory
  14. {
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. var app = new Application();
  20. app.Run();
  21. }
  22. }
  23.  
  24. public class Application
  25. {
  26. public void Run()
  27. {
  28. //var bus = RabbitHutch.CreateBus("host=localhost", x => x.Register<IEasyNetQLogger>(s => new ConsoleLogger()));
  29. //var bus = CreateBus("host=localhost");
  30. var bus = new RabbitHutch().CreateBus("host=localhost", x => x.Register<IEasyNetQLogger>(s => new ConsoleLogger()));
  31.  
  32. Console.ReadLine();
  33.  
  34. bus.Dispose();
  35. }
  36.  
  37. // this is probably the smallest method you can create to instantiate an IBus
  38. // otherwise you can copy and paste the RabbitHutch+Preconditions
  39. // removing all the static keyword as follow
  40. private IBus CreateBus(string connectionString)
  41. {
  42. var container = new DefaultServiceProvider();
  43.  
  44. container
  45. .Register<IContainer>(_ => container)
  46. .Register<IEasyNetQLogger, ConsoleLogger>() // <---- use NullLogger or custom loger if you want to suppress the console logger
  47. .Register<ISerializer, JsonSerializer>()
  48. .Register<IConventions, Conventions>()
  49. .Register<IEventBus, EventBus>()
  50. .Register<ITypeNameSerializer, TypeNameSerializer>()
  51. .Register<ICorrelationIdGenerationStrategy, DefaultCorrelationIdGenerationStrategy>()
  52. .Register<IMessageSerializationStrategy, DefaultMessageSerializationStrategy>()
  53. .Register<IMessageDeliveryModeStrategy, MessageDeliveryModeStrategy>()
  54. .Register<ITimeoutStrategy, TimeoutStrategy>()
  55. .Register<IClusterHostSelectionStrategy<ConnectionFactoryInfo>, RandomClusterHostSelectionStrategy<ConnectionFactoryInfo>>()
  56. .Register<IProduceConsumeInterceptor, DefaultInterceptor>()
  57. .Register<IConsumerDispatcherFactory, ConsumerDispatcherFactory>()
  58. .Register<IPublishExchangeDeclareStrategy, PublishExchangeDeclareStrategy>()
  59. .Register<IConsumerErrorStrategy, DefaultConsumerErrorStrategy>()
  60. .Register<IErrorMessageSerializer, DefaultErrorMessageSerializer>()
  61. .Register<IHandlerRunner, HandlerRunner>()
  62. .Register<IInternalConsumerFactory, InternalConsumerFactory>()
  63. .Register<IConsumerFactory, ConsumerFactory>()
  64. .Register<IConnectionFactory, ConnectionFactoryWrapper>()
  65. .Register<IPersistentChannelFactory, PersistentChannelFactory>()
  66. .Register<IClientCommandDispatcherFactory, ClientCommandDispatcherFactory>()
  67. .Register<IPublishConfirmationListener, PublishConfirmationListener>()
  68. .Register<IHandlerCollectionFactory, HandlerCollectionFactory>()
  69. .Register<IAdvancedBus, RabbitAdvancedBus>()
  70. .Register<IRpc, Rpc>()
  71. .Register<ISendReceive, SendReceive>()
  72. .Register<IScheduler, ExternalScheduler>()
  73. .Register<IBus, RabbitBus>();
  74.  
  75. var connectionStringParser = new ConnectionStringParser();
  76. var connectionConfiguration = connectionStringParser.Parse(connectionString);
  77. connectionConfiguration.Validate();
  78. container.Register(_ => connectionConfiguration);
  79. container.Register(_ => new AdvancedBusEventHandlers());
  80.  
  81. return container.Resolve<IBus>();
  82. }
  83. }
  84.  
  85. /// <summary>
  86. /// Static methods to create EasyNetQ core APIs.
  87. /// </summary>
  88. public class RabbitHutch
  89. {
  90. private Func<IContainer> createContainerInternal = () => new DefaultServiceProvider();
  91. private Preconditions Preconditions = new Preconditions();
  92.  
  93. /// <summary>
  94. /// Set the container creation function. This allows you to replace EasyNetQ's default internal
  95. /// IoC container. Note that all components should be registered as singletons. EasyNetQ will
  96. /// also call Dispose on components that are no longer required.
  97. /// </summary>
  98. public void SetContainerFactory(Func<IContainer> createContainer)
  99. {
  100. Preconditions.CheckNotNull(createContainer, "createContainer");
  101.  
  102. createContainerInternal = createContainer;
  103. }
  104.  
  105. /// <summary>
  106. /// Creates a new instance of <see cref="RabbitBus"/>.
  107. /// The RabbitMQ broker is defined in the connection string named 'rabbit'.
  108. /// </summary>
  109. /// <returns>
  110. /// A new <see cref="RabbitBus"/> instance.
  111. /// </returns>
  112. public IBus CreateBus()
  113. {
  114. return CreateBus(c => { });
  115. }
  116.  
  117. /// <summary>
  118. /// Creates a new instance of <see cref="RabbitBus"/>.
  119. /// The RabbitMQ broker is defined in the connection string named 'rabbit'.
  120. /// </summary>
  121. /// <param name="registerServices">
  122. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  123. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  124. /// </param>
  125. /// <returns>
  126. /// A new <see cref="RabbitBus"/> instance.
  127. /// </returns>
  128. public IBus CreateBus(Action<IServiceRegister> registerServices)
  129. {
  130. return CreateBus(AdvancedBusEventHandlers.Default, registerServices);
  131. }
  132.  
  133. /// <summary>
  134. /// Creates a new instance of <see cref="RabbitBus"/>.
  135. /// The RabbitMQ broker is defined in the connection string named 'rabbit'.
  136. /// </summary>
  137. /// <param name="advancedBusEventHandlers">
  138. /// An <see cref="AdvancedBusEventHandlers"/> instance which is used to add handlers
  139. /// to the events of the newly created <see cref="IBus.Advanced"/>.
  140. /// As <see cref="RabbitAdvancedBus"/> attempts to connect during instantiation, specifying a <see cref="AdvancedBusEventHandlers"/>
  141. /// before instantiation is the only way to catch the first <see cref="AdvancedBusEventHandlers.Connected"/> event.
  142. /// </param>
  143. /// <param name="registerServices">
  144. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  145. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  146. /// </param>
  147. /// <returns>
  148. /// A new <see cref="RabbitBus"/> instance.
  149. /// </returns>
  150. public IBus CreateBus(AdvancedBusEventHandlers advancedBusEventHandlers, Action<IServiceRegister> registerServices)
  151. {
  152. var rabbitConnectionString = ConfigurationManager.ConnectionStrings["rabbit"];
  153. if (rabbitConnectionString == null)
  154. {
  155. throw new EasyNetQException(
  156. "Could not find a connection string for RabbitMQ. " +
  157. "Please add a connection string in the <ConnectionStrings> section" +
  158. "of the application's configuration file. For example: " +
  159. "<add name=\"rabbit\" connectionString=\"host=localhost\" />");
  160. }
  161.  
  162. return CreateBus(rabbitConnectionString.ConnectionString, advancedBusEventHandlers, registerServices);
  163. }
  164.  
  165. /// <summary>
  166. /// Creates a new instance of <see cref="RabbitBus"/>.
  167. /// The RabbitMQ broker is defined in the connection string named 'rabbit'.
  168. /// </summary>
  169. /// <param name="advancedBusEventHandlers">
  170. /// An <see cref="AdvancedBusEventHandlers"/> instance which is used to add handlers
  171. /// to the events of the newly created <see cref="IBus.Advanced"/>.
  172. /// As <see cref="RabbitAdvancedBus"/> attempts to connect during instantiation, specifying a <see cref="AdvancedBusEventHandlers"/>
  173. /// before instantiation is the only way to catch the first <see cref="AdvancedBusEventHandlers.Connected"/> event.
  174. /// </param>
  175. /// <returns>
  176. /// A new <see cref="RabbitBus"/> instance.
  177. /// </returns>
  178. public IBus CreateBus(AdvancedBusEventHandlers advancedBusEventHandlers)
  179. {
  180. return CreateBus(advancedBusEventHandlers, c => { });
  181. }
  182.  
  183. /// <summary>
  184. /// Creates a new instance of <see cref="RabbitBus"/>.
  185. /// </summary>
  186. /// <param name="connectionString">
  187. /// The EasyNetQ connection string. Example:
  188. /// host=192.168.1.1;port=5672;virtualHost=MyVirtualHost;username=MyUsername;password=MyPassword;requestedHeartbeat=10
  189. ///
  190. /// The following default values will be used if not specified:
  191. /// host=localhost;port=5672;virtualHost=/;username=guest;password=guest;requestedHeartbeat=10
  192. /// </param>
  193. /// <returns>
  194. /// A new <see cref="RabbitBus"/> instance.
  195. /// </returns>
  196. public IBus CreateBus(string connectionString)
  197. {
  198. Preconditions.CheckNotNull(connectionString, "connectionString");
  199.  
  200. return CreateBus(connectionString, AdvancedBusEventHandlers.Default);
  201. }
  202.  
  203. /// <summary>
  204. /// Creates a new instance of <see cref="RabbitBus"/>.
  205. /// </summary>
  206. /// <param name="connectionString">
  207. /// The EasyNetQ connection string. Example:
  208. /// host=192.168.1.1;port=5672;virtualHost=MyVirtualHost;username=MyUsername;password=MyPassword;requestedHeartbeat=10
  209. ///
  210. /// The following default values will be used if not specified:
  211. /// host=localhost;port=5672;virtualHost=/;username=guest;password=guest;requestedHeartbeat=10
  212. /// </param>
  213. /// <param name="advancedBusEventHandlers">
  214. /// An <see cref="AdvancedBusEventHandlers"/> instance which is used to add handlers
  215. /// to the events of the newly created <see cref="IBus.Advanced"/>.
  216. /// As <see cref="RabbitAdvancedBus"/> attempts to connect during instantiation, specifying a <see cref="AdvancedBusEventHandlers"/>
  217. /// before instantiation is the only way to catch the first <see cref="AdvancedBusEventHandlers.Connected"/> event.
  218. /// </param>
  219. /// <returns>
  220. /// A new <see cref="RabbitBus"/> instance.
  221. /// </returns>
  222. public IBus CreateBus(string connectionString, AdvancedBusEventHandlers advancedBusEventHandlers)
  223. {
  224. Preconditions.CheckNotNull(connectionString, "connectionString");
  225. Preconditions.CheckNotNull(advancedBusEventHandlers, "advancedBusEventHandlers");
  226.  
  227. return CreateBus(connectionString, advancedBusEventHandlers, x => { });
  228. }
  229.  
  230. /// <summary>
  231. /// Creates a new instance of <see cref="RabbitBus"/>.
  232. /// </summary>
  233. /// <param name="connectionString">
  234. /// The EasyNetQ connection string. Example:
  235. /// host=192.168.1.1;port=5672;virtualHost=MyVirtualHost;username=MyUsername;password=MyPassword;requestedHeartbeat=10
  236. ///
  237. /// The following default values will be used if not specified:
  238. /// host=localhost;port=5672;virtualHost=/;username=guest;password=guest;requestedHeartbeat=10
  239. /// </param>
  240. /// <param name="registerServices">
  241. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  242. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  243. /// </param>
  244. /// <returns>
  245. /// A new <see cref="RabbitBus"/> instance.
  246. /// </returns>
  247. public IBus CreateBus(string connectionString, Action<IServiceRegister> registerServices)
  248. {
  249. Preconditions.CheckNotNull(connectionString, "connectionString");
  250. Preconditions.CheckNotNull(registerServices, "registerServices");
  251.  
  252. return CreateBus(connectionString, AdvancedBusEventHandlers.Default, registerServices);
  253. }
  254.  
  255. /// <summary>
  256. /// Creates a new instance of <see cref="RabbitBus"/>.
  257. /// </summary>
  258. /// <param name="connectionString">
  259. /// The EasyNetQ connection string. Example:
  260. /// host=192.168.1.1;port=5672;virtualHost=MyVirtualHost;username=MyUsername;password=MyPassword;requestedHeartbeat=10
  261. ///
  262. /// The following default values will be used if not specified:
  263. /// host=localhost;port=5672;virtualHost=/;username=guest;password=guest;requestedHeartbeat=10
  264. /// </param>
  265. /// <param name="advancedBusEventHandlers">
  266. /// An <see cref="AdvancedBusEventHandlers"/> instance which is used to add handlers
  267. /// to the events of the newly created <see cref="IBus.Advanced"/>.
  268. /// As <see cref="RabbitAdvancedBus"/> attempts to connect during instantiation, specifying a <see cref="AdvancedBusEventHandlers"/>
  269. /// before instantiation is the only way to catch the first <see cref="AdvancedBusEventHandlers.Connected"/> event.
  270. /// </param>
  271. /// <param name="registerServices">
  272. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  273. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  274. /// </param>
  275. /// <returns>
  276. /// A new <see cref="RabbitBus"/> instance.
  277. /// </returns>
  278. public IBus CreateBus(string connectionString, AdvancedBusEventHandlers advancedBusEventHandlers, Action<IServiceRegister> registerServices)
  279. {
  280. Preconditions.CheckNotNull(connectionString, "connectionString");
  281. Preconditions.CheckNotNull(registerServices, "registerServices");
  282. Preconditions.CheckNotNull(advancedBusEventHandlers, "advancedBusEventHandlers");
  283.  
  284. var connectionStringParser = new ConnectionStringParser();
  285.  
  286. var connectionConfiguration = connectionStringParser.Parse(connectionString);
  287.  
  288. return CreateBus(connectionConfiguration, advancedBusEventHandlers, registerServices);
  289. }
  290.  
  291. /// <summary>
  292. /// Creates a new instance of <see cref="RabbitBus"/>.
  293. /// </summary>
  294. /// <param name="hostName">
  295. /// The RabbitMQ broker.
  296. /// </param>
  297. /// <param name="hostPort">
  298. /// The RabbitMQ broker port.
  299. /// </param>
  300. /// <param name="virtualHost">
  301. /// The RabbitMQ virtualHost.
  302. /// </param>
  303. /// <param name="username">
  304. /// The username to use to connect to the RabbitMQ broker.
  305. /// </param>
  306. /// <param name="password">
  307. /// The password to use to connect to the RabbitMQ broker.
  308. /// </param>
  309. /// <param name="requestedHeartbeat">
  310. /// The initially requested heartbeat interval, in seconds; zero for none.
  311. /// </param>
  312. /// <param name="registerServices">
  313. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  314. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  315. /// </param>
  316. /// <returns>
  317. /// A new <see cref="RabbitBus"/> instance.
  318. /// </returns>
  319. public IBus CreateBus(
  320. string hostName,
  321. ushort hostPort,
  322. string virtualHost,
  323. string username,
  324. string password,
  325. ushort requestedHeartbeat,
  326. Action<IServiceRegister> registerServices)
  327. {
  328. Preconditions.CheckNotNull(hostName, "hostName");
  329. Preconditions.CheckNotNull(virtualHost, "virtualHost");
  330. Preconditions.CheckNotNull(username, "username");
  331. Preconditions.CheckNotNull(password, "password");
  332. Preconditions.CheckNotNull(registerServices, "registerServices");
  333.  
  334. return CreateBus(hostName, hostPort, virtualHost, username, password, requestedHeartbeat, AdvancedBusEventHandlers.Default, registerServices);
  335. }
  336.  
  337. /// <summary>
  338. /// Creates a new instance of <see cref="RabbitBus"/>.
  339. /// </summary>
  340. /// <param name="hostName">
  341. /// The RabbitMQ broker.
  342. /// </param>
  343. /// <param name="hostPort">
  344. /// The RabbitMQ broker port.
  345. /// </param>
  346. /// <param name="virtualHost">
  347. /// The RabbitMQ virtualHost.
  348. /// </param>
  349. /// <param name="username">
  350. /// The username to use to connect to the RabbitMQ broker.
  351. /// </param>
  352. /// <param name="password">
  353. /// The password to use to connect to the RabbitMQ broker.
  354. /// </param>
  355. /// <param name="requestedHeartbeat">
  356. /// The initially requested heartbeat interval, in seconds; zero for none.
  357. /// </param>
  358. /// <param name="advancedBusEventHandlers">
  359. /// An <see cref="AdvancedBusEventHandlers"/> instance which is used to add handlers
  360. /// to the events of the newly created <see cref="IBus.Advanced"/>.
  361. /// As <see cref="RabbitAdvancedBus"/> attempts to connect during instantiation, specifying a <see cref="AdvancedBusEventHandlers"/>
  362. /// before instantiation is the only way to catch the first <see cref="AdvancedBusEventHandlers.Connected"/> event.
  363. /// </param>
  364. /// <param name="registerServices">
  365. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  366. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  367. /// </param>
  368. /// <returns>
  369. /// A new <see cref="RabbitBus"/> instance.
  370. /// </returns>
  371. public IBus CreateBus(
  372. string hostName,
  373. ushort hostPort,
  374. string virtualHost,
  375. string username,
  376. string password,
  377. ushort requestedHeartbeat,
  378. AdvancedBusEventHandlers advancedBusEventHandlers,
  379. Action<IServiceRegister> registerServices)
  380. {
  381. Preconditions.CheckNotNull(hostName, "hostName");
  382. Preconditions.CheckNotNull(virtualHost, "virtualHost");
  383. Preconditions.CheckNotNull(username, "username");
  384. Preconditions.CheckNotNull(password, "password");
  385. Preconditions.CheckNotNull(advancedBusEventHandlers, "advancedBusEventHandlers");
  386. Preconditions.CheckNotNull(registerServices, "registerServices");
  387.  
  388. var connectionConfiguration = new ConnectionConfiguration
  389. {
  390. Hosts = new List<HostConfiguration>
  391. {
  392. new HostConfiguration { Host = hostName, Port = hostPort }
  393. },
  394. Port = hostPort,
  395. VirtualHost = virtualHost,
  396. UserName = username,
  397. Password = password,
  398. RequestedHeartbeat = requestedHeartbeat
  399. };
  400. return CreateBus(connectionConfiguration, advancedBusEventHandlers, registerServices);
  401. }
  402.  
  403. /// <summary>
  404. /// Creates a new instance of <see cref="RabbitBus"/>.
  405. /// </summary>
  406. /// <param name="connectionConfiguration">
  407. /// An <see cref="ConnectionConfiguration"/> instance.
  408. /// </param>
  409. /// <param name="registerServices">
  410. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  411. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  412. /// </param>
  413. /// <returns>
  414. /// A new <see cref="RabbitBus"/> instance.
  415. /// </returns>
  416. public IBus CreateBus(ConnectionConfiguration connectionConfiguration, Action<IServiceRegister> registerServices)
  417. {
  418. Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
  419. Preconditions.CheckNotNull(registerServices, "registerServices");
  420.  
  421. return CreateBus(connectionConfiguration, AdvancedBusEventHandlers.Default, registerServices);
  422. }
  423.  
  424. /// <summary>
  425. /// Creates a new instance of <see cref="RabbitBus"/>.
  426. /// </summary>
  427. /// <param name="connectionConfiguration">
  428. /// An <see cref="ConnectionConfiguration"/> instance.
  429. /// </param>
  430. /// <param name="advancedBusEventHandlers">
  431. /// An <see cref="AdvancedBusEventHandlers"/> instance which is used to add handlers
  432. /// to the events of the newly created <see cref="IBus.Advanced"/>.
  433. /// As <see cref="RabbitAdvancedBus"/> attempts to connect during instantiation, specifying a <see cref="AdvancedBusEventHandlers"/>
  434. /// before instantiation is the only way to catch the first <see cref="AdvancedBusEventHandlers.Connected"/> event.
  435. /// </param>
  436. /// <param name="registerServices">
  437. /// Override default services. For example, to override the default <see cref="IEasyNetQLogger"/>:
  438. /// RabbitHutch.CreateBus("host=localhost", x => x.Register{IEasyNetQLogger}(_ => myLogger));
  439. /// </param>
  440. /// <returns>
  441. /// A new <see cref="RabbitBus"/> instance.
  442. /// </returns>
  443. public IBus CreateBus(ConnectionConfiguration connectionConfiguration, AdvancedBusEventHandlers advancedBusEventHandlers, Action<IServiceRegister> registerServices)
  444. {
  445. Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
  446. Preconditions.CheckNotNull(advancedBusEventHandlers, "advancedBusEventHandlers");
  447. Preconditions.CheckNotNull(registerServices, "registerServices");
  448.  
  449. var container = createContainerInternal();
  450. if (container == null)
  451. {
  452. throw new EasyNetQException("Could not create container. " +
  453. "Have you called SetContainerFactory(...) with a function that returns null?");
  454. }
  455.  
  456. connectionConfiguration.Validate();
  457. container.Register(_ => connectionConfiguration);
  458. container.Register(_ => advancedBusEventHandlers);
  459. registerServices(container);
  460. ComponentRegistration.RegisterServices(container);
  461.  
  462. return container.Resolve<IBus>();
  463. }
  464. }
  465.  
  466. /// <summary>
  467. /// Collection of precondition methods for qualifying method arguments.
  468. /// </summary>
  469. internal class Preconditions
  470. {
  471. /// <summary>
  472. /// Ensures that <paramref name="value"/> is not null.
  473. /// </summary>
  474. /// <param name="value">
  475. /// The value to check, must not be null.
  476. /// </param>
  477. /// <param name="name">
  478. /// The name of the parameter the value is taken from, must not be
  479. /// blank.
  480. /// </param>
  481. /// <exception cref="ArgumentNullException">
  482. /// Thrown if <paramref name="value"/> is null.
  483. /// </exception>
  484. /// <exception cref="ArgumentException">
  485. /// Thrown if <paramref name="name"/> is blank.
  486. /// </exception>
  487. public void CheckNotNull<T>(T value, string name) where T : class
  488. {
  489. CheckNotNull(value, name, string.Format("{0} must not be null", name));
  490. }
  491.  
  492. /// <summary>
  493. /// Ensures that <paramref name="value"/> is not null.
  494. /// </summary>
  495. /// <param name="value">
  496. /// The value to check, must not be null.
  497. /// </param>
  498. /// <param name="name">
  499. /// The name of the parameter the value is taken from, must not be
  500. /// blank.
  501. /// </param>
  502. /// <param name="message">
  503. /// The message to provide to the exception if <paramref name="value"/>
  504. /// is null, must not be blank.
  505. /// </param>
  506. /// <exception cref="ArgumentNullException">
  507. /// Thrown if <paramref name="value"/> is null.
  508. /// </exception>
  509. /// <exception cref="ArgumentException">
  510. /// Thrown if <paramref name="name"/> or <paramref name="message"/> are
  511. /// blank.
  512. /// </exception>
  513. public void CheckNotNull<T>(T value, string name, string message) where T : class
  514. {
  515. if (value == null)
  516. {
  517. CheckNotBlank(name, "name", "name must not be blank");
  518. CheckNotBlank(message, "message", "message must not be blank");
  519.  
  520. throw new ArgumentNullException(name, message);
  521. }
  522. }
  523.  
  524. /// <summary>
  525. /// Ensures that <paramref name="value"/> is not blank.
  526. /// </summary>
  527. /// <param name="value">
  528. /// The value to check, must not be blank.
  529. /// </param>
  530. /// <param name="name">
  531. /// The name of the parameter the value is taken from, must not be
  532. /// blank.
  533. /// </param>
  534. /// <param name="message">
  535. /// The message to provide to the exception if <paramref name="value"/>
  536. /// is blank, must not be blank.
  537. /// </param>
  538. /// <exception cref="ArgumentException">
  539. /// Thrown if <paramref name="value"/>, <paramref name="name"/>, or
  540. /// <paramref name="message"/> are blank.
  541. /// </exception>
  542. public void CheckNotBlank(string value, string name, string message)
  543. {
  544. if (string.IsNullOrWhiteSpace(name))
  545. {
  546. throw new ArgumentException("name must not be blank", "name");
  547. }
  548.  
  549. if (string.IsNullOrWhiteSpace(message))
  550. {
  551. throw new ArgumentException("message must not be blank", "message");
  552. }
  553.  
  554. if (string.IsNullOrWhiteSpace(value))
  555. {
  556. throw new ArgumentException(message, name);
  557. }
  558. }
  559.  
  560. /// <summary>
  561. /// Ensures that <paramref name="value"/> is not blank.
  562. /// </summary>
  563. /// <param name="value">
  564. /// The value to check, must not be blank.
  565. /// </param>
  566. /// <param name="name">
  567. /// The name of the parameter the value is taken from, must not be
  568. /// blank.
  569. /// </param>
  570. /// <exception cref="ArgumentException">
  571. /// Thrown if <paramref name="value"/> or <paramref name="name"/> are
  572. /// blank.
  573. /// </exception>
  574. public void CheckNotBlank(string value, string name)
  575. {
  576. CheckNotBlank(value, name, string.Format("{0} must not be blank", name));
  577. }
  578.  
  579. /// <summary>
  580. /// Ensures that <paramref name="collection"/> contains at least one
  581. /// item.
  582. /// </summary>
  583. /// <param name="collection">
  584. /// The collection to check, must not be null or empty.
  585. /// </param>
  586. /// <param name="name">
  587. /// The name of the parameter the collection is taken from, must not be
  588. /// blank.
  589. /// </param>
  590. /// <param name="message">
  591. /// The message to provide to the exception if <paramref name="collection"/>
  592. /// is empty, must not be blank.
  593. /// </param>
  594. /// <exception cref="ArgumentException">
  595. /// Thrown if <paramref name="collection"/> is empty, or if
  596. /// <paramref name="value"/> or <paramref name="name"/> are blank.
  597. /// </exception>
  598. public void CheckAny<T>(IEnumerable<T> collection, string name, string message)
  599. {
  600. if (collection == null || !collection.Any())
  601. {
  602. CheckNotBlank(name, "name", "name must not be blank");
  603. CheckNotBlank(message, "message", "message must not be blank");
  604.  
  605. throw new ArgumentException(message, name);
  606. }
  607. }
  608.  
  609. /// <summary>
  610. /// Ensures that <paramref name="value"/> is true.
  611. /// </summary>
  612. /// <param name="value">
  613. /// The value to check, must be true.
  614. /// </param>
  615. /// <param name="name">
  616. /// The name of the parameter the value is taken from, must not be
  617. /// blank.
  618. /// </param>
  619. /// <param name="message">
  620. /// The message to provide to the exception if <paramref name="collection"/>
  621. /// is false, must not be blank.
  622. /// </param>
  623. /// <exception cref="ArgumentException">
  624. /// Thrown if <paramref name="value"/> is false, or if <paramref name="name"/>
  625. /// or <paramref name="message"/> are blank.
  626. /// </exception>
  627. public void CheckTrue(bool value, string name, string message)
  628. {
  629. if (!value)
  630. {
  631. CheckNotBlank(name, "name", "name must not be blank");
  632. CheckNotBlank(message, "message", "message must not be blank");
  633.  
  634. throw new ArgumentException(message, name);
  635. }
  636. }
  637.  
  638. /// <summary>
  639. /// Ensures that <paramref name="value"/> is false.
  640. /// </summary>
  641. /// <param name="value">
  642. /// The value to check, must be false.
  643. /// </param>
  644. /// <param name="name">
  645. /// The name of the parameter the value is taken from, must not be
  646. /// blank.
  647. /// </param>
  648. /// <param name="message">
  649. /// The message to provide to the exception if <paramref name="collection"/>
  650. /// is true, must not be blank.
  651. /// </param>
  652. /// <exception cref="ArgumentException">
  653. /// Thrown if <paramref name="value"/> is true, or if <paramref name="name"/>
  654. /// or <paramref name="message"/> are blank.
  655. /// </exception>
  656. public void CheckFalse(bool value, string name, string message)
  657. {
  658. if (value)
  659. {
  660. CheckNotBlank(name, "name", "name must not be blank");
  661. CheckNotBlank(message, "message", "message must not be blank");
  662.  
  663. throw new ArgumentException(message, name);
  664. }
  665. }
  666.  
  667. public void CheckShortString(string value, string name)
  668. {
  669. CheckNotNull(value, name);
  670. if (value.Length > 255)
  671. {
  672. throw new ArgumentException(string.Format("Argument '{0}' must be less than or equal to 255 characters.", name));
  673. }
  674. }
  675.  
  676. public void CheckTypeMatches(Type expectedType, object value, string name, string message)
  677. {
  678. if (!expectedType.IsAssignableFrom(value.GetType()))
  679. {
  680. CheckNotBlank(name, "name", "name must not be blank");
  681. CheckNotBlank(message, "message", "message must not be blank");
  682.  
  683. throw new ArgumentException(message, name);
  684. }
  685. }
  686.  
  687. public void CheckLess(TimeSpan value, TimeSpan maxValue, string name)
  688. {
  689. if (value < maxValue)
  690. return;
  691. throw new ArgumentOutOfRangeException(name, string.Format("Arguments {0} must be less than maxValue", name));
  692. }
  693.  
  694. public void CheckNull<T>(T value, string name)
  695. {
  696. if (value == null)
  697. return;
  698. throw new ArgumentException(string.Format("{0} must not be null", name), name);
  699. }
  700. }
  701. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement