public virtual WatcherResult Watch() { try { LoggingService.Trace("Watching."); if (DataManager == null) { LoggingService.Debug("Creating new instance of Plugin Data Manager."); DataManager = new PluginDataManager(this.Id); LoggingService.Debug("Setting Data File."); DataManager.SetDataFile(); } var plannedExecutionTime = DataManager.GetPlannedExecutionTime(); LoggingService.Trace("Planned Execution Time: {0}", plannedExecutionTime.ToString("G")); if (DateTime.Compare(DateTime.Now, plannedExecutionTime) >= 0) { LoggingService.Debug("Time Reached"); var nextExecutionTime = GetNextExecutionTime(); LoggingService.Debug("Saving Next Execution Time: {0}", nextExecutionTime.ToString("G")); DataManager.SaveNextExecutionTime(nextExecutionTime); return(WatcherResult.Succeed(ArgumentCollection.New())); } LoggingService.Trace("Time Not Reached Yet!"); return(WatcherResult.NotFound); } catch (Exception exception) { LoggingService.Error(exception); return(WatcherResult.NotFound); } }
protected override void OnStartup(StartupEventArgs e) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); try { sw.Start(); Logger.Log(EventID.DesktopDashboard.Application.StartupEnter); base.OnStartup(e); WindowState windowState = null; wDesktopDashboard control = new wDesktopDashboard(); try { windowState = UserSettings.LoadSetting <WindowState>(UserSettings.SettingType.WindowState); } catch (Exception ex) { Logger.Log(EventID.DesktopDashboard.Application.Exception, nameof(UserSettings.LoadSetting), ex); } if (windowState == null) { windowState = new WindowState(); windowState.Width = Consts.DefaultWindowWidth; windowState.Height = Consts.DefaultWindowHeight; windowState.PositionTop = 0; windowState.PositionLeft = SystemParameters.PrimaryScreenWidth - windowState.Width; windowState.TopMost = false; try { UserSettings.SaveSetting(UserSettings.SettingType.WindowState, windowState); } catch (Exception ex) { Logger.Log(EventID.DesktopDashboard.Application.Exception, nameof(UserSettings.SaveSetting), ex); } } ArgumentCollection args = new ArgumentCollection(); args.Set(ArgumentCollection.ArgumentType.WindowState, windowState); args.Set(ArgumentCollection.ArgumentType.WindowTitle, Consts.WindowTitle); args.Set(ArgumentCollection.ArgumentType.WindowIcon, DesktopDashboard.Resources.ResourceImage.WindowIcon); args.Set(ArgumentCollection.ArgumentType.WindowCloseCommand, new Command((object parameter) => { control?.Close(); this.mainWindow?.Close(); })); this.mainWindow = new BaseWindow(args); this.mainWindow.SetContent(control); this.mainWindow.Show(); } catch (Exception ex) { Logger.Log(EventID.DesktopDashboard.Application.Exception, nameof(this.OnStartup), ex); } finally { sw.Stop(); Logger.Log(EventID.DesktopDashboard.Application.StartupExit, sw.ElapsedMilliseconds); } }
public void DeleteFilesTest() { var localWriteDir = Path.GetDirectoryName(Environment.ExpandEnvironmentVariables(LocalWorkingDir)); FtpDeleteAction ftpDeleteAction = new FtpDeleteAction() { Id = PluginUtilities.GetUniqueId(), LoggingService = ServicesContainer.ServicesProvider.GetLoggingService(nameof(FtpDownloadAction)) }; ftpDeleteAction.Host = FtpTestCredentials.Host; ftpDeleteAction.Username = FtpTestCredentials.User; ftpDeleteAction.Password = FtpTestCredentials.Password; ftpDeleteAction.Port = FtpTestCredentials.Port; ftpDeleteAction.RemoteWorkingDir = "/"; var fileNamePath = CreateTestFile(localWriteDir); var actionResult = ftpDeleteAction.Execute(ArgumentCollection.New() .WithArgument(FtpDownloadActionExecutionArgs.RemoteFilesCollection, new List <string>() { Path.GetFileName(fileNamePath) }) ); Assert.IsNotNull(actionResult); Assert.IsTrue(actionResult.Result); }
private bool ArgumentsMatchesArgumentConstraints(ArgumentCollection argumentCollection) { return(argumentCollection .AsEnumerable() .Zip(this.argumentConstraints, (x, y) => new { ArgumentValue = x, Constraint = y }) .All(x => x.Constraint.IsValid(x.ArgumentValue))); }
public static void Submit(ClusterSubmitterArgs clusterArgs, ArgumentCollection applicationArgs) { CommandArguments cmd = applicationArgs as CommandArguments; Helper.CheckCondition <ArgumentException>(cmd != null, "Can only provide command arguments to the cluster submitter"); Submit(clusterArgs, new DistributableWrapper(cmd)); }
public WatcherResult Watch() { try { var usage = Counter.NextValue(); // LoggingService.Debug($"Last Usage: {_lastUsage}, Current Usage: {usage}, Target {TargetMaximumUsage}"); if (usage > TargetMaximumUsage && CanNotify()) { // Notify only for the first occurrence when exceeding the target maximum if (_lastUsage < TargetMaximumUsage // Current usage is greater than previous notification usage || _lastNotificationUsage < usage) { _lastUsage = usage; _lastNotificationUsage = usage; _lastNotificationTime = DateTime.Now; return(WatcherResult.Succeed(ArgumentCollection.New() .WithArgument(UsageWatcherResultArgs.Usage, usage.ToString("F")) )); } } _lastUsage = usage; return(WatcherResult.NotFound); } catch (Exception exception) { LoggingService.Error(exception); return(WatcherResult.NotFound); } }
/// <summary> /// Removes optional arguments from the command-line input. /// </summary> /// <param name="arguments"></param> /// <param name="argumentCollection"></param> /// <returns>string</returns> private static string RemoveKnownArguments(string arguments, ArgumentCollection argumentCollection) { foreach (string key in argumentCollection.Keys) { if (__argumentMap[key] == ArgumentType.Null) { string arg = String.Concat(ArgumentCollection.Delimiter, key); int index = arguments.IndexOf(arg); if (index > -1) { arguments = arguments.Remove(index, arg.Length); } } else { string arg = String.Concat(ArgumentCollection.Delimiter, key, "=", argumentCollection[key]); int index = arguments.IndexOf(arg); if (index > -1) { arguments = arguments.Remove(index, arg.Length); } } } return(arguments); }
public void Initialize() { ArgumentCollection args = new ArgumentCollection(); args.Set(ArgumentCollection.ArgumentType.DriveInfo, this.DriveInfo); this.Control = new ucPartitionInfo(args); }
public void GenerateQRCodeSuccessfulTest() { string imageFormat = "png"; string eccl = QRCodeGenerator.ECCLevel.H.ToString("G"); string output = Path.Combine(Path.GetTempPath(), "output.png"); const bool eraseExistingFile = true; const bool forceUtf8 = true; const int pixelPerModule = 20; GenerateQRCodeAction action = new GenerateQRCodeAction() { ImageFormat = imageFormat, ErrorCorrectLevel = eccl, OutputFilePath = output, EraseExistingFile = eraseExistingFile, ForceUtf8 = forceUtf8, PixelPerModule = pixelPerModule }; var actionResult = action.Execute(ArgumentCollection.New() .WithArgument(GenerateQRCodeActionExecutionArgs.PlainText, qrCodeContent)); Assert.IsNotNull(actionResult); Assert.IsTrue(actionResult.Result); Assert.IsTrue(File.Exists(output)); File.Delete(output); }
private FakeCall(MethodInfo method, ArgumentCollection argumentCollection, object fakedObject, int sequenceNumber) { this.Method = method; this.Arguments = argumentCollection; this.FakedObject = fakedObject; this.SequenceNumber = sequenceNumber; }
static void Main(string[] raw) { try { Logger.ObserveTaskException(); Logger.Info(LogType, Assembly.GetExecutingAssembly()); Logger.Info(LogType, $"Ghostscript {GetGsVersion()}"); Logger.Info(LogType, $"[ {string.Join(" ", raw)} ]"); ApplicationSetting.Configure(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var args = new ArgumentCollection(raw, Argument.Windows, true); var setting = CreateSetting(args, Assembly.GetExecutingAssembly()); setting.Load(); setting.Normalize(); setting.Set(args); if (args.Options.ContainsKey("SkipUI")) { Execute(setting); } else { Show(setting); } } catch (Exception err) { Logger.Error(LogType, err); } }
public void CreateResultSucceedInstanceTest() { var watcherResult = WatcherResult.Succeed(ArgumentCollection.New()); Assert.IsNotNull(watcherResult); Assert.IsTrue(watcherResult.Result); }
/* ----------------------------------------------------------------- */ /// /// StartAs /// /// <summary> /// Process オブジェクトを生成し、開始します。 /// </summary> /// /// <param name="args">プログラム引数</param> /// /// <remarks> /// 開始された Process オブジェクト /// </remarks> /// /* ----------------------------------------------------------------- */ static System.Diagnostics.Process StartAs(string[] args) { var parser = new ArgumentCollection(args, '/'); if (!parser.Options.TryGetValue("Exec", out var exec)) { throw new ArgumentException("Exec"); } try { parser.Options.TryGetValue("UserName", out var user); return(Cube.Processes.Process.StartAs(user, exec, args)); } catch (Exception e) { if (!parser.Options.TryGetValue("ThreadID", out var id)) { throw; } else { Logger.Warn(typeof(Program), e.Message, e); Logger.Info(typeof(Program), $"Use ThreadID ({id})"); return(Cube.Processes.Process.StartAs(uint.Parse(id), exec, args)); } } }
public void SendSampleFileTest() { FtpUploadAction action = new FtpUploadAction() { Id = PluginUtilities.GetUniqueId(), LoggingService = ServicesContainer.ServicesProvider.GetLoggingService(nameof(FtpUploadAction)), Host = FtpTestCredentials.Host, Username = FtpTestCredentials.User, Password = FtpTestCredentials.Password, Port = FtpTestCredentials.Port, DestinationFolderPath = "Data", DestinationFileName = "renamed.txt", UseRemoteTemporaryExtension = true, RemoteTemporaryExtension = "remote", UseLocalTemporaryExtension = true, LocalTemporaryExtension = "local", Overwrite = true, CreateRemoteDirectory = true }; string sourceFileName = Path.Combine(Path.GetTempPath(), "test.txt"); File.WriteAllText(sourceFileName, "Hello world! This is a remote message!"); var result = action.Execute(ArgumentCollection.New() .WithArgument(FtpUploadActionExecutionArgs.SourceFilesCollection, new List <string> { sourceFileName })); Console.WriteLine(result.AttachedException); Assert.IsTrue(result.Result); File.Delete(sourceFileName); }
public void FailsWhenNoSourceFilesToZipTest() { IAction action = new ZipFilesAction() { LoggingService = ServicesContainer.ServicesProvider.GetLoggingService(null) }; string outputZipPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".zip"); var actionResult = action.Execute(ArgumentCollection.New() .WithArgument(ZipFilesActionInstanceArgs.ArchivePath, outputZipPath)); Assert.IsNotNull(actionResult); Assert.IsFalse(actionResult.Result); Assert.IsNotNull(actionResult.AttachedException); Assert.AreEqual(typeof(MissingArgumentsException), actionResult.AttachedException.GetType()); actionResult = action.Execute(ArgumentCollection.New() .WithArgument(ZipFilesActionExecutionArgs.ArchivePath, outputZipPath)); Assert.IsNotNull(actionResult); Assert.IsFalse(actionResult.Result); Assert.IsNotNull(actionResult.AttachedException); Assert.AreEqual(typeof(MissingArgumentsException), actionResult.AttachedException.GetType()); // CLEANUP if (File.Exists(outputZipPath)) { File.Delete(outputZipPath); } }
/* ----------------------------------------------------------------- */ /// /// Main /// /// <summary> /// CoReceiver のエントリポイントです。 /// </summary> /// /* ----------------------------------------------------------------- */ static void Main(string[] args) { // ログ出力用の処理です。不要な場合、削除して構いません。 InitLog(args); // まず、プログラム引数を ArgumentCollection クラスを用いて解析します。 // 今回の連携デモでは JSON データの保存されているパスが DocumentName // オプション引数に指定されているため、SettingFolder クラスに対して // Format.Json および DocumentName の値を指定して初期化します。 // その後、Load メソッドを実行する事により JSON 形式の設定内容が読み込まれます。 var src = new ArgumentCollection(args); var settings = new SettingFolder(Format.Json, src.Options["DocumentName"]); settings.Load(); // SettingFolder オブジェクトに対して、プログラム引数の内容を反映させるため // Set メソッドを実行します。 // ただし、Set メソッドは Destination (保存場所)の値を上書きします。 // 今回の連携デモでは、JSON データに記載された場所に PDF ファイルを保存する事を // 想定しているため、ローカル変数にいったん退避させた後、Set メソッド適用後に // 再度その値を反映させる事とします。 var dest = settings.Value.Destination; settings.Set(src); settings.Value.Destination = dest; // 設定が完了したら、Facade クラスで変換処理を実行します。 using (var facade = new Facade(settings)) facade.Invoke(); // 最後に、印刷前プログラムが作成した一時ファイルを削除します。 File.Delete(settings.Location); }
public void Then_Null_Argument_Instances_Are_Not_Allowed() { var systemUnderTest = new ArgumentCollection(); Invoking(() => systemUnderTest.Add(null)).Should().ThrowExactly <ArgumentNullException>() .Which.ParamName.Should().Be("item"); }
private static ArgumentCollection TranslateArguments(IEnumerable <Expression> argumentExpressions) { var arguments = new ArgumentCollection(); argumentExpressions.Each(arg => arguments.Add(TranslateTerm(arg))); return(arguments); }
public void GetTyped() { Assert.Equal(5, ArgumentCollection.Create(valueTypeMethod.GetParameters(), 5).Get <int>(0)); Assert.Equal(5, ArgumentCollection.Create(valueTypeMethod.GetParameters(), 5).Get <int>("value")); // If nullable annotations are ignored and we request a nullable int, it should still work. #nullable disable
/// <summary> /// To Parse String. /// </summary> /// <param name="obj">The Object.</param> /// <param name="parseTypeOrNull">Parse Type Or Null.</param> /// <param name="suppressDefaults">Suppress Defaults</param> /// <returns></returns> public static string ToParseString(this object obj, Type parseTypeOrNull = null, bool suppressDefaults = false) { if (obj == null) { return(null); } Type t = obj.GetType(); if (t.HasParseMethod() || !t.IsConstructable()) { return(obj.ToString()); } else if (obj is IEnumerable) { return("(" + ((IEnumerable)obj).StringJoin(",") + ")"); } else if (parseTypeOrNull == null) { return(ConstructorArguments.ToString(obj)); // can only get here if t is constructable. } else { object valueAsParseType = ArgumentCollection.ImplicitlyCastValueToType(obj, parseTypeOrNull); return(ConstructorArguments.ToString(valueAsParseType, suppressDefaults)); } }
public void Parse_Integer() { var src = new ArgumentCollection(new[] { "Sample.json", "/Timeout", "Dummy", "/Retry", "Dummy" }, '/', true); Assert.That(src.GetTimeout(), Is.EqualTo(30)); Assert.That(src.GetRetryCount(), Is.EqualTo(1)); }
public void Replace() { var src = new ArgumentCollection(new string[0], '/', true); var dest = new Installer(Format.Json, GetExamplesWith("SampleSkeleton.json")); var s0 = dest.Config.Ports[0].Proxy; var c0 = src.ReplaceDirectory(s0); Assert.That(s0, Is.EqualTo(@"%%dir%%\CubePDF\CubeProxy.exe")); Assert.That(c0, Is.Not.EqualTo(s0)); Assert.That(c0, Does.Not.StartWith("%%dir%%")); Assert.That(c0, Does.EndWith("CubeProxy.exe")); var s1 = dest.Config.Ports[0].Application; var c1 = src.ReplaceDirectory(s1); Assert.That(s1, Is.EqualTo(@"%%DIR%%\CubePDF\cubepdf.exe")); Assert.That(c1, Is.Not.EqualTo(s1)); Assert.That(c1, Does.Not.StartsWith("%%DIR%%")); Assert.That(c1, Does.EndWith("cubepdf.exe")); var s2 = dest.Config.Ports[1].Proxy; var c2 = src.ReplaceDirectory(s2); Assert.That(s2, Is.EqualTo(@"C:\Program Files\CubePDF\CubeProxy.exe")); Assert.That(c2, Is.EqualTo(s2)); var s3 = dest.Config.Ports[1].Arguments; var c3 = src.ReplaceDirectory(s3); Assert.That(s3, Is.Empty); Assert.That(c3, Is.EqualTo(s3)); }
/* ----------------------------------------------------------------- */ /// /// StartAs /// /// <summary> /// Process オブジェクトを生成し、開始します。 /// </summary> /// /// <param name="args">プログラム引数</param> /// /// <remarks> /// 開始された Process オブジェクト /// </remarks> /// /* ----------------------------------------------------------------- */ static System.Diagnostics.Process StartAs(string[] args) { var src = new ArgumentCollection(args, Argument.Windows, true); if (!src.Options.TryGetValue("Exec", out var exec)) { throw new ArgumentException("Exec"); } try { src.Options.TryGetValue("UserName", out var user); return(Process.StartAs(user, exec, args)); } catch (Exception err) { if (!src.Options.TryGetValue("ThreadID", out var id)) { throw; } Logger.Warn(LogType, err); Logger.Info(LogType, $"Use ThreadID ({id})"); return(Process.StartAs(uint.Parse(id), exec, args)); } }
public void DownloadFileFromWorkingDirAndRenameTest() { var localWriteDir = Environment.ExpandEnvironmentVariables(LocalWorkingDir); FtpDownloadAction ftpDownloadAction = new FtpDownloadAction { Id = PluginUtilities.GetUniqueId(), LoggingService = ServicesContainer.ServicesProvider.GetLoggingService(nameof(FtpDownloadAction)), Host = FtpTestCredentials.Host, Username = FtpTestCredentials.User, Password = FtpTestCredentials.Password, Port = FtpTestCredentials.Port, DirectoryPath = LocalDownloadDir, RemoteWorkingDir = "test" }; ftpDownloadAction.RenameDownloaded = true; ftpDownloadAction.RenameDownloadedNewName = "ROUTINDO_"; var fileNamePath = CreateTestFile(localWriteDir); var actionResult = ftpDownloadAction.Execute(ArgumentCollection.New() .WithArgument(FtpDownloadActionExecutionArgs.RemoteFilesCollection, new List <string>() { Path.GetFileName(fileNamePath) }) ); Assert.IsNotNull(actionResult); Assert.IsTrue(actionResult.Result); }
private object GetArgumentValue( ParameterInfo parameter, ArgumentCollection constructorArguments, IContainer container) { object value; if (constructorArguments.Contains(parameter.Name)) { value = constructorArguments[parameter.Name]; } else if (parameter.ParameterType.IsArray) { var elementType = parameter.ParameterType.GetElementType(); var arrayCastDelegate = ArrayCastDelegates[elementType]; var instances = container.GetAllInstances(elementType).ToArray(); value = arrayCastDelegate(instances); } else { value = container.GetInstance(parameter.ParameterType); } return value; }
public VonkTestContext(string informationModel = VonkConstants.Model.FhirR3) : base() { TestRequest = new VonkTestRequest(); TestArguments = new ArgumentCollection(); TestResponse = new VonkTestResponse(); InformationModel = informationModel; }
public void CreateZipOnSameExistingOptionTest() { var outputDirectory = Path.GetTempPath(); IAction action = new ZipDirectoryAction() { EraseOutputIfExists = true, UseLocationAsOutput = true, Id = PluginUtilities.GetUniqueId(), LoggingService = ServicesContainer.ServicesProvider.GetLoggingService(null) }; var testDir = Path.Combine(Path.GetTempPath(), "TEMPO_TEST"); if (!Directory.Exists(testDir)) { Directory.CreateDirectory(testDir); } File.WriteAllText(Path.Combine(outputDirectory, "TEMPO_TEST.zip"), ""); var actionResult = action.Execute(ArgumentCollection.New() .WithArgument(ZipDirectoryActionExecutionArgs.Directory, testDir)); Assert.IsNotNull(actionResult); Assert.IsTrue(actionResult.Result); }
public WatcherResult Watch() { try { if (string.IsNullOrWhiteSpace(ProcessName)) { throw new MissingArgumentException(ProcessWatcherArgs.ProcessName); } var processes = System.Diagnostics.Process.GetProcessesByName(ProcessName); var process = processes.FirstOrDefault(e => !e.HasExited); if (!NotifyOnlyOnFirstOccurrence) { _lastStatus = null; } if (WatchForStopped) { if (process == null && ( // First Time after service started !_lastStatus.HasValue // Or process was previously running || _lastStatus.Value)) { _lastStatus = false; return(WatcherResult.Succeed( ArgumentCollection.New() .WithArgument(ProcessWatcherResultArgs.ProcessName, ProcessName) )); } _lastStatus = process != null; return(WatcherResult.NotFound); } if (process != null && ( // First Time after service started !_lastStatus.HasValue // Or process was previously stopped || !_lastStatus.Value) ) { _lastStatus = true; return(WatcherResult.Succeed( ArgumentCollection.New() .WithArgument(ProcessWatcherResultArgs.ProcessName, process.ProcessName) .WithArgument(ProcessWatcherResultArgs.ProcessId, process.Id) )); } _lastStatus = process != null; return(WatcherResult.NotFound); } catch (Exception exception) { LoggingService.Error(exception); return(WatcherResult.NotFound.WithException(exception)); } }
/* ----------------------------------------------------------------- */ /// /// Set /// /// <summary> /// プログラム引数の内容を設定します。 /// </summary> /// /// <param name="args">プログラム引数</param> /// /* ----------------------------------------------------------------- */ public void Set(string[] args) { var src = new ArgumentCollection(args, '/'); var opt = src.Options; if (opt.TryGetValue(nameof(MachineName), out var pc)) { MachineName = pc; } if (opt.TryGetValue(nameof(UserName), out var user)) { UserName = user; } if (opt.TryGetValue(nameof(DocumentName), out var doc)) { DocumentName = new DocumentName(doc, Assembly.Product, IO); } if (opt.TryGetValue(nameof(Digest), out var digest)) { Digest = digest; } if (opt.TryGetValue("InputFile", out var input)) { Value.Source = input; } var dest = IO.Get(IO.Combine(Value.Destination, DocumentName.Name)); var name = dest.NameWithoutExtension; var ext = Value.Format.GetExtension(); Value.Destination = IO.Combine(dest.DirectoryName, $"{name}{ext}"); Value.DeleteSource = opt.ContainsKey("DeleteOnClose"); }
public void Parse_Empty() { var src = new ArgumentCollection(Enumerable.Empty <string>(), Argument.Dos); Assert.That(src.Count, Is.EqualTo(0)); Assert.That(src.Options.Count, Is.EqualTo(0)); }
public string Evaluate(IFormatProvider formatProvider, ArgumentCollection arguments) { return new Interpreter( formatProvider, Utilities.ThrowIfNull(arguments, "arguments"), SimpleErrorLogger.Instance).Evaluate( this.ast); }
public virtual void LoadOptionsOnly(ArgumentCollection argCollection) { FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); for (int i = 0; i < NumOptionalArgs; i++) { FieldInfo field = fields[i]; string flag = field.Name; object value = field.GetValue(this); bool isFlag = value is bool; //try { if (isFlag) { LoadFlag(field, argCollection); } else { LoadOption(field, argCollection); } } //catch (Exception e) //{ // //throw new ArgumentException("Error parsing optional flag " + field.Name + ". " + e.InnerException.Message); //} } }
public void Constructor_that_takes_method_should_set_argument_names() { var method = typeof(IFoo).GetMethod("Bar", new[] { typeof(object), typeof(object) }); var arguments = new ArgumentCollection(new object[] { "foo", "bar" }, method); arguments.ArgumentNames.Should().Equal(new[] { "argument", "argument2" }); }
public void CanLocateDefaultConstructor() { var arguments = new ArgumentCollection(); var constructor = _selector.Select(typeof(Square), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters().Length == 0); }
public DynamicDelegateContainerActivator( Type type, ConstructorInfo constructor, ArgumentCollection constructorArguments) { _constructor = constructor; _constructorArguments = constructorArguments; _activator = new DynamicDelegateActivator(type, constructor); }
public void CanLocateConstructorWithExactArgumentTypes() { var arguments = new ArgumentCollection(); arguments.Add("width", 5); var constructor = _selector.Select(typeof(Square), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters().Length == 1); }
public void CanLocateConstructorWithBaseClassArgument() { var arguments = new ArgumentCollection(); arguments.Add("shape", new Circle()); var constructor = _selector.Select(typeof(ConstructorSelectorTestModel), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters()[0].ParameterType == typeof(Shape)); }
public void CanLocateConstructorWithImplementedInterfaceArgument() { var arguments = new ArgumentCollection(); arguments.Add("square", new Square()); var constructor = _selector.Select(typeof(ConstructorSelectorTestModel), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters()[0].ParameterType == typeof(ISquare)); }
public void GetArgument_should_delegate_to_the_argument_collections_get_method_when_using_name() { // Arrange var call = A.Fake<IFakeObjectCall>(); var arguments = new ArgumentCollection(new object[] { 1, 2 }, new[] { "argument1", "argument2" }); A.CallTo(() => call.Arguments).Returns(arguments); // Act var result = call.GetArgument<int>("argument2"); // Assert result.Should().Be(2); }
public ProxyContainerActivator( IProxyDispatcher proxyDispatcher, Type type, ConstructorInfo constructor, ArgumentCollection constructorArguments, IInterceptor interceptor) { _proxyDispatcher = proxyDispatcher; _type = type; _constructor = constructor; _constructorArguments = constructorArguments; _interceptor = interceptor; }
public object CreateInstance(Type type, ArgumentCollection constructorArguments) { var constructor = _constructorSelector.Select(type, constructorArguments); if (constructor == null) { // TODO: Resource file throw new TypeLoadException("No matching constructor found on type with specified constructorArgument types."); } var args = PrepareConstructorArguments(constructor, constructorArguments); return Activator.CreateInstance(type, args); }
private object[] PrepareConstructorArguments(ConstructorInfo constructor, ArgumentCollection arguments) { var parameters = constructor.GetParameters(); var parameterCount = parameters.Length; var result = new object[parameterCount]; for (var i = 0; i < parameterCount; i++) { result[i] = arguments[parameters[i].Name]; } return result; }
/// <summary> /// Invokes the Caching Handler. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the handler chain.</param> /// <returns>Return value from the target.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { var methodName = String.Format("{0}.{1}", input.Target.GetType().FullName, input.MethodBase.Name); var callSiteDetails = new ArgumentCollection(input.Arguments.OfType<Object>()); var cachedCall = cache.TryGetResult(methodName, callSiteDetails); switch (cachedCall.Item1) { case CacheHitResult.Success: return cachedCall.Item2; case CacheHitResult.Failure: var result = getNext()(input, getNext); cache.AddToCache(methodName, callSiteDetails, result); return result; default: throw new Exception("Unknown cache status."); } }
protected virtual bool ArgumentSuppliedForParameter(ParameterInfo parameter, ArgumentCollection arguments) { object argument; if (!arguments.TryGetValue(parameter.Name, out argument)) { return false; } var argumentType = argument.GetType(); if (!parameter.ParameterType.IsAssignableFrom(argumentType)) { return false; } return true; }
public override ConstructorInfo Select(Type type, ArgumentCollection arguments) { ConstructorInfo result = null; var parameterCount = -1; var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); foreach (var constructor in constructors) { var parameters = constructor.GetParameters(); var hasUnresolvedPrimitiveParameter = false; var matchedParameters = 0; foreach (var parameter in parameters) { if (IsPrimitiveType(parameter.ParameterType)) { if (ArgumentSuppliedForParameter(parameter, arguments)) { matchedParameters++; } else { hasUnresolvedPrimitiveParameter = true; break; } } } if (!hasUnresolvedPrimitiveParameter && parameters.Length > parameterCount && arguments.Count == matchedParameters) { parameterCount = parameters.Length; result = constructor; } } return result; }
protected object[] PrepareConstructorArguments( ConstructorInfo constructor, ArgumentCollection constructorArguments, IContainer container) { if (constructorArguments == null) { constructorArguments = new ArgumentCollection(); } var parameters = constructor.GetParameters(); var args = new object[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { args[i] = GetArgumentValue(parameters[i], constructorArguments, container); } return args; }
public override ConstructorInfo Select(Type type, ArgumentCollection arguments) { ConstructorInfo result = null; var argumentTypes = arguments.GetArgumentTypes(); var constructors = type.GetConstructors(ConstructorBindingFlags); for (var i = 0; i < constructors.Length; i++) { var constructor = constructors[i]; var matched = IsMatch(constructor, argumentTypes); if (matched) { result = constructor; break; } } return result; }
private bool ArgumentsMatchesArgumentConstraints(ArgumentCollection argumentCollection) { foreach (var argumentConstraintPair in argumentCollection.AsEnumerable().Zip(this.argumentConstraints)) { if (!argumentConstraintPair.Item2.IsValid(argumentConstraintPair.Item1)) { return false; } } return true; }
public OpenTag(TagType tag, IEnumerable<INode> arguments) { _Tag = tag; _Arguments = new ArgumentCollection(arguments); }
public abstract ConstructorInfo Select(Type type, ArgumentCollection arguments);
private static bool calledWithBaseObjectAndChangeSet(ArgumentCollection args, FlatPropertyBag baseObject, TimestampedPropertyVersionDelta versionDelta) { var correct = args.Get<IVersionControlNode>(ExistingControllerArgumentName).Mutations.Single().Equals(versionDelta); correct &= args.Get<FlatPropertyBag>(ExistingObjectArgumentName).Equals(baseObject); return correct; }
private bool ArgumentsMatchesArgumentConstraints(ArgumentCollection argumentCollection) { return argumentCollection .AsEnumerable() .Zip(this.argumentConstraints, (x, y) => new { ArgumentValue = x, Constraint = y }) .All(x => x.Constraint.IsValid(x.ArgumentValue)); }
/// <summary> /// Gets the define options. /// </summary> /// <returns>An <see cref="ArgumentCollection"/> instance containing the define arguments.</returns> public ArgumentCollection GetDefineArguments() { ArgumentCollection defineArguments = new ArgumentCollection(); foreach (CrossCompileDefine define in this.Defines) { if (string.IsNullOrEmpty(define.DefineValue)) { defineArguments.Add(new CrossCompileOption(this.DefineSwitch + define.DefineName)); } else { defineArguments.Add( new CrossCompileOption(this.DefineSwitch + define.DefineName + "=" + define.DefineValue)); } } return defineArguments; }
public GenericElement(TagType tag, INode content, IEnumerable<INode> arguments) { _Tag = tag; _Arguments = new ArgumentCollection(arguments); _Content = content; }
private bool ArgumentsMatches(ArgumentCollection argumentCollection) { return this.argumentsPredicate(argumentCollection); }
public static string Evaluate(string format, ArgumentCollection arguments) { return Evaluate(null, format, arguments); }
public void Should_be_serializable_when_arguments_are_equatable() { // Arrange object collection = new ArgumentCollection( new object[] { "first argument" }, typeof(string).GetMethod("Equals", new[] { typeof(string) })); // Act // Assert collection.Should().BeBinarySerializable(); }
public Interpreter(IFormatProvider formatProvider, ArgumentCollection arguments, IErrorLogger errorLogger) { this.formatProvider = formatProvider; this.arguments = Utilities.ThrowIfNull(arguments, "arguments"); this.errorLogger = Utilities.ThrowIfNull(errorLogger, "errorLogger"); }
public static string Evaluate(IFormatProvider formatProvider, string format, ArgumentCollection arguments) { return Parse(format).Evaluate(formatProvider, arguments); }
public string Evaluate(ArgumentCollection arguments) { return Evaluate((IFormatProvider)null, arguments); }