public override object Run(object obj, string[] parameters, IPropertyBag bag, IMarkupBase markup) { if (parameters == null || (parameters.Length < 2 || parameters.Length > 3)) throw new ImpressionInterpretException("Filter " + Keyword + " expects 2 or 3 parameters.", markup); // text field to bind to // selected value // text field to bind to // value field to bind to // selected value if (obj == null) return null; if (obj.GetType().GetInterface("IEnumerable") != null) { IReflector reflector = new Reflector(); bool textOnly = parameters.Length == 2; string textField = parameters[0]; string selectedField = textOnly ? parameters[1] : parameters[2]; StringBuilder optionBuilder = new StringBuilder(); IEnumerator en = ((IEnumerable) obj).GetEnumerator(); // " for quotes // ' for apostrophes // lookup the selected value object selectedObject = bag == null ? null : reflector.Eval(bag, selectedField); string selectedValue = selectedObject != null ? selectedObject.ToString() : null; if (textOnly) { while (en.MoveNext()) { object current = en.Current; object textObject = reflector.Eval(current, textField); string textString = textObject != null ? textObject.ToString() : null; string selected = (textString == selectedValue) ? " selected=\"true\"" : ""; optionBuilder.AppendFormat("<option{1}>{0}</option>", textString, selected); } } else { string valueField = parameters[1]; while(en.MoveNext()) { object current = en.Current; object textObject = reflector.Eval(current, textField); string textString = textObject != null ? textObject.ToString() : null; object valueObject = reflector.Eval(current, valueField); string valueString = valueObject != null ? valueObject.ToString() : null; string selected = (valueString == selectedValue) ? " selected=\"true\"" : ""; optionBuilder.AppendFormat("<option value=\"{0}\"{2}>{1}</option>", valueString, textString, selected); } } return optionBuilder.ToString(); } return null; }
static void Main(string[] args) { Rotor rL = new Rotor(FixedMechanicRotor.ROTOR_II); //II has notch F Rotor rM = new Rotor(FixedMechanicRotor.ROTOR_IV); //IV has notch K Rotor rR = new Rotor(FixedMechanicRotor.ROTOR_V); //V has notch A //Following WW2 Convention, it is Left-Mid-Right e.g. II IV V Rotor[] rotors = { rL, rM, rR }; Reflector re = new Reflector(FixedMechanicReflector.REFLECTOR_B); Plugboard plug = new Plugboard(new String[] { "AV", "BS", "CG", "DL", "FU", "HZ", "IN", "KM", "OW", "RX"}); //Barbarosa WindowSetting initialSetting = new WindowSetting('B', 'L', 'A'); RingSetting ringPositions = new RingSetting(2, 21, 12); //an example of naming hassle because Enigma is both namespace and class Enigma.representation.Enigma enigma = new Enigma.representation.Enigma(rotors, re, plug, ringPositions, initialSetting); string myfile = "C:\\Users\\ToshiW\\Documents\\Visual Studio 2012\\Projects\\Enigma\\Enigma\\Resources\\BarbarosaCiphertext.txt"; string input = Utility.FileToString(myfile); //Console.WriteLine(readResult); //Console.ReadLine(); //Let Enigma do its thing string result = enigma.encryptString(input); Console.WriteLine(result); Console.ReadLine(); }
private void placeReflector(Vector3 point) { float x = Mathf.Round(point.x); float z = Mathf.Round(point.z); switch(reflector) { case Reflector.BOX: placedReflector = Instantiate(reflectorPrefabBox, new Vector3(x, 1, z), Quaternion.identity) as GameObject; break; case Reflector.NE: placedReflector = Instantiate(reflectorPrefabNE, new Vector3(x, 1, z), Quaternion.identity) as GameObject; break; case Reflector.NW: placedReflector = Instantiate(reflectorPrefabNW, new Vector3(x, 1, z), Quaternion.identity) as GameObject; break; case Reflector.SE: placedReflector = Instantiate(reflectorPrefabSE, new Vector3(x, 1, z), Quaternion.identity) as GameObject; break; case Reflector.SW: placedReflector = Instantiate(reflectorPrefabSW, new Vector3(x, 1, z), Quaternion.identity) as GameObject; break; } sound.playSelectSound(); refGui.blockPlaced = true; reflector = Reflector.NONE; removePlacedHighlight(); }
public XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute) { if (operation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation"); #pragma warning suppress 56506 // Declaring contract cannot be null Reflector parentReflector = new Reflector(operation.DeclaringContract.Namespace, operation.DeclaringContract.ContractType); #pragma warning suppress 56506 // parentReflector cannot be null _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); }
public void CreateOutputOptions_should_return_expected_result() { var subject = new MapReduceOperation<BsonDocument>(_collectionNamespace, _mapFunction, _reduceFunction, _resultSerializer, _messageEncoderSettings); var subjectReflector = new Reflector(subject); var expectedResult = new BsonDocument("inline", 1); var result = subjectReflector.CreateOutputOptions(); result.Should().Be(expectedResult); }
public ManualResetEvent AddReflection(Control cntrl) { if (cntrl == null) return null; if (cntrl.IsDisposed) return null; if (Exits(cntrl)) return null; IScreener cs = new Reflector (cntrl); IProjector pj = new Projector(cs, new Reflection(cntrl.Parent.BackColor)); this.Add(pj); return ((Projector)pj).Wait; }
void Awake() { //bulletLayer = LayerMask.NameToLayer("Bullet"); enemyLayer = LayerMask.NameToLayer("Enemy"); hero = this; health = _maxHealth = 10; stamina = _maxStamina = 200; reflector = transform.Find("Reflector").GetComponent<Reflector>(); rend = GetComponent<Renderer>(); }
// TODO: Go nuts, make the signal events wire based public SteckerbrettM3(Wheel wheel0, Wheel wheel1, Wheel wheel2, Reflector reflector) { _wheel0 = wheel0; _wheel1 = wheel1; _wheel2 = wheel2; _reflector = reflector; HookupWheel0(); HookupWheel1(); HookupWheel2(); HookUpReflector(); }
public void constructor_should_initialize_subject() { var maxChunkCount = 1; var chunkSize = 16; var subject = new BsonChunkPool(maxChunkCount, chunkSize); var reflector = new Reflector(subject); subject.MaxChunkCount.Should().Be(maxChunkCount); subject.ChunkSize.Should().Be(chunkSize); reflector._disposed.Should().BeFalse(); }
private static void AddBehaviors(ContractDescription contract, bool builtInOperationBehavior) { Reflector reflector = new Reflector(contract.Namespace, contract.ContractType); foreach (OperationDescription description in contract.Operations) { System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.OperationReflector reflector2 = reflector.ReflectOperation(description); if ((reflector2 != null) && (description.DeclaringContract == contract)) { description.Behaviors.Add(new XmlSerializerOperationBehavior(reflector2, builtInOperationBehavior)); description.Behaviors.Add(new XmlSerializerOperationGenerator(new XmlSerializerImportOptions())); } } }
public void Load(Reflector.CodeModel.IAssembly item) { try { //%SystemRoot%\Microsoft.net\Framework\v2.0.50727\mscorlib.dll //Engine.Runtime.LoadAssembly(Assembly.LoadFile(Environment.ExpandEnvironmentVariables(item.Location))); ThreadStart starter2 = delegate { Engine.Runtime.LoadAssembly(Assembly.LoadFile(Environment.ExpandEnvironmentVariables(item.Location))); }; new Thread(starter2).Start(); } catch (Exception ex) { Console.Error.WriteLine("Unable to load assembly: " + item.Location); } }
public void CreateOutputOptions_should_return_expected_result() { var subject = new MapReduceOutputToCollectionOperation(_collectionNamespace, _outputCollectionNamespace, _mapFunction, _reduceFunction, _messageEncoderSettings); var subjectReflector = new Reflector(subject); var expectedResult = new BsonDocument { { "replace", _outputCollectionNamespace.CollectionName }, { "db", _outputCollectionNamespace.DatabaseNamespace.DatabaseName } }; var result = subjectReflector.CreateOutputOptions(); result.Should().Be(expectedResult); }
public EnigmaMachine() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolver); InitializeComponent(); rotorsToolStripMenuItem_Click(null, null); panel6.BackColor = Color.FromArgb(7, 7, 7); left_Rotor = new Rotor("I", "EKMFLGDQVZNTOWYHXUSPAIBRCJ", 1, 17); mid_Rotor = new Rotor("II", "AJDKSIRUXBLHWTMCQGZNPYFVOE", 1, 5); right_Rotor = new Rotor("III", "BDFHJLCPRTXVZNYEIWGAKMUSQO", 1, 22); extra_Rotor = new Rotor("IV", "ESOVPZJAYQUIRHXLNFTGKDCMWB", 1, 10); reflector = new Reflector("B", "B", "YRUHQSLDPXNGOKMIEBFZCWVJAT"); DisplayPlugboard(); Display_Rotors(); }
public bool ShowDialog(IntPtr hWndOwner) { bool flag = false; if (Environment.OSVersion.Version.Major >= 6) { var r = new Reflector("System.Windows.Forms"); uint num = 0; Type typeIFileDialog = r.GetType("FileDialogNative.IFileDialog"); object dialog = r.Call(ofd, "CreateVistaDialog"); r.Call(ofd, "OnBeforeVistaDialog", dialog); uint options = (uint)r.CallAs(typeof(System.Windows.Forms.FileDialog), ofd, "GetOptions"); options |= (uint)r.GetEnum("FileDialogNative.FOS", "FOS_PICKFOLDERS"); r.CallAs(typeIFileDialog, dialog, "SetOptions", options); object pfde = r.New("FileDialog.VistaDialogEvents", ofd); object[] parameters = new object[] { pfde, num }; r.CallAs2(typeIFileDialog, dialog, "Advise", parameters); num = (uint)parameters[1]; try { int num2 = (int)r.CallAs(typeIFileDialog, dialog, "Show", hWndOwner); flag = 0 == num2; } finally { r.CallAs(typeIFileDialog, dialog, "Unadvise", num); GC.KeepAlive(pfde); } } else { using (var fbd = new FolderBrowserDialog()) { fbd.Description = this.Title; fbd.SelectedPath = this.InitialDirectory; fbd.ShowNewFolderButton = false; if (fbd.ShowDialog(new WindowWrapper(hWndOwner)) != DialogResult.OK) return false; ofd.FileName = fbd.SelectedPath; flag = true; } } return flag; }
public void constructor_should_initialize_subject() { var baseSource = Substitute.For<IBsonChunkSource>(); var maxUnpooledChunkSize = 2; var minChunkSize = 4; var maxChunkSize = 8; var subject = new InputBufferChunkSource(baseSource, maxUnpooledChunkSize, minChunkSize, maxChunkSize); var reflector = new Reflector(subject); subject.BaseSource.Should().BeSameAs(baseSource); subject.MaxChunkSize.Should().Be(maxChunkSize); subject.MaxUnpooledChunkSize.Should().Be(maxUnpooledChunkSize); subject.MinChunkSize.Should().Be(minChunkSize); reflector._disposed.Should().BeFalse(); }
public void constructor_should_initialize_subject() { var mockBaseSource = new Mock<IBsonChunkSource>(); var initialUnpooledChunkSize = 2; var minChunkSize = 4; var maxChunkSize = 8; var subject = new OutputBufferChunkSource(mockBaseSource.Object, initialUnpooledChunkSize, minChunkSize, maxChunkSize); var reflector = new Reflector(subject); subject.BaseSource.Should().BeSameAs(mockBaseSource.Object); subject.InitialUnpooledChunkSize.Should().Be(initialUnpooledChunkSize); subject.MaxChunkSize.Should().Be(maxChunkSize); subject.MinChunkSize.Should().Be(minChunkSize); reflector._disposed.Should().BeFalse(); }
private bool ShowDialog(IntPtr hWndOwner) { bool flag; if (Environment.OSVersion.Version.Major >= 6) { var r = new Reflector("System.Windows.Forms"); uint num = 0; var typeIFileDialog = r.GetType("FileDialogNative.IFileDialog"); var dialog = Reflector.Call(_ofd, "CreateVistaDialog"); Reflector.Call(_ofd, "OnBeforeVistaDialog", dialog); var options = (uint)Reflector.CallAs(typeof(FileDialog), _ofd, "GetOptions"); options |= (uint)r.GetEnum("FileDialogNative.FOS", "FOS_PICKFOLDERS"); Reflector.CallAs(typeIFileDialog, dialog, "SetOptions", options); var pfde = r.New("FileDialog.VistaDialogEvents", _ofd); var parameters = new[] { pfde, num }; Reflector.CallAs2(typeIFileDialog, dialog, "Advise", parameters); num = (uint)parameters[1]; try { var num2 = (int)Reflector.CallAs(typeIFileDialog, dialog, "Show", hWndOwner); flag = 0 == num2; } finally { Reflector.CallAs(typeIFileDialog, dialog, "Unadvise", num); GC.KeepAlive(pfde); } } else { var fbd = new FolderBrowserDialog { Description = Title, SelectedPath = InitialDirectory }; if (fbd.ShowDialog(new WindowWrapper(hWndOwner)) != DialogResult.OK) return false; _ofd.FileName = fbd.SelectedPath; return true; } return flag; }
public void constructor_should_initialize_instance() { var channelSource = Substitute.For<IChannelSource>(); var databaseNamespace = new DatabaseNamespace("test"); var collectionNamespace = new CollectionNamespace(databaseNamespace, "test"); var query = new BsonDocument("x", 1); var firstBatch = new BsonDocument[] { new BsonDocument("y", 2) }; var cursorId = 1L; var batchSize = 2; var limit = 3; var serializer = BsonDocumentSerializer.Instance; var messageEncoderSettings = new MessageEncoderSettings(); var maxTime = TimeSpan.FromSeconds(1); var result = new AsyncCursor<BsonDocument>( channelSource, collectionNamespace, query, firstBatch, cursorId, batchSize, limit, serializer, messageEncoderSettings, maxTime); var reflector = new Reflector(result); reflector.BatchSize.Should().Be(batchSize); reflector.ChannelSource.Should().Be(channelSource); reflector.CollectionNamespace.Should().Be(collectionNamespace); reflector.Count.Should().Be(firstBatch.Length); reflector.CurrentBatch.Should().BeNull(); reflector.CursorId.Should().Be(cursorId); reflector.Disposed.Should().BeFalse(); reflector.FirstBatch.Should().Equal(firstBatch); reflector.Limit.Should().Be(limit); reflector.MaxTime.Should().Be(maxTime); reflector.MessageEncoderSettings.Should().BeEquivalentTo(messageEncoderSettings); reflector.Query.Should().Be(query); reflector.Serializer.Should().Be(serializer); }
public bool ShowDialog(IntPtr hWndOwner) { if ((Environment.OSVersion.Version.Major >= 6) && !this.UseOldDialog) { Reflector reflector = new Reflector("System.Windows.Forms"); uint num = 0; Type type = reflector.GetType("FileDialogNative.IFileDialog"); object obj2 = reflector.Call(this.ofd, "CreateVistaDialog", new object[0]); reflector.Call(this.ofd, "OnBeforeVistaDialog", new object[] {obj2}); uint num2 = (uint) reflector.CallAs(typeof (FileDialog), this.ofd, "GetOptions", new object[0]); num2 |= (uint) reflector.GetEnum("FileDialogNative.FOS", "FOS_PICKFOLDERS"); reflector.CallAs(type, obj2, "SetOptions", new object[] {num2}); object obj3 = reflector.New("FileDialog.VistaDialogEvents", new object[] {this.ofd}); object[] parameters = new object[] {obj3, num}; reflector.CallAs2(type, obj2, "Advise", parameters); num = (uint) parameters[1]; try { int num3 = (int) reflector.CallAs(type, obj2, "Show", new object[] {hWndOwner}); return (0 == num3); } finally { reflector.CallAs(type, obj2, "Unadvise", new object[] {num}); GC.KeepAlive(obj3); } } FolderBrowserDialogEx ex = new FolderBrowserDialogEx(); ex.Description = this.Title; ex.SelectedPath = this.InitialDirectory; ex.ShowNewFolderButton = true; ex.ShowEditBox = true; ex.ShowFullPathInEditBox = true; if (ex.ShowDialog(new WindowWrapper(hWndOwner)) != DialogResult.OK) { return false; } this.ofd.FileName = ex.SelectedPath; return true; }
public void RegisterRunSeatDispatcher(FrameworkElement el, Grid container, int rowPosition) { _buildSeatDispatcher = new Action<Reflector>(model => { container.RowDefinitions[rowPosition].Height = new GridLength(_seatDispatcherHeight); View.SetModel(el, model.Target); model.SetProperty<System.Func<bool, Luna.Infrastructure.Domain.ISimpleEmployee, bool>>("TrySubmitChanged", (test, employee) => { if (test == false && IsDirty == false) { SubmitSeatChanges(new[] { _attendances.FirstOrDefault(o => o.Profile.Equals(employee)) }, false); } return !IsDirty; // IsDirty means can't call UpdateSchedule }); model.SetProperty<Action<int>>("OccupationsChanged", (i) => { var index = i == -1 ? BindableAgents.IndexOf(SelectedAgent) : i; AgentOccupations[index] = BindableAgents[index].SaftyGetProperty<IEnumerable, IWorkingAgent>(o => o.Occupations); this.QuietlyReload(ref _agentOccupations, "AgentOccupations"); }); model.SetProperty<Action<IList<IEnumerable>>>("OccupationsReloaded", (list) => { AgentOccupations = (from IWorkingAgent a in BindableAgents where a.Occupations != null select (IEnumerable)a.Occupations).ToList(); }); _seatDispatcherPresenter = model; }); _destroySeatDispatcher = new Action(() => { _seatDispatcherHeight = container.RowDefinitions[rowPosition].ActualHeight; View.SetModel(el, null); container.RowDefinitions[rowPosition].Height = new GridLength(0); }); }
public static LifeListRootObjectWrapper GetLifeListRootObjectWrapper(this LifelistActivator activator) { return(Reflector.GetInstanceFieldByName(activator, "m_RootObjectWrapper", ReflectionWays.SystemReflection) as LifeListRootObjectWrapper); }
public static TestAssembly TestAssembly(Assembly assembly = null, string configFileName = null) { return(new TestAssembly(Reflector.Wrap(assembly ?? Assembly.GetExecutingAssembly()), configFileName ?? AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)); }
public static ExplicitEncryptionLibMongoCryptController _libMongoCryptController(this ClientEncryption clientEncryption) { return((ExplicitEncryptionLibMongoCryptController)Reflector.GetFieldValue(clientEncryption, nameof(_libMongoCryptController))); }
public static IReflectionMethodInfo ReflectionMethodInfo <TClass>(string methodName) { return(Reflector.Wrap(typeof(TClass).GetMethod(methodName))); }
static Mapping() { MappingRepository <bool> .Mapping = GetValue(ctx => ParseHtmlBool(ctx.Input)); MappingRepository <byte> .Mapping = GetValue(ctx => byte.Parse(ctx.Input)); MappingRepository <sbyte> .Mapping = GetValue(ctx => sbyte.Parse(ctx.Input)); MappingRepository <short> .Mapping = GetValue(ctx => short.Parse(ctx.Input)); MappingRepository <ushort> .Mapping = GetValue(ctx => ushort.Parse(ctx.Input)); MappingRepository <int> .Mapping = GetValue(ctx => int.Parse(ctx.Input)); MappingRepository <uint> .Mapping = GetValue(ctx => uint.Parse(ctx.Input)); MappingRepository <long> .Mapping = GetValue(ctx => long.Parse(ctx.Input)); MappingRepository <ulong> .Mapping = GetValue(ctx => ulong.Parse(ctx.Input)); MappingRepository <float> .Mapping = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (float)ReflectionTools.ParsePercentage(ctx.Input, typeof(float), CultureInfo.CurrentCulture) : float.Parse(ctx.Input)); MappingRepository <double> .Mapping = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (double)ReflectionTools.ParsePercentage(ctx.Input, typeof(double), CultureInfo.CurrentCulture) : double.Parse(ctx.Input)); MappingRepository <decimal> .Mapping = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (decimal)ReflectionTools.ParsePercentage(ctx.Input, typeof(decimal), CultureInfo.CurrentCulture) : decimal.Parse(ctx.Input)); MappingRepository <DateTime> .Mapping = GetValue(ctx => DateTime.Parse(ctx.HasInput ? ctx.Input : ctx.Inputs["Date"] + " " + ctx.Inputs["Time"]).FromUserInterface()); MappingRepository <Guid> .Mapping = GetValue(ctx => Guid.Parse(ctx.Input)); MappingRepository <TimeSpan> .Mapping = GetValue(ctx => { var dateFormatAttr = ctx.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>(); if (dateFormatAttr != null) { return(DateTime.ParseExact(ctx.Input, dateFormatAttr.Format, CultureInfo.CurrentCulture).TimeOfDay); } else { return(TimeSpan.Parse(ctx.Input)); } }); MappingRepository <SqlHierarchyId> .Mapping = GetValue(ctx => SqlHierarchyId.Parse(ctx.Input)); MappingRepository <ColorEmbedded> .Mapping = GetValue(ctx => ctx.Input.HasText() ? ColorEmbedded.FromRGBHex(ctx.Input) : null); MappingRepository <bool?> .Mapping = GetValueNullable(ctx => ParseHtmlBool(ctx.Input)); MappingRepository <byte?> .Mapping = GetValueNullable(ctx => byte.Parse(ctx.Input)); MappingRepository <sbyte?> .Mapping = GetValueNullable(ctx => sbyte.Parse(ctx.Input)); MappingRepository <short?> .Mapping = GetValueNullable(ctx => short.Parse(ctx.Input)); MappingRepository <ushort?> .Mapping = GetValueNullable(ctx => ushort.Parse(ctx.Input)); MappingRepository <int?> .Mapping = GetValueNullable(ctx => int.Parse(ctx.Input)); MappingRepository <uint?> .Mapping = GetValueNullable(ctx => uint.Parse(ctx.Input)); MappingRepository <long?> .Mapping = GetValueNullable(ctx => long.Parse(ctx.Input)); MappingRepository <ulong?> .Mapping = GetValueNullable(ctx => ulong.Parse(ctx.Input)); MappingRepository <float?> .Mapping = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (float)ReflectionTools.ParsePercentage(ctx.Input, typeof(float), CultureInfo.CurrentCulture) : float.Parse(ctx.Input)); MappingRepository <double?> .Mapping = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (double)ReflectionTools.ParsePercentage(ctx.Input, typeof(double), CultureInfo.CurrentCulture) : double.Parse(ctx.Input)); MappingRepository <decimal?> .Mapping = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (decimal)ReflectionTools.ParsePercentage(ctx.Input, typeof(decimal), CultureInfo.CurrentCulture) : decimal.Parse(ctx.Input)); MappingRepository <DateTime?> .Mapping = GetValue(ctx => { var input = ctx.HasInput ? ctx.Input : " ".CombineIfNotEmpty(ctx.Inputs["Date"], ctx.Inputs["Time"]); if (input.HasText()) { DateTime dt; if (DateTime.TryParse(input, out dt)) { return(dt.FromUserInterface()); } else { SmartDateTimeSpan sts; string error = SmartDateTimeSpan.TryParse(input, out sts); if (!error.HasText()) { dt = sts.ToDateTime(); return(dt.FromUserInterface()); } } } return((DateTime?)null); //return input.HasText() ? DateTime.Parse(input).FromUserInterface() : (DateTime?)null; }); MappingRepository <Guid?> .Mapping = GetValueNullable(ctx => Guid.Parse(ctx.Input)); MappingRepository <TimeSpan?> .Mapping = GetValue(ctx => { if (ctx.Input.IsNullOrEmpty()) { return((TimeSpan?)null); } var dateFormatAttr = ctx.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>(); if (dateFormatAttr != null) { return(DateTime.ParseExact(ctx.Input, dateFormatAttr.Format, CultureInfo.CurrentCulture).TimeOfDay); } else { return(TimeSpan.Parse(ctx.Input)); } }); MappingRepository <string> .Mapping = StringTrim; }
public static IMongoClient _mongocryptdClient(this AutoEncryptionLibMongoCryptController libMongoCryptController) { return((IMongoClient)Reflector.GetFieldValue(libMongoCryptController, nameof(_mongocryptdClient))); }
public static int Main(string[] args) { var asm = typeof(SingleFileTestRunner).Assembly; Console.WriteLine("Running assembly:" + asm.FullName); var diagnosticSink = new ConsoleDiagnosticMessageSink(); var testsFinished = new TaskCompletionSource(); var testSink = new TestMessageSink(); var summarySink = new DelegatingExecutionSummarySink(testSink, () => false, (completed, summary) => Console.WriteLine($"Tests run: {summary.Total}, Errors: {summary.Errors}, Failures: {summary.Failed}, Skipped: {summary.Skipped}. Time: {TimeSpan.FromSeconds((double)summary.Time).TotalSeconds}s")); var resultsXmlAssembly = new XElement("assembly"); var resultsSink = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly); testSink.Execution.TestSkippedEvent += args => { Console.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); }; testSink.Execution.TestFailedEvent += args => { Console.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{Xunit.ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{Xunit.ExceptionUtility.CombineStackTraces(args.Message)}"); }; testSink.Execution.TestAssemblyFinishedEvent += args => { Console.WriteLine($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}"); testsFinished.SetResult(); }; var assemblyConfig = new TestAssemblyConfiguration() { // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner PreEnumerateTheories = false, }; var xunitTestFx = new SingleFileTestRunner(diagnosticSink); var asmInfo = Reflector.Wrap(asm); var asmName = asm.GetName(); var discoverySink = new TestDiscoverySink(); var discoverer = xunitTestFx.CreateDiscoverer(asmInfo); discoverer.Find(false, discoverySink, TestFrameworkOptions.ForDiscovery(assemblyConfig)); discoverySink.Finished.WaitOne(); XunitFilters filters = new XunitFilters(); // Quick hack wo much validation to get no traits passed Dictionary <string, List <string> > noTraits = new Dictionary <string, List <string> >(); for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-notrait", StringComparison.OrdinalIgnoreCase)) { var traitKeyValue = args[i + 1].Split("=", StringSplitOptions.TrimEntries); if (!noTraits.TryGetValue(traitKeyValue[0], out List <string> values)) { noTraits.Add(traitKeyValue[0], values = new List <string>()); } values.Add(traitKeyValue[1]); } } foreach (KeyValuePair <string, List <string> > kvp in noTraits) { filters.ExcludedTraits.Add(kvp.Key, kvp.Value); } var filteredTestCases = discoverySink.TestCases.Where(filters.Filter).ToList(); var executor = xunitTestFx.CreateExecutor(asmName); executor.RunTests(filteredTestCases, resultsSink, TestFrameworkOptions.ForExecution(assemblyConfig)); resultsSink.Finished.WaitOne(); var failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0; return(failed ? 1 : 0); }
/// <summary> /// Enumerates the commands representing the scenarios defined by the <paramref name="method"/>. /// </summary> /// <param name="method">The scenario method.</param> /// <returns>An instance of <see cref="IEnumerable{ITestCommand}"/> representing the scenarios defined by the <paramref name="method"/>.</returns> /// <remarks>This method may be overridden.</remarks> protected virtual IEnumerable <ICommand> EnumerateScenarioCommands(IMethodInfo method) { Guard.AgainstNullArgument("method", method); Guard.AgainstNullArgumentProperty("method", "MethodInfo", method.MethodInfo); var parameters = method.MethodInfo.GetParameters(); if (!parameters.Any()) { return(new[] { new Command(new MethodCall(method)) }); } var commands = new List <ICommand>(); var ordinal = 0; foreach (var arguments in GetArgumentCollections(method.MethodInfo)) { var closedTypeMethod = method; Type[] typeArguments = null; if (method.MethodInfo != null && method.MethodInfo.IsGenericMethodDefinition) { typeArguments = ResolveTypeArguments(method, arguments).ToArray(); closedTypeMethod = Reflector.Wrap(method.MethodInfo.MakeGenericMethod(typeArguments)); } var generatedArguments = new List <Argument>(); for (var missingArgumentIndex = arguments.Length; missingArgumentIndex < parameters.Length; ++missingArgumentIndex) { var parameterType = parameters[missingArgumentIndex].ParameterType; if (parameterType.IsGenericParameter) { Type concreteType = null; var typeParameters = method.MethodInfo.GetGenericArguments(); for (var typeParameterIndex = 0; typeParameterIndex < typeParameters.Length; ++typeParameterIndex) { if (typeParameters[typeParameterIndex] == parameterType) { concreteType = typeArguments[typeParameterIndex]; break; } } if (concreteType == null) { var message = string.Format( CultureInfo.CurrentCulture, "The type of parameter \"{0}\" cannot be resolved.", parameters[missingArgumentIndex].Name); throw new InvalidOperationException(message); } parameterType = concreteType; } generatedArguments.Add(new Argument(parameterType)); } var methodCall = new MethodCall(closedTypeMethod, arguments.Concat(generatedArguments).ToArray(), typeArguments, ++ordinal); commands.Add(new Command(methodCall)); } return(commands); }
protected override IObjectSpecImmutable LoadSpecification(Reflector reflector) { return(reflector.LoadSpecification <IObjectSpecImmutable>(typeof(TestDomainObject))); }
public void Complete_cannotBecomeTenDigits_TestMethod() { BSNVerification verification = new BSNVerification(); Exception exception = null; foreach (string cannotBecomeNineDigit in cannotBecomeNineDigits) { try { string nineDigit = verification.Complete(cannotBecomeNineDigit); Assert.Inconclusive("It should not be possible that {0} completed into {1}", Reflector.GetNameSeparatorValue(new { cannotBecomeNineDigit }), Reflector.GetNameSeparatorValue(new { nineDigit })); } catch (Exception ex) { exception = ex; continue; } } throw exception; }
public static IWorkingContext GetProjectViewContext(this LifelistActivator activator) { return(Reflector.GetInstanceFieldByName(activator, "m_ProjectViewContext", ReflectionWays.SystemReflection) as IWorkingContext); }
public void Dispose_should_dispose_subject() { var subject = new ByteArrayChunk(1); subject.Dispose(); var reflector = new Reflector(subject); reflector._disposed.Should().BeTrue(); }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="eventManager">Manages SMAPI events.</param> /// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param> /// <param name="modRegistry">Tracks the installed mods.</param> /// <param name="reflection">Simplifies access to private code.</param> /// <param name="onModMessageReceived">A callback to invoke when a mod message is received.</param> /// <param name="logNetworkTraffic">Whether to log network traffic.</param> public SMultiplayer(IMonitor monitor, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, Reflector reflection, Action <ModMessageModel> onModMessageReceived, bool logNetworkTraffic) { this.Monitor = monitor; this.EventManager = eventManager; this.JsonHelper = jsonHelper; this.ModRegistry = modRegistry; this.Reflection = reflection; this.OnModMessageReceived = onModMessageReceived; this.LogNetworkTraffic = logNetworkTraffic; }
public void WriteString_should_write_expected_bytes_when_size_is_near_tempUtf8_length( [Values(-1, 0, 1)] int delta) { var stream = new MemoryStream(); var subject = new BsonStreamAdapter(stream); var subjectReflector = new Reflector(subject); var size = subjectReflector._tempUtf8.Length + delta; var length = size - 1; var value = new string('a', length); var expectedBytes = BitConverter.GetBytes(length + 1).Concat(Enumerable.Repeat<byte>(97, length)).Concat(new byte[] { 0 }).ToArray(); subject.WriteString(value, Utf8Encodings.Strict); stream.ToArray().Should().Equal(expectedBytes); }
public static IOperationExecutor _operationExecutor(this MongoDatabase obj) => (IOperationExecutor)Reflector.GetFieldValue(obj, nameof(_operationExecutor));
public void constructor_should_initialize_instance( [Values(false, true)] bool ownsStream) { var stream = Substitute.For<Stream>(); var subject = new BsonStreamAdapter(stream, ownsStream: ownsStream); var subjectReflector = new Reflector(subject); subjectReflector._disposed.Should().BeFalse(); subjectReflector._ownsStream.Should().Be(ownsStream); subjectReflector._stream.Should().Be(stream); subjectReflector._temp.Should().NotBeNull(); subjectReflector._tempUtf8.Should().NotBeNull(); }
public static IReflectionTypeInfo ReflectionTypeInfo <TClass>() { return(Reflector.Wrap(typeof(TClass))); }
private static void validateGeneratedNumber(BSNVerification verification, string generatedBSN) { bool validBSN = verification.IsValid(generatedBSN); Assert.IsTrue(validBSN, "Generated {0} is invalid", Reflector.GetNameSeparatorValue(new { generatedBSN })); }
public static XunitTestAssembly XunitTestAssembly(Assembly assembly = null, string configFileName = null) { return(new XunitTestAssembly(Reflector.Wrap(assembly ?? Assembly.GetExecutingAssembly()), configFileName)); }
private static object _mechanism(GssapiAuthenticator obj) { return(Reflector.GetFieldValue(obj, nameof(_mechanism))); }
public static string GetKey(object queryName) { return(queryName is Type t?Reflector.CleanTypeName(EnumEntity.Extract(t) ?? t) : queryName.ToString() !); }
public static string _mechanism_serviceName(this GssapiAuthenticator obj) { var mechanism = _mechanism(obj); return((string)Reflector.GetFieldValue(mechanism, "_serviceName")); }
public void Dispose_should_dispose_subject() { var stream = Substitute.For<Stream>(); var subject = new BsonStreamAdapter(stream); subject.Dispose(); var subjectReflector = new Reflector(subject); subjectReflector._disposed.Should().BeTrue(); }
public ExternalNamespaceNameSource(string @namespace, IEnumerable <Assembly> assemblies, Reflector reflector) { this.reflector = reflector; Argument.RequireNotNullAndNotEmpty("namespace", @namespace); Argument.RequireNotNull("assemblies", assemblies); // this all is horribly inefficient, especially if using multiple namespaces from a single assembly // but it can wait for now this.typeCache = assemblies.SelectMany(a => a.GetExportedTypes()) .Where(t => t.Namespace == @namespace) .ToDictionary(t => t.Name); if (this.typeCache.Count == 0) { throw new NotImplementedException("ExternalNamespaceNameSource: No types in " + @namespace); } this.memberCache = this.typeCache.Values .SelectMany(t => t.GetMethods()) .Where(m => m.IsStatic) .Where(m => m.IsDefined <ExtensionAttribute>(false)) .GroupBy(m => m.Name) .ToDictionary(g => g.Key, g => g.ToArray()); }
public static IAsyncCursor <TIn> _wrapped <TIn, TOut>(this BatchTransformingAsyncCursor <TIn, TOut> obj) => (IAsyncCursor <TIn>)Reflector.GetFieldValue(obj, nameof(_wrapped));
public static CryptClient _cryptClient(this LibMongoCryptControllerBase libMongoCryptController) { return((CryptClient)Reflector.GetFieldValue(libMongoCryptController, nameof(_cryptClient))); }
// private fields public static bool _disposed(this ChannelSourceHandle obj) => (bool)Reflector.GetFieldValue(obj, nameof(_disposed));
public static bool _mechanism_canonicalizeHostName(this GssapiAuthenticator obj) { var mechanism = _mechanism(obj); return((bool)Reflector.GetFieldValue(mechanism, "_canonicalizeHostName")); }
protected override IObjectSpecImmutable LoadSpecification(Reflector reflector) { return reflector.LoadSpecification<IObjectSpecImmutable>(typeof (ISet<TestPoco>)); }
public static ReferenceCounted <IChannelSource> _reference(this ChannelSourceHandle obj) => (ReferenceCounted <IChannelSource>)Reflector.GetFieldValue(obj, nameof(_reference));
public void Dispose_should_not_dispose_forked_handle() { var subject = new ByteArrayChunk(1); var forked = subject.Fork(); subject.Dispose(); var reflector = new Reflector((ByteArrayChunk)forked); reflector._disposed.Should().BeFalse(); }
// TODO: Handle by-ref public override object Eval() { object target = _target.Eval(); return(Reflector.CallInstanceMethod(_memberName, null, target, new object[0])); }
public void constructor_should_use_false_as_the_default_value_for_ownsStream() { var stream = Substitute.For<Stream>(); var subject = new BsonStreamAdapter(stream); var subjectReflector = new Reflector(subject); subjectReflector._ownsStream.Should().BeFalse(); }
public static void HandleChannelException(this Server server, IConnection connection, Exception ex) { Reflector.Invoke(server, nameof(HandleChannelException), connection, ex); }
public void Dispose_can_be_called_multiple_times() { var stream = Substitute.For<Stream>(); var subject = new BsonStreamAdapter(stream); subject.Dispose(); subject.Dispose(); var subjectReflector = new Reflector(subject); subjectReflector._disposed.Should().BeTrue(); }
public static bool IsStateChangeError(this Server server, ServerErrorCode?code, string message) { return((bool)Reflector.Invoke(server, nameof(IsStateChangeError), code, message)); }
public override void SetUp() { base.SetUp(); var cache = new ImmutableInMemorySpecCache(); ReflectorConfiguration.NoValidate = true; var reflectorConfiguration = new ReflectorConfiguration(new Type[] {}, new Type[] {}, new string[] {}); facetFactory = new RemoveIgnoredMethodsFacetFactory(0); var menuFactory = new NullMenuFactory(); var classStrategy = new DefaultClassStrategy(reflectorConfiguration); var metamodel = new Metamodel(classStrategy, cache); Reflector = new Reflector(classStrategy, metamodel, reflectorConfiguration, menuFactory, new IFacetDecorator[] {}, new IFacetFactory[] {facetFactory}); }
public static bool IsRecovering(this Server server, ServerErrorCode?code, string message) { return((bool)Reflector.Invoke(server, nameof(IsRecovering), code, message)); }
/// <summary> /// Exports a reflection. /// </summary> //[ImplementsMethod] public static object export(Reflector/*!*/ reflector, bool doReturn) { if (reflector == null) PhpException.ArgumentNull("reflector"); // TODO: return null; }
protected virtual string GetComponentName(Type type) { return(Reflector.CleanTypeName(type)); }