Advertisement
Demonslay335

GetRandomCommand.cs

Jul 16th, 2017
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.15 KB | None | 0 0
  1. ```// Decompiled with JetBrains decompiler
  2. // Type: Microsoft.PowerShell.Commands.GetRandomCommand
  3. // Assembly: Microsoft.PowerShell.Commands.Utility, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  4. // MVID: 3BD7B47C-588A-4217-80BE-3EE52156DF03
  5. // Assembly location: C:\Windows\WinSxS\msil_microsoft.powershell.commands.utility_31bf3856ad364e35_1.0.0.0_none_b77a5f49a3ba5d1f\Microsoft.PowerShell.Commands.Utility.dll
  6.  
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Management.Automation;
  11. using System.Management.Automation.Runspaces;
  12. using System.Threading;
  13.  
  14. namespace Microsoft.PowerShell.Commands
  15. {
  16. [Cmdlet("Get", "Random", DefaultParameterSetName = "RandomNumberParameterSet")]
  17. public class GetRandomCommand : PSCmdlet
  18. {
  19. [TraceSource("GetRandomCommand", "Class that has get-random command implementation")]
  20. private static PSTraceSource tracer = PSTraceSource.GetTracer("GetRandomCommand", "Class that has get-random command implementation");
  21. private static ReaderWriterLock runspaceGeneratorMapLock = new ReaderWriterLock();
  22. private static Dictionary<Guid, Random> RunspaceGeneratorMap = new Dictionary<Guid, Random>();
  23. private const string RandomNumberParameterSet = "RandomNumberParameterSet";
  24. private const string RandomListItemParameterSet = "RandomListItemParameterSet";
  25. private GetRandomCommand.MyParameterSet effectiveParameterSet;
  26. private Random generator;
  27. private int? setSeed;
  28. private object maximum;
  29. private object minimum;
  30. private List<object> chosenListItems;
  31. private int numberOfProcessedListItems;
  32. private object[] inputObject;
  33. private int count;
  34.  
  35. private GetRandomCommand.MyParameterSet EffectiveParameterSet
  36. {
  37. get
  38. {
  39. if (this.effectiveParameterSet == GetRandomCommand.MyParameterSet.Unknown)
  40. {
  41. if (this.MyInvocation.ExpectingInput && this.Maximum == null && this.Minimum == null)
  42. this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomListItem;
  43. else if (this.ParameterSetName.Equals("RandomListItemParameterSet", StringComparison.OrdinalIgnoreCase))
  44. this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomListItem;
  45. else if (this.ParameterSetName.Equals("RandomNumberParameterSet", StringComparison.OrdinalIgnoreCase))
  46. {
  47. if (this.Maximum != null && this.Maximum.GetType().IsArray)
  48. {
  49. this.InputObject = (object[]) this.Maximum;
  50. this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomListItem;
  51. }
  52. else
  53. this.effectiveParameterSet = GetRandomCommand.MyParameterSet.RandomNumber;
  54. }
  55. }
  56. return this.effectiveParameterSet;
  57. }
  58. }
  59.  
  60. private Random Generator
  61. {
  62. get
  63. {
  64. if (this.generator == null)
  65. {
  66. Guid instanceId = this.Context.CurrentRunspace.InstanceId;
  67. bool flag = false;
  68. try
  69. {
  70. GetRandomCommand.runspaceGeneratorMapLock.AcquireReaderLock(-1);
  71. flag = !GetRandomCommand.RunspaceGeneratorMap.TryGetValue(instanceId, out this.generator);
  72. }
  73. finally
  74. {
  75. GetRandomCommand.runspaceGeneratorMapLock.ReleaseReaderLock();
  76. }
  77. if (flag)
  78. this.Generator = new Random();
  79. }
  80. return this.generator;
  81. }
  82. set
  83. {
  84. this.generator = value;
  85. Runspace currentRunspace = this.Context.CurrentRunspace;
  86. try
  87. {
  88. GetRandomCommand.runspaceGeneratorMapLock.AcquireWriterLock(-1);
  89. if (!GetRandomCommand.RunspaceGeneratorMap.ContainsKey(currentRunspace.InstanceId))
  90. currentRunspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(GetRandomCommand.CurrentRunspace_StateChanged);
  91. GetRandomCommand.RunspaceGeneratorMap[currentRunspace.InstanceId] = this.generator;
  92. }
  93. finally
  94. {
  95. GetRandomCommand.runspaceGeneratorMapLock.ReleaseWriterLock();
  96. }
  97. }
  98. }
  99.  
  100. [Parameter]
  101. [ValidateNotNull]
  102. public int? SetSeed
  103. {
  104. get
  105. {
  106. return this.setSeed;
  107. }
  108. set
  109. {
  110. this.setSeed = value;
  111. }
  112. }
  113.  
  114. [Parameter(ParameterSetName = "RandomNumberParameterSet", Position = 0)]
  115. public object Maximum
  116. {
  117. get
  118. {
  119. return this.maximum;
  120. }
  121. set
  122. {
  123. this.maximum = value;
  124. }
  125. }
  126.  
  127. [Parameter(ParameterSetName = "RandomNumberParameterSet")]
  128. public object Minimum
  129. {
  130. get
  131. {
  132. return this.minimum;
  133. }
  134. set
  135. {
  136. this.minimum = value;
  137. }
  138. }
  139.  
  140. [ValidateNotNullOrEmpty]
  141. [Parameter(Mandatory = true, ParameterSetName = "RandomListItemParameterSet", Position = 0, ValueFromPipeline = true)]
  142. public object[] InputObject
  143. {
  144. get
  145. {
  146. return this.inputObject;
  147. }
  148. set
  149. {
  150. this.inputObject = value;
  151. }
  152. }
  153.  
  154. [ValidateRange(1, 2147483647)]
  155. [Parameter(ParameterSetName = "RandomListItemParameterSet")]
  156. public int Count
  157. {
  158. get
  159. {
  160. return this.count;
  161. }
  162. set
  163. {
  164. this.count = value;
  165. }
  166. }
  167.  
  168. private ErrorDetails GetErrorDetails(string errorId, params object[] args)
  169. {
  170. if (string.IsNullOrEmpty(errorId))
  171. throw GetRandomCommand.tracer.NewArgumentNullException("errorId");
  172. return new ErrorDetails(this.GetType().Assembly, "GetRandomCommandStrings", errorId, args);
  173. }
  174.  
  175. private void ThrowMinGreaterThanOrEqualMax(object min, object max)
  176. {
  177. if (min == null)
  178. throw GetRandomCommand.tracer.NewArgumentNullException("min");
  179. if (max == null)
  180. throw GetRandomCommand.tracer.NewArgumentNullException("max");
  181. string errorId = "MinGreaterThanOrEqualMax";
  182. this.ThrowTerminatingError(new ErrorRecord((Exception) new ArgumentException(this.GetErrorDetails(errorId, min, max).Message), errorId, ErrorCategory.InvalidArgument, (object) null));
  183. }
  184.  
  185. private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e)
  186. {
  187. switch (e.RunspaceStateInfo.State)
  188. {
  189. case RunspaceState.Closed:
  190. case RunspaceState.Broken:
  191. try
  192. {
  193. GetRandomCommand.runspaceGeneratorMapLock.AcquireWriterLock(-1);
  194. GetRandomCommand.RunspaceGeneratorMap.Remove(((Runspace) sender).InstanceId);
  195. break;
  196. }
  197. finally
  198. {
  199. GetRandomCommand.runspaceGeneratorMapLock.ReleaseWriterLock();
  200. }
  201. }
  202. }
  203.  
  204. private bool IsInt(object o)
  205. {
  206. if (o == null)
  207. return true;
  208. PSObject psObject = PSObject.AsPSObject(o);
  209. if (psObject.BaseObject is int)
  210. return true;
  211. if (psObject.BaseObject is string)
  212. {
  213. int result;
  214. return int.TryParse((string) psObject.BaseObject, out result);
  215. }
  216. return false;
  217. }
  218.  
  219. private double ConvertToDouble(object o, double defaultIfNull)
  220. {
  221. if (o == null)
  222. return defaultIfNull;
  223. return (double) LanguagePrimitives.ConvertTo(o, typeof (double), (IFormatProvider) CultureInfo.InvariantCulture);
  224. }
  225.  
  226. private int ConvertToInt(object o, int defaultIfNull)
  227. {
  228. if (o == null)
  229. return defaultIfNull;
  230. return (int) LanguagePrimitives.ConvertTo(o, typeof (int), (IFormatProvider) CultureInfo.InvariantCulture);
  231. }
  232.  
  233. private double GetRandomDouble(double min, double max)
  234. {
  235. double d = max - min;
  236. double num1;
  237. if (double.IsInfinity(d))
  238. {
  239. do
  240. {
  241. double num2 = this.Generator.NextDouble();
  242. num1 = min + num2 * max - num2 * min;
  243. }
  244. while (num1 >= max);
  245. }
  246. else
  247. {
  248. do
  249. {
  250. double num2 = this.Generator.NextDouble();
  251. num1 = min + num2 * d;
  252. d *= num2;
  253. }
  254. while (num1 >= max);
  255. }
  256. return num1;
  257. }
  258.  
  259. protected override void BeginProcessing()
  260. {
  261. using (GetRandomCommand.tracer.TraceMethod())
  262. {
  263. if (this.SetSeed.HasValue)
  264. this.Generator = new Random(this.SetSeed.Value);
  265. if (this.EffectiveParameterSet == GetRandomCommand.MyParameterSet.RandomNumber)
  266. {
  267. if (this.IsInt(this.Maximum) && this.IsInt(this.Minimum))
  268. {
  269. int minValue = this.ConvertToInt(this.Minimum, 0);
  270. int maxValue = this.ConvertToInt(this.Maximum, int.MaxValue);
  271. if (minValue >= maxValue)
  272. this.ThrowMinGreaterThanOrEqualMax((object) minValue, (object) maxValue);
  273. this.WriteObject((object) this.Generator.Next(minValue, maxValue));
  274. }
  275. else
  276. {
  277. double min = this.ConvertToDouble(this.Minimum, 0.0);
  278. double max = this.ConvertToDouble(this.Maximum, double.MaxValue);
  279. if (min >= max)
  280. this.ThrowMinGreaterThanOrEqualMax((object) min, (object) max);
  281. this.WriteObject((object) this.GetRandomDouble(min, max));
  282. }
  283. }
  284. else
  285. {
  286. if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
  287. return;
  288. this.chosenListItems = new List<object>();
  289. this.numberOfProcessedListItems = 0;
  290. if (this.Count != 0)
  291. return;
  292. this.Count = 1;
  293. }
  294. }
  295. }
  296.  
  297. protected override void ProcessRecord()
  298. {
  299. using (GetRandomCommand.tracer.TraceMethod())
  300. {
  301. if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
  302. return;
  303. foreach (object obj in this.InputObject)
  304. {
  305. if (this.numberOfProcessedListItems < this.Count)
  306. this.chosenListItems.Add(obj);
  307. else if (this.Generator.Next(this.numberOfProcessedListItems + 1) < this.Count)
  308. this.chosenListItems[this.Generator.Next(this.chosenListItems.Count)] = obj;
  309. ++this.numberOfProcessedListItems;
  310. }
  311. }
  312. }
  313.  
  314. protected override void EndProcessing()
  315. {
  316. using (GetRandomCommand.tracer.TraceMethod())
  317. {
  318. if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
  319. return;
  320. int count = this.chosenListItems.Count;
  321. for (int minValue = 0; minValue < count; ++minValue)
  322. {
  323. int index = this.Generator.Next(minValue, count);
  324. if (minValue != index)
  325. {
  326. object chosenListItem = this.chosenListItems[minValue];
  327. this.chosenListItems[minValue] = this.chosenListItems[index];
  328. this.chosenListItems[index] = chosenListItem;
  329. }
  330. }
  331. foreach (object chosenListItem in this.chosenListItems)
  332. this.WriteObject(chosenListItem);
  333. }
  334. }
  335.  
  336. private enum MyParameterSet
  337. {
  338. Unknown,
  339. RandomNumber,
  340. RandomListItem,
  341. }
  342. }
  343. }
  344. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement