Example #1
0
        // declare a delegate
        public GameConnection(string peerID)
        {
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            Console.WriteLine((IP = ipAddress.ToString()));
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 12000);

            // Create a TCP/IP socket
            Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket
            Socket.Bind(localEndPoint);
            Socket.Listen(10);

            ClientHandlers = new List<ClientHandler>();
            ListenThread = new Thread(Listening);
            ListenThread.Name = "Listen Thread";
            IPTable = new List<string>();
            this.peerID = peerID;

            //ListenThread.Start();
            configurator = new Configurator(IP);
            MessageBox = new List<Message>();
            PeerIDs = new List<string>();

            MessageToBroadCast = new Queue<byte[]>();
        }
Example #2
0
        /// <summary>
        /// Processes both directives that were added to the preprocessor plus any additional ones passed in.
        /// </summary>
        internal void ProcessDirectives(Configurator configurator, IEnumerable<DirectiveValue> additionalValues)
        {
            HashSet<string> singleValueNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (DirectiveValue value in _values.Concat(additionalValues))
            {
                IDirective directive;
                if (AllDirectives.TryGetValue(value.Name, out directive))
                {
                    // Make sure this isn't an extra value for a single-value directive
                    if (!directive.SupportsMultiple && !singleValueNames.Add(value.Name))
                    {
                        string line = value.Line.HasValue ? (" on line " + value.Line.Value) : string.Empty;
                        throw new Exception($"Error while processing directive{line}: #{value.Name} {value.Value}{Environment.NewLine}"
                            + "Directive was previously specified and only one value is allowed");
                    }

                    // Process the directive
                    try
                    {
                        directive.Process(configurator, value.Value);
                    }
                    catch (Exception ex)
                    {
                        string line = value.Line.HasValue ? (" on line " + value.Line.Value) : string.Empty;
                        throw new Exception($"Error while processing directive{line}: #{value.Name} {value.Value}{Environment.NewLine}{ex}");
                    }
                }
            }
        }
Example #3
0
 public void Process(Configurator configurator, string value)
 {
     if (string.IsNullOrWhiteSpace(value))
     {
         throw new Exception("NuGet source directive must have a value");
     }
     configurator.PackageInstaller.AddPackageSource(value.Trim().Trim('"'));
 }
Example #4
0
 public void Process(Configurator configurator, string value)
 {
     if (string.IsNullOrWhiteSpace(value))
     {
         throw new Exception("Assembly directive must have a value");
     }
     configurator.AssemblyLoader.Add(value.Trim().Trim('"'));
 }
 public void TestParsingRegistrations()
 {
     ConfigurationSectionHelper helper = new ConfigurationSectionHelper();
       TypeMappingConfigurationElement element = new TypeMappingConfigurationElement();
       element.TypeName = "System.Object";
       element.MapTo = "RockSolidIoc.Tests.EmptyObject";
       TypeMappingCollection collection = new TypeMappingCollection();
       collection.Add(element);
       helper.TypeMappings = collection;
       Configurator testConfigurator = new Configurator();
       IIocContainer result = testConfigurator.Configure(helper);
       object s = result.Resolve<object>();
       Assert.IsInstanceOfType(s, typeof(EmptyObject));
 }
Example #6
0
 // Methods
 static Instrumentation()
 {
     m_Configurator = new Configurator();
       m_EventSinks = new EventSinkBag();
       m_EventCategories = new EventCategoryBag();
       m_Filters = new EventFilterBag();
       m_EventSources = new EventSourceFilterBag();
       m_Cache = new Hashtable();
       m_ThreadNameCache = new Hashtable();
       m_EventAsms = new EventAssemblyBag();
       m_Configurator.ConfigRootTag = "instrumentation";
       AppDomain.CurrentDomain.ProcessExit += new EventHandler(DisposeEventSinks);
       AppDomain.CurrentDomain.DomainUnload += new EventHandler(DisposeEventSinks);
 }
 public void TestParsingResolvers()
 {
     ConfigurationSectionHelper helper = new ConfigurationSectionHelper();
       ResolverConfigurationElement resolver = new ResolverConfigurationElement();
       resolver.ResolverTypeName = "RockSolidIoc.Tests.MockFriendlyResolver";
       resolver.TypeName = "System.String";
       ResolverCollection collection = new ResolverCollection();
       collection.Add(resolver);
       helper.Resolvers = collection;
       Configurator testConfigurator = new Configurator();
       IIocContainer result = testConfigurator.Configure(helper);
       string s = result.Resolve<string>();
       MockFriendlyResolver.Mock.Verify(p => p.ResolveDependency(typeof(string), result), Times.Exactly(1));
       MockFriendlyResolver.ResetMock();
 }
 public void TestParsingLifetimeManager()
 {
     ConfigurationSectionHelper helper = new ConfigurationSectionHelper();
       LifetimeManagerMappingConfigurationElement element = new LifetimeManagerMappingConfigurationElement();
       element.LifetimeManagerTypeName = "RockSolidIoc.Tests.MockFriendlyLifetimeManager";
       element.TypeName = "System.Object";
       LifetimeManagerMappingCollection collection = new LifetimeManagerMappingCollection();
       collection.Add(element);
       helper.LifetimeManagerMappings = collection;
       Configurator testConfigurator = new Configurator();
       IIocContainer result = testConfigurator.Configure(helper);
       object s = result.Resolve<object>();
       MockFriendlyLifetimeManager.Mock.Verify(p => p.AddInstance(It.IsAny<object>()), Times.Exactly(1));
       MockFriendlyLifetimeManager.ResetMock();
 }
Example #9
0
 public UserDB(Configurator conf)
 {
     this._config = conf;
     this._sha = SHA512.Create();
     try
     {	this.BuildDBConnectionString(conf);
         this._dbcon = new NpgsqlConnection(this._db_connection_string);
         this._cmd = this._dbcon.CreateCommand();
         this._dbcon.Open();
         this.CheckForTable();
     }
     catch(Exception e)
     {
         Logger.log("Failed to establish connection: "+e.Message+"\n"+e.StackTrace, Logger.Verbosity.moderate);
         throw new FatalException("UserManager failed to connect to the database. (Reason: "+e.Message+")");
     }
 }
        public ActionResult Index()
        {
            // here we call "Configure" method
            var configurator = new Configurator<MyCoolUser,MyCoolUserRow>().Configure();

            // here we point our "Handle"-method
            configurator.Url(Url.Action("HandleUsersTable"));

            // our view-model
            var vm = new UsersViewModel()
            {
                UsersTable = configurator
            };

            // that's it
            return View("Index", vm);
        }
Example #11
0
        public ProtocolTester(String prot_spec, Protocol harness)
        {
            if(prot_spec == null || harness == null)
                throw new Exception("ProtocolTester(): prot_spec or harness is null");

            props=prot_spec;
            this.harness=harness;
            props="LOOPBACK:" + props; // add a loopback layer at the bottom of the stack

            config=new Configurator();
            top=config.setupClientStack(props, null);
            harness.DownProtocol = top;
            top.UpProtocol = harness;

            bottom = getBottomProtocol(top);
            config.startProtocolStack(bottom);
        }
        public void Recycle()
        {
            waitingDocumentConfigurator = null;
            animationManager.StopAll();
            dragPinchManager.Disable();
            // Stop tasks
            if (RenderingHandler != null)
            {
                RenderingHandler.Stop();
                RenderingHandler.RemoveMessages(RenderingHandler.MsgRenderTask);
            }

            decodingAsyncTask?.Cancel();

            // Clear caches
            CacheManager.Recycle();

            if (ScrollHandle != null && isScrollHandleInit)
            {
                ScrollHandle.DestroyLayout();
            }

            if (PdfFile != null)
            {
                PdfFile.Dispose();
                PdfFile = null;
            }

            RenderingHandler   = null;
            ScrollHandle       = null;
            isScrollHandleInit = false;
            CurrentXOffset     = CurrentYOffset = 0;
            Zoom       = 1f;
            IsRecycled = true;
            Callbacks  = new Callbacks();
            state      = State.Default;
        }
Example #13
0
        /// <summary>
        /// Gets the database instance or creates one
        /// </summary>
        /// <returns>The instance.</returns>
        /// <param name="database">Database.</param>
        public ISiaqodb GetInstance(string database)
        {
            try
            {
                //Does it exist in the dictionary...
                Siaqodb db;
                if (SiaqoDatabases != null)
                {
                    if (SiaqoDatabases.TryGetValue(database, out db))
                    {
                        return(db);
                    }
                }

                //Did not find it so add it...
                var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), database);
                var config = new Configurator();
                // Siaqodb Starter version allows you to store 100 objects per type
                // To obtain a trial or full license please visit https://www.siaqodb.com
                // If you are using a trial or fully licensed version of Siaqodb, uncomment this line and enter your key
                //Sqo.SiaqodbConfigurator.SetLicense("[Paste your provided license key here...]");
                SiaqodbConfigurator.ApplyConfigurator(config);
                db = new Siaqodb(dbpath);
                //Add the instance to the list
                SiaqoDatabases?.Add(database, db);

                return(db);
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debug.WriteLine(ex.Message);
                }
                return(null);
            }
        }
Example #14
0
        public static void EntityToReal <T>(T entity)
        {
            if (entity == null)
            {
                return;
            }

            Type type = entity.GetType();
            var  subs = Configurator.SubstitutesFor(type);

            if (subs == null)
            {
                return;
            }

            foreach (Substitutable item in subs)
            {
                int hiddenVal = ReflectionHelper.GetValue <T>(entity, item);
                var strategy  = GetStrategyFor(item);
                int realVal   = strategy.ToReal(hiddenVal);

                ReflectionHelper.SetValue <T>(entity, item, realVal);
            }
        }
Example #15
0
        public void TestCreation()
        {
            string text  = Application.dataPath + "/Core/GameSystems/Configurator/UnitTest/";
            string text2 = text + "ApplicationConfig.txt";

            FileHelper.DeleteIfExists(text2);
            Configurator configurator = new Configurator();

            Assert.IsNotNull(configurator);
            configurator.SetConfigurationPath(text);
            configurator.Init(isUnitTest: true);
            Assert.IsTrue(File.Exists(text2));
            configurator = null;
            configurator = new Configurator();
            Assert.IsNotNull(configurator);
            configurator.SetConfigurationPath(text);
            configurator.Init(isUnitTest: true);
            Type type = Type.GetType("DisneyMobile.CoreUnitySystems.Test.ConfigurableSystem_Test+ConfigurableSystem");
            IDictionary <string, object> dictionaryForSystem = configurator.GetDictionaryForSystem(type);

            Assert.That((int)dictionaryForSystem["values"].AsDic()["mTestValue3"], Is.EqualTo(42));
            FileHelper.DeleteIfExists(text2);
            configurator = null;
        }
Example #16
0
        /// <summary>
        /// Thread that is waiting for configurator result.
        /// </summary>
        private void WaitConfigurator()
        {
            int    res = -1;
            string str;
            Brush  b = Brushes.Red;

            _clockProc.WaitForExit();
            res = _clockProc.ExitCode;
            _clockProc.Close();

            str = Configurator.GetErrorMsg((ErrorCodes)res);
            if (res == (int)ErrorCodes.Success)
            {
                b = Brushes.Green;
            }

            else
            {
                b = Brushes.Red;
            }

            if (Configurator.Terminated)
            {
                return;
            }
            this.Dispatcher.Invoke((Action)(() =>
            {
                _tbConf.Foreground = b;
                _tbConf.Text = str;
                _btnConfig.IsEnabled = true;
                _circularPB.StopProgress();
                _ucPb.Visibility = System.Windows.Visibility.Hidden;
                _tbPb.Visibility = System.Windows.Visibility.Hidden;
                SetEnableNavigators(true);
            }));
        }
        public static void TryingToRetreiveANonExistentObject(Exception ex)
        {
            "Given an empty config file"
            .f(() =>
            {
                using (var writer = new StreamWriter("foo1.csx"))
                {
                    writer.Flush();
                }
            })
            .Teardown(() => File.Delete("foo1.csx"));

            "When I load the file"
            .f(() => Configurator.Load("foo1.csx"));

            "And I try and get an object named 'foo'"
            .f(() => ex = Record.Exception(() => Configurator.Get <Foo>("foo")));

            "Then an exception is thrown"
            .f(() => ex.Should().NotBeNull());

            "And the exception message contains 'foo'"
            .f(() => ex.Message.Should().Contain("foo"));
        }
Example #18
0
        public static string Serialize(Action <Configurator> func)
        {
            var configurator = new Configurator(null);

            func(configurator);

            var model = CommandModelBuilder.Build(configurator);

            var settings = new XmlWriterSettings
            {
                Indent             = true,
                IndentChars        = "  ",
                NewLineChars       = "\n",
                OmitXmlDeclaration = false
            };

            using (var buffer = new StringWriter())
                using (var xmlWriter = XmlWriter.Create(buffer, settings))
                {
                    Serialize(model).WriteTo(xmlWriter);
                    xmlWriter.Flush();
                    return(buffer.GetStringBuilder().ToString().NormalizeLineEndings());
                }
        }
        private static string GetTimePart(TimeSpan timespan, CultureInfo culture)
        {
            var formatter = Configurator.GetFormatter(culture);

            if (timespan.Days >= 7)
            {
                return(formatter.TimeSpanHumanize(TimeUnit.Week, timespan.Days / 7));
            }

            if (timespan.Days >= 1)
            {
                return(formatter.TimeSpanHumanize(TimeUnit.Day, timespan.Days));
            }

            if (timespan.Hours >= 1)
            {
                return(formatter.TimeSpanHumanize(TimeUnit.Hour, timespan.Hours));
            }

            if (timespan.Minutes >= 1)
            {
                return(formatter.TimeSpanHumanize(TimeUnit.Minute, timespan.Minutes));
            }

            if (timespan.Seconds >= 1)
            {
                return(formatter.TimeSpanHumanize(TimeUnit.Second, timespan.Seconds));
            }

            if (timespan.Milliseconds >= 1)
            {
                return(formatter.TimeSpanHumanize(TimeUnit.Millisecond, timespan.Milliseconds));
            }

            return(formatter.TimeSpanHumanize_Zero());
        }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="configurator"></param>
        public Connection(Configurator configurator)
        {
            _config = configurator;

            _timerT36 = new Timer(s => CheckTransactions(),
                                  null, 1000, Timeout.Infinite);

            _timerT6ControlTimeout = new Timer(s => CloseConnection(),
                                               null, Timeout.Infinite, Timeout.Infinite);

            _timerT7ConnectionIdleTimeout = new Timer(s => CloseConnection(),
                                                      null, Timeout.Infinite, Timeout.Infinite);

            if (_config.Mode == ConnectionMode.Active)
            {
                _timerT5ConnectSeparationTimeout = new Timer(s => TryConnect(),
                                                             null, Timeout.Infinite, Timeout.Infinite);
            }
            else
            {
                _timerT5ConnectSeparationTimeout = new Timer(s => TryListen(),
                                                             null, Timeout.Infinite, Timeout.Infinite);
            }
        }
Example #21
0
        public void CollectJsonData_NewArrayItems_DataMerged()
        {
            var firstData = DynamicJson.Serialize(new
            {
                library = new { food = new { veg = "v", fruit = "f", nuts = "n" } }
            });
            var secondData = DynamicJson.Serialize(new
            {
                library = new { food = new { bread = "b", fruit = "{f\\:", nuts = "\"nut\"" } }
            });

            var first = new Configurator(_libraryFolder.Path, NavigationIsolator.GetOrCreateTheOneNavigationIsolator());

            first.CollectJsonData(firstData.ToString());
            first.CollectJsonData(secondData.ToString());

            var     second = new Configurator(_libraryFolder.Path, NavigationIsolator.GetOrCreateTheOneNavigationIsolator());
            dynamic j      = (DynamicJson)DynamicJson.Parse(second.GetLibraryData());

            Assert.AreEqual("v", j.library.food.veg);
            Assert.AreEqual("{f\\:", j.library.food.fruit);
            Assert.AreEqual("b", j.library.food.bread);
            Assert.AreEqual("\"nut\"", j.library.food.nuts);
        }
        public void TestVfpConfig()
        {
            IConnectionStringValidator csv = new TestCsv(DbType.Vfp);
            IConnectionStringProvider  csp = new TestVfpConnectionStringProvider();

            Configurator c = new Configurator(csp, csv);

            c.Configure(_CurrentDirectory);

            IList <KeyValuePair <String, String> > terms = new List <KeyValuePair <String, String> >();

            terms.Add(new KeyValuePair <String, String>(StripBraces(Constants.ConfigTokenNames.DbType), Constants.ConfigTokenValues.DbTypeVfp));  // DbType = VFP
            terms.Add(new KeyValuePair <String, String>(StripBraces(Constants.ConfigTokenNames.DbName), Constants.ConfigTokenValues.DbNameVfp));  // DbName = HostDb
            terms.Add(new KeyValuePair <String, String>(StripBraces(Constants.ConfigTokenValues.DbNameVfp), TestConfigurator.VfpFolderName));     // Connection element - HostDb & D:\Vhost\

            IEnumerable <String> lines = File.ReadLines(_appConfigFileName).Where(line => !line.Trim().StartsWith("<!--"));

            foreach (KeyValuePair <String, String> kvp in terms)
            {
                IEnumerable <String> selectedLines = lines.Where(line => line.Contains(kvp.Value) && line.Contains(kvp.Key));
                Assert.AreEqual(1, selectedLines.Count());
                Debug.WriteLine(selectedLines.Take(1).ToList()[0]);
            }
        }
            public static string GetParseMessage(IEnumerable <string> args, Configurator configurator, bool shouldThrowOnSuccess = true)
            {
                try
                {
                    // Create the model from the configuration.
                    var model = CommandModelBuilder.Build(configurator);

                    // Parse the resulting tree from the model and the args.
                    var parser = new CommandTreeParser(model);
                    parser.Parse(args);

                    // If we get here, something is wrong.
                    if (shouldThrowOnSuccess)
                    {
                        throw new InvalidOperationException("Expected a parse exception.");
                    }

                    return(null);
                }
                catch (ParseException ex)
                {
                    return(Render(ex.Pretty));
                }
            }
        public static void TryingToRetreiveAnAnonymousValue(Foo value, bool result)
        {
            "Given a local config file containing a named Foo with a Bar of 'baz'"
            .Given(() =>
            {
                using (var writer = new StreamWriter(new LocalConfigurator().Path))
                {
                    writer.WriteLine(@"#r ""ConfigR.Features.dll""");
                    writer.WriteLine(@"using ConfigR.Features;");
                    writer.WriteLine(@"Add(""foo"", new AnonymousValuesFeature.Foo { Bar = ""baz"" });");
                    writer.Flush();
                }
            })
            .Teardown(() => File.Delete(new LocalConfigurator().Path));

            "When I try to get a Foo"
            .When(() => result = Configurator.TryGet <Foo>(out value));

            "Then the result is true"
            .Then(() => result.Should().BeTrue());

            "And the Foo has a Bar of 'baz'"
            .And(() => value.Bar.Should().Be("baz"));
        }
Example #25
0
        private void DownloadConfigBtn_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("PCSX2 Configurator: Update Config Click");

            if (!GameHelper.IsGameUsingRemoteConfig(_selectedGame))
            {
                Mouse.OverrideCursor = Cursors.Wait;
                var result = Configurator.DownloadConfig(_selectedGame, _selectedGameRemoteConfigPathTask.Result);
                Mouse.OverrideCursor = null;

                MessageDialog.Show(this,
                                   result ? MessageDialog.Type.ConfigDownloadSuccess : MessageDialog.Type.ConfigDownloadError);
            }
            else
            {
                Mouse.OverrideCursor = Cursors.Wait;
                Configurator.UpdateGameConfig(_selectedGame, _selectedGameRemoteConfigPathTask.Result);
                Mouse.OverrideCursor = null;

                MessageDialog.Show(this, MessageDialog.Type.ConfigUpdateSuccess);
            }

            InitializeConfigWindow();
        }
Example #26
0
        private void CreateConfigBtn_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("PCSX2 Configurator: Create Config Click");

            var createConfig = true;

            if (GameHelper.IsGameConfigured(_selectedGame))
            {
                var msgResult = MessageDialog.Show(this, MessageDialog.Type.ConfigOverwriteConfirm);

                if (msgResult != true)
                {
                    createConfig = false;
                }
            }

            if (!createConfig)
            {
                return;
            }
            Configurator.CreateConfig(_selectedGame);
            MessageDialog.Show(this, MessageDialog.Type.ConfigConfiguredSuccess);
            InitializeConfigWindow();
        }
Example #27
0
        public void GenerateModuleConstructorMethodsGeneratesGenericConstructors()
        {
            // Given
            Engine engine = new Engine();

            engine.Trace.AddListener(new TestTraceListener());
            Configurator configurator = new Configurator(engine);
            Type         moduleType   = typeof(GenericModule <>);
            string       expected     = $@"
                        public static Wyam.Core.Tests.Configuration.GenericModule<T> GenericModule<T>(T input)
                        {{
                            return new Wyam.Core.Tests.Configuration.GenericModule<T>(input);  
                        }}
                        public static Wyam.Core.Tests.Configuration.GenericModule<T> GenericModule<T>(System.Action<T> input)
                        {{
                            return new Wyam.Core.Tests.Configuration.GenericModule<T>(input);  
                        }}";

            // When
            string generated = configurator.GenerateModuleConstructorMethods(moduleType);

            // Then
            Assert.AreEqual(expected, generated);
        }
Example #28
0
        /// <param name="modFolder">Path to the mod folder.</param>
        public XInput(string modFolder)
        {
            var configurator      = new Configurator(modFolder);
            int numConfigurations = configurator.Configurations.Length;

            for (int x = 0; x < numConfigurations; x++)
            {
                var config = configurator.GetConfiguration <Config>(x);
                if (config.ControllerPort == -1)
                {
                    config.ControllerPort = x;
                }

                // Self-updating Controller Bindings
                var controllerId = x;
                config.ConfigurationUpdated += configurable =>
                {
                    _controllers[controllerId].Config = (Config)configurable;
                    Program.Logger.WriteLine($"[XInput/Riders] Configuration for port {controllerId} updated.");
                };

                _controllers[config.ControllerPort] = new ControllerTuple(new SharpDX.XInput.Controller((UserIndex)x), config);
            }
        }
        private static IEnumerable <string> CreateTheTimePartsWithUpperAndLowerLimits(TimeSpan timespan, CultureInfo culture, TimeUnit maxUnit, TimeUnit minUnit)
        {
            var cultureFormatter   = Configurator.GetFormatter(culture);
            var firstValueFound    = false;
            var timeUnitsEnumTypes = GetEnumTypesForTimeUnit();
            var timeParts          = new List <string>();

            foreach (var timeUnitType in timeUnitsEnumTypes)
            {
                var timepart = GetTimeUnitPart(timeUnitType, timespan, culture, maxUnit, minUnit, cultureFormatter);

                if (timepart != null || firstValueFound)
                {
                    firstValueFound = true;
                    timeParts.Add(timepart);
                }
            }
            if (IsContainingOnlyNullValue(timeParts))
            {
                var noTimeValueCultureFarmated = cultureFormatter.TimeSpanHumanize_Zero();
                timeParts = CreateTimePartsWithNoTimeValue(noTimeValueCultureFarmated);
            }
            return(timeParts);
        }
Example #30
0
        public void ErrorInConfigContainsCorrectLineNumbers()
        {
            // Given
            Engine       engine       = new Engine();
            Configurator configurator = new Configurator(engine);
            string       configScript = @"
Assemblies.Load("""");

===

class Y { };
class X { };

---

int z = 0;

foo bar;
";

            // When
            AggregateException exception = null;

            try
            {
                configurator.Configure(configScript, false);
            }
            catch (AggregateException ex)
            {
                exception = ex;
            }

            // Then
            Assert.AreEqual(1, exception.InnerExceptions.Count);
            StringAssert.StartsWith("Line 13", exception.InnerExceptions[0].Message);
        }
Example #31
0
        /// <summary>
        /// Sets up free initial data ordering for query.
        /// Free ordering is able to extract ordering direction from anywhere in any manner and
        /// apply ordering based on it to source data sequence.
        /// It is not bound to any column and has no UI.
        /// </summary>
        /// <param name="configurator">Table configurator</param>
        /// <param name="orderingExtractFunction">Ordering extraction function</param>
        /// <param name="orderingColumn">Column to apply ordering</param>
        public static void FreeOrdering
        <TSourceData, TValue, TTableData>(
            this Configurator <TSourceData, TTableData> configurator,
            Func <Query, Tuple <bool, Ordering> > orderingExtractFunction,
            Expression <Func <TSourceData, TValue> > orderingColumn
            ) where TTableData : new()
        {
            var f = new FreeFilter <TSourceData, Ordering>(configurator);

            f.Value(orderingExtractFunction);
            f.By((source, ordering) =>
            {
                switch (ordering)
                {
                case Ordering.Neutral: return(source);

                case Ordering.Ascending: return(source.OrderBy(orderingColumn));

                case Ordering.Descending: return(source.OrderByDescending(orderingColumn));
                }
                return(source);
            });
            configurator.RegisterFilter(f);
        }
        public static void RetreivingAnObject(Foo result)
        {
            "Given a config file containing a Foo with a Bar of 'baz'"
            .Given(() =>
            {
                using (var writer = new StreamWriter("foo.csx"))
                {
                    writer.WriteLine(@"#r ""ConfigR.Features.dll""");
                    writer.WriteLine(@"using ConfigR.Features;");
                    writer.WriteLine(@"Add(""foo"", new FileConfigurationFeature.Foo { Bar = ""baz"" });");
                    writer.Flush();
                }
            })
            .Teardown(() => File.Delete("foo.csx"));

            "When I load the file"
            .When(() => Configurator.Load("foo.csx"));

            "And I get the Foo"
            .And(() => result = Configurator.Get <Foo>("foo"));

            "Then the Foo has a Bar of 'baz'"
            .Then(() => result.Bar.Should().Be("baz"));
        }
        /// <summary>
        /// Handles command line request.
        /// </summary>
        /// <param name="commandRequest">Command line request.</param>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidCommand"));
                return;
            }

            if (commandRequest.Command is null)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidCommand"));
                return;
            }

            if (commandRequest.Command.Equals(Configurator.GetConstantString("CommandImport"), StringComparison.InvariantCultureIgnoreCase))
            {
                this.Import(commandRequest.Parameters);
                this.Service.ClearCache();
            }
            else
            {
                base.Handle(commandRequest);
            }
        }
Example #34
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            string defaultPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            var defaultServersPath = Path.Combine(defaultPath, "bedrockServers");
            var defaultServerName  = "bedServer";

            var serversPath = Configuration.GetValue <string>("ServersPath");
            var serverName  = Configuration.GetValue <string>("ServerName");

            if (serversPath == "")
            {
                serversPath = defaultServersPath;
            }

            if (serverName == "")
            {
                serverName = defaultServerName;
            }

            _configurator = Configurator.CreateInstance(serversPath, serverName);
        }
Example #35
0
        /// <summary>
        /// Provides table with short window containing response information that will be custom-evaluated
        /// during each server request with specified action delegate
        /// </summary>
        /// <param name="conf"></param>
        /// <param name="responseDataEvaluator">Function evaluating response info on server side</param>
        /// <param name="ui">Response information UI builder</param>
        /// <param name="where">Plugin placement - to distinguish which instance to update. Can be omitted if you have single plugin instance per table.</param>
        /// <returns></returns>
        public static Configurator <TSourceData, TTableData> ResponseInfo <TSourceData, TTableData, TResponseData>
            (this Configurator <TSourceData, TTableData> conf,
            Action <PluginConfigurationWrapper <ResponseInfoClientConfiguration> > ui,
            Func <PowerTablesData <TSourceData, TTableData>, TResponseData> responseDataEvaluator,
            string where = null)
            where TTableData : new()
        {
            var arm = new ActionBasedResponseModifier <TSourceData, TTableData>((a, r) =>
            {
                r.AdditionalData[PluginId] = responseDataEvaluator(a);
            });

            conf.RegisterResponseModifier(arm);

            conf.TableConfiguration.UpdatePluginConfig <ResponseInfoClientConfiguration>(PluginId, pc =>
            {
                if (ui != null)
                {
                    ui(pc);
                }
                pc.Configuration.ResponseObjectOverriden = true;
            }, where);
            return(conf);
        }
Example #36
0
        public static IEnumerable <ValidationResult> ValidateConsumer <TConsumer>(this Configurator configurator)
            where TConsumer : class
        {
            if (!typeof(TConsumer).HasInterface <IConsumer>())
            {
                yield return(configurator.Warning("Consumer",
                                                  $"The consumer class {TypeMetadataCache<TConsumer>.ShortName} does not implement any IConsumer interfaces"));
            }

            IEnumerable <ValidationResult> warningForMessages = ConsumerMetadataCache <TConsumer>
                                                                .ConsumerTypes.Distinct(MessageTypeComparer)
                                                                .Where(x => !(HasProtectedDefaultConstructor(x.MessageType) || HasSinglePublicConstructor(x.MessageType)))
                                                                .Select(x =>
                                                                        $"The {TypeMetadataCache.GetShortName(x.MessageType)} message should have a public or protected default constructor."
                                                                        + " Without an available constructor, MassTransit will initialize new message instances"
                                                                        + " without calling a constructor, which can lead to unpredictable behavior if the message"
                                                                        + " depends upon logic in the constructor to be executed.")
                                                                .Select(message => configurator.Warning("Message", message));

            foreach (ValidationResult message in warningForMessages)
            {
                yield return(message);
            }
        }
Example #37
0
        private static void Main(string[] args)
        {
            try
            {
                // 项目启动时,添加
                Configurator.Put(".xls", new WorkbookLoader());

                ExportHelper.ExportToLocal(@"Template\Template.xls", "out.xls",
                                           new SheetRenderer("参数渲染示例",
                                                             new ParameterRenderer("String", "Hello World!"),
                                                             new ParameterRenderer("Boolean", true),
                                                             new ParameterRenderer("DateTime", DateTime.Now),
                                                             new ParameterRenderer("Double", 3.14),
                                                             new ParameterRenderer("Image", Image.FromFile("Image/C#高级编程.jpg"))
                                                             )
                                           );
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("finished!");
        }
 // our "Handle"-method
 public ActionResult HandleUsersTable()
 {
     var configurator = new Configurator<MyCoolUser, MyCoolUserRow>().Configure();
     var handler = new PowerTablesHandler<MyCoolUser, MyCoolUserRow>(configurator);
     return handler.Handle(_dataService.GetData(), this.ControllerContext);
 }
 private IConfigurator GetToc(string tutorialId)
 {
     var conf = new Configurator<TutorialEntry,TocEntryViewModel>();
     conf.Hierarchy();
     conf.ProjectDataWith(c => c.OrderBy(x=>x.Order).Select(x => new TocEntryViewModel()
     {
         IsExpanded = true,
         IsVisible = true,
         ChildrenCount = x.SubTutorials.Count,
         Description = x.Description,
         Link =
             Url.Action("Tutorial",
                 new { tutorialId = x.Namespace.Replace("Reinforced.Lattice.Book.WebApp.App_Data.", "").Replace(".", "_") }),
         Text = x.FriendlyName,
         ParentKey = x.Parent == null ? null : x.Parent.Namespace,
         RootKey = x.Namespace,
         IsSelected = x.Namespace.EndsWith(tutorialId)
     }));
     conf.Column(c=>c.Link).DataOnly();
     conf.Column(c=>c.Description).DataOnly();
     //conf.Column(c=>c.Order).OrderableUi(c=>c.UseClientOrdering().DefaultOrdering(Ordering.Ascending)).DataOnly();
     conf.Prefetch(TutorialsList.LinearTutorialList.OrderBy(c=>c.Order));
     conf.Column(c=>c.Text).FilterValueUi(ui=>ui.ClientFiltering().Placeholder("Search documentation...").Inputdelay(10));
     return conf;
 }
Example #40
0
        public void Listening()
        {
            while (!shutdown)
            {
                try
                {
                    Console.WriteLine("Waiting for game client..");
                    Socket handler = Socket.Accept();

                    byte[] bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);

                    if (configurator != null)
                    {
                        if (configurator.Status == Configurator.State.start)
                        {
                            configurator.Parse(bytes);
                            StartConfig();
                        }
                        else
                        {
                            configurator.Status = Configurator.State.done;
                        }
                    }
                    else
                    {
                        configurator = new Configurator(IP);
                        configurator.Parse(bytes);
                        StartConfig();
                    }

                    // Create Client Handler
                    lock (ClientHandlers)
                    {
                        Console.WriteLine("GameConnection Listened :" + IP);
                        ClientHandlers.Add(new ClientHandler(this, handler));
                    }

                    Console.WriteLine(ClientHandlers.Count);
                }
                catch (Exception E)
                {

                }
            }
        }
Example #41
0
 public void StartConfig(List<string> IPTable)
 {
     System.Diagnostics.Debug.WriteLine("Start Config - Start");
     configurator = new Configurator(IP, IPTable);
     configurator.Status = Configurator.State.starting;
     System.Diagnostics.Debug.WriteLine("Start Config " + IPTable.Count);
     List<string> toConnect = configurator.IPToConnect();
     Thread.Sleep(2000);
     foreach (string ip in toConnect)
     {
         ClientHandler ch = Connect(ip);
         System.Diagnostics.Debug.WriteLine(ip + "," + ip.Count());
         ch.SendMsg(configurator.ConstructMessageConfig());
         Message msg = new Message();
         msg.msgCode = Message.PEERTABLE;
         msg.list = PeerIDs;
         ch.SendMsg(msg.Construct());
     }
 }
 public void NavigateToYourVenuesPage()
 {
     webDriver.Url = Configurator.GetConfiguratorInstance().GetBaseUrlVenues();
 }
 public static void Background()
 {
     "Given no configuration is loaded"
     .Given(() => Configurator.Unload());
 }
Example #44
0
 public Controller()
 {
     this._configuration = new Configurator();
     this._connections = new ArrayList();
     this.initialize();
 }
 public void NavigateToGovUkHomePage()
 {
     webDriver.Url = Configurator.GetConfiguratorInstance().GetBaseUrl();
 }
Example #46
0
 private void BuildDBConnectionString(Configurator conf)
 {
     this._db_connection_string =
         "Server="+conf.get_value("dbServer")+";"+
         "Database="+conf.get_value("dbDB")+";"+
         "User ID="+conf.get_value("dbUser")+";"+
         "Password="******"dbPassword")+";";
 }
Example #47
0
        protected override void SetupInternal(Configurator config)
        {
            bool initSuccess = Glfw.Init();

            if (!initSuccess)
            {
                Engine.Log.Error("Couldn't initialize glfw.", MessageSource.Glfw);
                return;
            }

            _errorCallback = ErrorCallback;
            Glfw.SetErrorCallback(_errorCallback);

#if ANGLE
            LoadLibrary("libEGL");
            LoadLibrary("libGLESv2");
            Glfw.WindowHint(Glfw.Hint.ClientApi, Glfw.ClientApi.OpenGLES);
            Glfw.WindowHint(Glfw.Hint.ContextCreationApi, Glfw.ContextApi.EGL);
            Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, 3);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Kernel32Methods.GetModuleHandle("renderdoc.dll") != IntPtr.Zero)
            {
                Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, 1);
            }
#endif

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // Macs need a very specific context to be requested.
                Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, 3);
                Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, 2);
                Glfw.WindowHint(Glfw.Hint.OpenglForwardCompat, true);
                Glfw.WindowHint(Glfw.Hint.OpenglProfile, Glfw.OpenGLProfile.Core);
            }
            else
            {
                // Version set by the angle ifdef shouldn't be overwritten.
#if !ANGLE
                Glfw.WindowHint(Glfw.Hint.ContextVersionMajor, 3);
                Glfw.WindowHint(Glfw.Hint.ContextVersionMinor, 3);
                Glfw.WindowHint(Glfw.Hint.OpenglForwardCompat, true);
                Glfw.WindowHint(Glfw.Hint.OpenglProfile, Glfw.OpenGLProfile.Core);
#endif
            }

            Glfw.Window?win = Glfw.CreateWindow((int)config.HostSize.X, (int)config.HostSize.Y, config.HostTitle);
            if (win == null || win.Value.Ptr == IntPtr.Zero)
            {
                Engine.Log.Error("Couldn't create window.", MessageSource.Glfw);
                return;
            }

            _win = win.Value;

            Glfw.SetWindowSizeLimits(_win, (int)config.RenderSize.X, (int)config.RenderSize.Y, -1, -1);

            _focusCallback = FocusCallback;
            Glfw.SetWindowFocusCallback(_win, _focusCallback);
            _resizeCallback = ResizeCallback;
            Glfw.SetFramebufferSizeCallback(_win, _resizeCallback);
            Context = new GlfwGraphicsContext(_win);
            Context.MakeCurrent();

            _keyInputCallback = KeyInput;
            Glfw.SetKeyCallback(_win, _keyInputCallback);

            _mouseButtonFunc = MouseButtonKeyInput;
            Glfw.SetMouseButtonCallback(_win, _mouseButtonFunc);

            _mouseScrollFunc = MouseScrollInput;
            Glfw.SetScrollCallback(_win, _mouseScrollFunc);

            void TextInputRedirect(Glfw.Window _, uint codePoint)
            {
                UpdateTextInput((char)codePoint);
            }

            _textInputCallback = TextInputRedirect;
            Glfw.SetCharCallback(_win, _textInputCallback);

            Glfw.Monitor[] monitors = Glfw.GetMonitors();
            for (var i = 0; i < monitors.Length; i++)
            {
                Glfw.GetMonitorPos(monitors[i], out int x, out int y);
                Glfw.VideoMode videoMode = Glfw.GetVideoMode(monitors[i]);
                var            mon       = new GlfwMonitor(new Vector2(x, y), new Vector2(videoMode.Width, videoMode.Height));
                UpdateMonitor(mon, true, i == 0);
            }

            FocusChanged(true);
            Glfw.FocusWindow(_win);

#if OpenAL
            Audio = OpenALAudioAdapter.TryCreate(this) ?? (AudioContext) new NullAudioContext();
#else
            Audio = new NullAudioContext();
#endif
        }
 public void Are_we_done()
 {
     Result result = new Configurator()
         .ForCustomer("Johnson")
         .ForUser("Bill");
 }
Example #49
0
 private Configurator GetConfigurator(Engine engine)
 {
     Configurator configurator = new Configurator(engine);
     return configurator;
 }
Example #50
0
 public Controller()
 {
     this._configuration = new Configurator();
     this.initialize();
 }