示例#1
0
        public async Task Initialize()
        {
            _devices  = new List <TurnOnOffDevice>();
            _readers  = new List <ReaderDevice>();
            _displays = new List <DisplayDevice>();

            Devices           = new List <ITurnOnOffModule>();
            Readers           = new List <IReaderModule>();
            Displays          = new List <IDisplayModule>();
            _conditions       = new List <Condition>();
            _conditionManager = new ConditionManager(_conditions, Devices);

            var config = new BridgeConfiguration(StationHelper.GetDeviceID(), "com.guybrush")
            {
                ModelName       = "Guybrush Bridge",
                DeviceName      = "Guybrush Smart Home",
                ApplicationName = "Guybrush Station",
                Vendor          = "Guybrush"
            };

            _homeDevice = new SmarthomeAdapter(config, _conditionManager);
            await AllJoynDsbServiceManager.Current.StartAsync(_homeDevice);

            Status = StationStatus.Running;
        }
示例#2
0
        public AccountFactory(BridgeConfiguration configuration, IServiceProvider serviceProvider)
        {
            _configuration   = configuration;
            _serviceProvider = serviceProvider;

            _accounts = new Dictionary <string, IAccountController>();
        }
示例#3
0
        internal static CertificateGenerator GetCertificateGeneratorInstance(BridgeConfiguration config)
        {
            if (s_certificateGenerator == null)
            {
                lock (s_certificateHelperLock)
                {
                    if (s_certificateGenerator == null)
                    {
                        s_certificateGenerator = new CertificateGenerator()
                        {
                            CertificatePassword = config.BridgeCertificatePassword,
                            CrlUriBridgeHost    = string.Format("http://{0}:{1}", config.BridgeHost, config.BridgePort),
                            CrlUriRelativePath  = s_crlUriRelativePath,
                            ValidityPeriod      = config.BridgeCertificateValidityPeriod
                        };

                        // Upon creation, we want to immediately get the authority certificate and install it
                        // as it means we are about to run a test requiring certs
                        CertificateManager.InstallCertificateToRootStore(s_certificateGenerator.AuthorityCertificate.Certificate);
                    }
                }
            }

            return(s_certificateGenerator);
        }
示例#4
0
        internal static string EnsureSslPortCertificateInstalled(BridgeConfiguration configuration)
        {
            // Ensure the https certificate is installed before this endpoint resource is used
            X509Certificate2 cert = CertificateManager.CreateAndInstallLocalMachineCertificates(GetCertificateGeneratorInstance(configuration));

            // Ensure http.sys has been told to use this certificate on the https port
            CertificateManager.InstallSSLPortCertificate(cert.Thumbprint, configuration.BridgeHttpsPort);

            return(cert.Thumbprint);
        }
        public SmarthomeAdapter(BridgeConfiguration configuration, ConditionManager conditionMgr) : base(configuration)
        {
            _conditionManager = conditionMgr;

            _abo = new AdapterBusObject("Guybrush");
            AdapterInterface conditionInterface = new AdapterInterface("com.guybrush.station.conditions");

            var addConInputParams = new List <AdapterValue>();

            addConInputParams.Add(new AdapterValue("SourceDeviceType", -1));
            addConInputParams.Add(new AdapterValue("SourceDevice", ""));
            addConInputParams.Add(new AdapterValue("TargetDevice", ""));
            addConInputParams.Add(new AdapterValue("RequiredValue", -1));
            addConInputParams.Add(new AdapterValue("ConditionType", -1));
            addConInputParams.Add(new AdapterValue("TargetValue", -1));

            var addConOutParams = new List <AdapterValue>();

            addConOutParams.Add(new AdapterValue("Response", ""));

            AdapterMethod addCondAttr = new AdapterMethod("AddCondition", "Calling this method will add new condition.", AddCondition, addConInputParams, addConOutParams);

            conditionInterface.Methods.Add(addCondAttr);



            var getCondOutParams = new List <AdapterValue>();

            getCondOutParams.Add(new AdapterValue("SourceDeviceType", ""));
            getCondOutParams.Add(new AdapterValue("SourceDevice", ""));
            getCondOutParams.Add(new AdapterValue("TargetDevice", ""));
            getCondOutParams.Add(new AdapterValue("RequiredValue", ""));
            getCondOutParams.Add(new AdapterValue("ConditionType", ""));
            getCondOutParams.Add(new AdapterValue("TargetValue", ""));

            AdapterMethod getCondAttr = new AdapterMethod("GetConditions", "Calling this method returns list of conditions", GetConditions, null, getCondOutParams);

            conditionInterface.Methods.Add(getCondAttr);

            var removeCondInputParams = new List <AdapterValue>();

            removeCondInputParams.Add(new AdapterValue("SourceDevice", ""));
            removeCondInputParams.Add(new AdapterValue("TargetDevice", ""));

            var removeConOutParams = new List <AdapterValue>();

            removeConOutParams.Add(new AdapterValue("Response", ""));

            AdapterMethod removeCondAttr = new AdapterMethod("RemoveCondition", "Calling this method will remove a condition", RemoveCondition, removeCondInputParams, removeConOutParams);

            conditionInterface.Methods.Add(removeCondAttr);

            _abo.Interfaces.Add(conditionInterface);
            BusObjects.Add(_abo);
        }
示例#6
0
        internal static string EnsureHttpsCertificateInstalled(BridgeConfiguration configuration)
        {
            // Ensure the https certificate is installed before this endpoint resource is used
            string certThumbPrint = CertificateManager.InstallMyCertificate(configuration,
                                                                            configuration.BridgeHttpsCertificate);

            // Ensure http.sys has been told to use this certificate on the https port
            CertificateManager.InstallSSLPortCertificate(certThumbPrint, configuration.BridgeHttpsPort);

            return(certThumbPrint);
        }
示例#7
0
        private void _processContentConfig(BridgeContentConfig contentConfig, Stream stream)
        {
            var    serializer          = new SerializerBuilder().ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull).Build();
            var    watch               = new Stopwatch();
            string serializationFolder = BridgeConfiguration.GetConfig().SerializationFolder;

            _clearTempFolder();
            watch.Start();

            //have this driven by config
            var serializationPath     = $"{serializationFolder}/content/{contentConfig.Name}";
            var tempGUID              = DateTime.Now.Ticks.ToString();
            var tempSerializationPath = $"{serializationFolder}/temp/{tempGUID}/{contentConfig.Name}";
            var pageTypes             = contentConfig.GetPageTypes();
            var fieldsToIgnore        = contentConfig.GetIgnoreFields();
            var path = contentConfig.Query;

            //TODO: Query to see if page types exist, if DOESNT, display that...
            MultiDocumentQuery docs = DocumentHelper.GetDocuments().Path(path).Types(pageTypes.ToArray()).AllCultures().FilterDuplicates();
            var treeNodes           = docs.ToList <TreeNode>();

            foreach (var treeNode in treeNodes)
            {
                watch.Reset();
                watch.Start();
                var mappedItem = treeNode.Adapt <BridgeTreeNode>();
                mappedItem.FieldValues = new Dictionary <string, object>();

                foreach (string columnName in treeNode.ColumnNames)
                {
                    if (!fieldsToIgnore.Contains(columnName))
                    {
                        var columnValue = treeNode.GetValue(columnName);
                        if (columnValue != null)
                        {
                            mappedItem.FieldValues.Add(columnName, columnValue);
                        }
                    }
                }
                mappedItem.ParentNodeGUID = treeNode?.Parent?.NodeGUID;
                var stringBuilder = new StringBuilder();
                var res           = serializer.Serialize(mappedItem);
                stringBuilder.AppendLine(res);
                var      pathToWriteTo = $"{tempSerializationPath}/{mappedItem.NodeAliasPath}#{mappedItem.DocumentCulture}.yaml";
                var      concretePath  = this.GetRootPath(pathToWriteTo);
                FileInfo file          = new FileInfo(concretePath);
                file.Directory.Create(); // If the directory already exists, this method does nothing.
                File.WriteAllText(concretePath, res);
            }
            watch.Stop();
            _outputToStream(stream, $"Generating temp {contentConfig.Name} - {watch.ElapsedMilliseconds}ms");
            _processDifferences(stream, watch, serializationPath, tempSerializationPath);
        }
示例#8
0
文件: Program.cs 项目: michlG/wcf
        // Returns 'true' if the BridgeConfiguration describes a Bridge that
        // would run locally.
        private static bool IsBridgeHostLocal(BridgeConfiguration configuration)
        {
            if (String.Equals("localhost", configuration.BridgeHost, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            if (String.Equals(Environment.MachineName, configuration.BridgeHost, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            return(false);
        }
示例#9
0
        private void _processContentConfig(BridgeContentConfig contentConfig, Stream stream)
        {
            var    serializer          = new SerializerBuilder().ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull).Build();
            var    watch               = new Stopwatch();
            string serializationFolder = BridgeConfiguration.GetConfig().SerializationFolder;

            //have this driven by config
            var serializationPath = $"{serializationFolder}/content/{contentConfig.Name}";
            var pageTypes         = contentConfig.GetPageTypes();
            var fieldsToIgnore    = contentConfig.GetIgnoreFields();
            var path = contentConfig.Query;

            MultiDocumentQuery docs = DocumentHelper.GetDocuments().Path(path).Types(pageTypes.ToArray()).AllCultures().FilterDuplicates();
            var treeNodes           = docs.ToList <TreeNode>();

            foreach (var treeNode in treeNodes)
            {
                watch.Reset();
                watch.Start();
                var mappedItem = treeNode.Adapt <BridgeTreeNode>();
                mappedItem.FieldValues = new Dictionary <string, object>();

                foreach (string columnName in treeNode.ColumnNames)
                {
                    if (!fieldsToIgnore.Contains(columnName))
                    {
                        var columnValue = treeNode.GetValue(columnName);
                        if (columnValue != null)
                        {
                            mappedItem.FieldValues.Add(columnName, columnValue);
                        }
                    }
                }
                mappedItem.ParentNodeGUID = treeNode?.Parent?.NodeGUID;
                var stringBuilder = new StringBuilder();
                var res           = serializer.Serialize(mappedItem);
                stringBuilder.AppendLine(res);
                var      pathToWriteTo = $"{serializationPath}/{mappedItem.NodeAliasPath}#{mappedItem.DocumentCulture}.yaml";
                var      concretePath  = this.GetRootPath(pathToWriteTo);
                FileInfo file          = new FileInfo(concretePath);
                file.Directory.Create(); // If the directory already exists, this method does nothing.
                File.WriteAllText(concretePath, res);
                watch.Stop();
                byte[] bytes = Encoding.UTF8.GetBytes($"Serialized {contentConfig.Name}: {mappedItem.NodeAliasPath}#{mappedItem.DocumentCulture}.yaml ({mappedItem.NodeGUID}) - {watch.ElapsedMilliseconds}ms");
                stream.Write(bytes, 0, bytes.Length);
                stream.WriteByte(10);
                stream.Flush();
            }
        }
示例#10
0
文件: Program.cs 项目: michlG/wcf
            public override string ToString()
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("Options are:")
                .AppendLine(String.Format("  -allowRemote = {0}", AllowRemote))
                .AppendLine(String.Format("  -remoteAddresses = {0}", RemoteAddresses))
                .AppendLine(String.Format("  -ping = {0}", Ping))
                .AppendLine(String.Format("  -stop = {0}", Stop))
                .AppendLine(String.Format("  -stopIfLocal = {0}", StopIfLocal))
                .AppendLine(String.Format("  -reset = {0}", Reset))
                .AppendLine(String.Format("BridgeConfiguration is:{0}{1}",
                                          Environment.NewLine, BridgeConfiguration.ToString()));
                return(sb.ToString());
            }
示例#11
0
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            Dictionary <string, string> dictionary = BridgeConfiguration.ToDictionary();

            string configResponse = JsonSerializer.SerializeDictionary(dictionary);

            Trace.WriteLine(String.Format("{0:T} - GET config returning raw content:{1}{2}",
                                          DateTime.Now, Environment.NewLine, configResponse),
                            typeof(ConfigController).Name);

            // Directly return a json string to avoid use of MediaTypeFormatters
            HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(configResponse);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(JsonSerializer.JsonMediaType);
            return(response);
        }
 static void DumpConfig(BridgeConfiguration config, IPEndPoint presenceServiceEndPoint)
 {
     Trace.WriteLine(":: Settings ::");
     Trace.WriteLine("");
     Trace.WriteLine("Bridge endpoint (Internal): " + config.InternalServiceBinding.EndPoint);
     Trace.WriteLine("Bridge endpoint (External): " + config.ExternalServiceBinding.EndPoint);
     Trace.WriteLine("Presence multicast endpoint: " + config.PresenceBinding.MulticastEndPoint);
     Trace.WriteLine("Presence endpoint: " + presenceServiceEndPoint);
     Trace.WriteLine("");
     Trace.WriteLine(":: Target bridges ::");
     Trace.WriteLine("");
     foreach (Target target in config.Targets)
     {
         Trace.WriteLine(target.EndPoint);
     }
     Trace.WriteLine("");
 }
示例#13
0
    public static IScriptHost GetScriptHost()
    {
        var              console     = new CakeConsole();
        ICakeLog         log         = new CakeBuildLog(console);
        IFileSystem      fileSystem  = new FileSystem();
        ICakeDataService data        = new BridgeDataService();
        ICakeEnvironment environment = new CakeEnvironment(
            new CakePlatform(),
            new CakeRuntime(),
            log
            );
        IGlobber           globber       = new Globber(fileSystem, environment);
        ICakeArguments     arguments     = new BridgeArguments();
        ICakeConfiguration configuration = new BridgeConfiguration();
        IToolLocator       tools         = new ToolLocator(
            environment,
            new ToolRepository(environment),
            new ToolResolutionStrategy(
                fileSystem,
                environment,
                globber,
                configuration
                )
            );
        ICakeContext context = new CakeContext(
            fileSystem,
            environment,
            globber,
            log,
            arguments,
            new ProcessRunner(fileSystem, environment, log, tools, configuration),
            new WindowsRegistry(),
            tools,
            data,
            configuration
            );

        return(new BridgeScriptHost(
                   new CakeEngine(data, log),
                   context,
                   new DefaultExecutionStrategy(log),
                   new CakeReportPrinter(console, context),
                   arguments
                   ));
    }
示例#14
0
 public Home()
 {
     this.RequiresAuthentication(HttpContext.Current);
     Get("/index", parameters => {
         var bridgeCoreConfigs    = BridgeConfiguration.GetConfig().CoreConfigs;
         var bridgeContentConfigs = BridgeConfiguration.GetConfig().ContentConfigs;
         var currentRequest       = Request.Url;
         currentRequest.Path      = (ConfigurationManager.AppSettings["BridgeBaseUrl"] ?? "/Admin/BridgeUI").ToString();
         var model = new { coreConfigs = bridgeCoreConfigs, contentConfigs = bridgeContentConfigs, urlBase = currentRequest.ToString() };
         return(View["Index", model]);
     });
     Get("/about", parameters => "Hello from Bridge -|--|-");
     //Get("/{all*}", parameters =>
     //{
     //    //If you are having serious problems hitting anything, uncomment this
     //    var test = Request;
     //    return "catchall";
     //});
 }
        protected override void OnStart(string[] args)
        {
            var config = BridgeConfiguration.GetConfig();

            var presenceServiceEndPoint  = new IPEndPoint(config.InternalServiceBinding.EndPoint.Address, config.PresenceBinding.ServicePort);
            var multicastReceiveEndPoint = new IPEndPoint(config.InternalServiceBinding.EndPoint.Address, config.PresenceBinding.CallbackPort);

            DumpConfig(config, presenceServiceEndPoint);

            bridge = new SquiggleBridge(config.InternalServiceBinding.EndPoint,
                                        config.ExternalServiceBinding.EndPoint,
                                        config.PresenceBinding.MulticastEndPoint,
                                        multicastReceiveEndPoint,
                                        presenceServiceEndPoint);

            foreach (Target target in config.Targets)
            {
                bridge.AddTarget(target.EndPoint);
            }

            bridge.Start();
        }
示例#16
0
 private void _clearTempFolder()
 {
     try
     {
         //just trying to clean up some temp stuff from prev diffs
         string        serializationFolder = BridgeConfiguration.GetConfig().SerializationFolder;
         var           tempRoot            = this.GetRootPath($"{serializationFolder}/temp");
         DirectoryInfo di = new DirectoryInfo(tempRoot);
         foreach (FileInfo file in di.EnumerateFiles())
         {
             file.Delete();
         }
         foreach (DirectoryInfo dir in di.EnumerateDirectories())
         {
             dir.Delete(true);
         }
     }
     catch (Exception ex)
     {
         //keep moving
     }
 }
示例#17
0
        private void _processCoreConfig(BridgeCoreConfig coreConfig, Stream stream)
        {
            string       serializationFolder = BridgeConfiguration.GetConfig().SerializationFolder;
            var          deserializer        = new DeserializerBuilder().Build();
            TreeProvider tree  = new TreeProvider(MembershipContext.AuthenticatedUser);
            var          watch = new Stopwatch();

            //have this driven by config
            var serializationPath    = $"{serializationFolder}/core/{coreConfig.Name}";
            var classTypes           = coreConfig.GetClassTypes();
            var ignoreFields         = coreConfig.GetIgnoreFields();
            var allAllowedChildInfos = new List <AllowedChildClassInfo>();


            int retryCount = 3;

            _processClasses(retryCount, allAllowedChildInfos, coreConfig.Name, stream, deserializer, watch, serializationPath, classTypes, ignoreFields);
            //at this point we should have all children, lets post process these
            foreach (var allowedChildClass in allAllowedChildInfos)
            {
                AllowedChildClassInfoProvider.SetAllowedChildClassInfo(allowedChildClass);
            }
        }
 private async void CheckBridgeStatus()
 {
     status.Text = "Starting up bridge...";
     try
     {
         var config = new BridgeConfiguration(GetDeviceID(), "com.dotMorten.TestApp")
         {
             // The following are optional. If not set will be pulled from the package information and system information
             ModelName = "AllJoyn Mock DSB",
             DeviceName = "AllJoyn Simulator",
             ApplicationName = "AllJoyn Device Simulator",
             Vendor = "MockDevices Inc"
         };
         await AllJoynDsbServiceManager.Current.StartAsync(config);
         status.Text = ""; // Bridge Successfully Initialized
         addDeviceBox.IsEnabled = true;
     }
     catch (System.Exception ex)
     {
         status.Text = "Bridge failed to initialize:\n" + ex.Message;
         return;
     }
     LoadDevices();
 }
示例#19
0
 public BridgeComponent(BridgeConfiguration <TLeft, TRight> config)
 {
     this.config = config;
 }
示例#20
0
 public static IScenarioWithEndpointBehavior <TContext> With <TContext, TLeft, TRight>(this IScenarioWithEndpointBehavior <TContext> scenario, BridgeConfiguration <TLeft, TRight> config)
     where TContext : ScenarioContext
     where TLeft : TransportDefinition, new()
     where TRight : TransportDefinition, new()
 {
     return(scenario.WithComponent(new BridgeComponent <TLeft, TRight>(config)));
 }
 public BridgeComponent(Func <BridgeConfiguration <TLeft, TRight> > config)
 {
     this.config = config();
 }
示例#22
0
 public Bridge(BridgeConfiguration configuration, GatewayFactory factory)
 {
     _configuration = configuration;
     _factory       = factory;
 }
        private bool VerifyBridgeMasterCache(string bridgeID, bool findConnectedMaster, BridgeConfiguration bridgeConfig)
        {
            bool isBridgeCacheMaster = false;

            if (bridgeConfig != null && bridgeConfig.TargetCacheConfigList != null)
            {
                foreach (TargetCacheCofiguration targetCacheConfig in bridgeConfig.TargetCacheConfigList)
                {
                    if (targetCacheConfig != null && targetCacheConfig.IsMaster)
                    {
                        if (findConnectedMaster && targetCacheConfig.IsConnected || !findConnectedMaster)
                        {
                            isBridgeCacheMaster = true;
                            break;
                        }
                    }
                }
            }
            return(isBridgeCacheMaster);
        }
示例#24
0
        private void _processCoreConfig(BridgeCoreConfig coreConfig, Stream stream)
        {
            var    serializer          = new SerializerBuilder().ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull).Build();
            string serializationFolder = BridgeConfiguration.GetConfig().SerializationFolder;
            var    watch = new Stopwatch();

            _clearTempFolder();
            watch.Start();
            //have this driven by config
            var serializationPath     = $"{serializationFolder}/core/{coreConfig.Name}";
            var tempGUID              = DateTime.Now.Ticks.ToString();
            var tempSerializationPath = $"{serializationFolder}/temp/{tempGUID}/{coreConfig.Name}";
            var classTypes            = coreConfig.GetClassTypes();
            var fieldsToIgnore        = coreConfig.GetIgnoreFields();

            ProviderHelper.ClearHashtables("cms.class", false);
            foreach (var classType in classTypes)
            {
                var dci = DataClassInfoProvider.GetDataClassInfo(classType);
                if (dci != null)
                {
                    var mappedItem = dci.Adapt <BridgeClassInfo>();
                    mappedItem.FieldValues = new Dictionary <string, object>();

                    foreach (string columnName in dci.ColumnNames)
                    {
                        if (!fieldsToIgnore.Contains(columnName))
                        {
                            var columnValue = dci.GetValue(columnName);
                            mappedItem.FieldValues.Add(columnName, columnValue);
                        }
                    }

                    var assignedSites = new List <Guid>();
                    foreach (SiteInfo assignedSite in dci.AssignedSites)
                    {
                        assignedSites.Add(assignedSite.SiteGUID);
                    }
                    mappedItem.AssignedSites = assignedSites;

                    var allowedChildClasses = AllowedChildClassInfoProvider.GetAllowedChildClasses().Where("ParentClassID", QueryOperator.Equals, dci["ClassID"].ToString()).Column("ChildClassID").ToList();

                    var allowedChildrenTypes = new List <string>();
                    foreach (AllowedChildClassInfo allowedChildClass in allowedChildClasses)
                    {
                        var className = new ObjectQuery("cms.class").Where("ClassID", QueryOperator.Equals, allowedChildClass.ChildClassID).Column("ClassName").FirstOrDefault()["ClassName"].ToString();
                        allowedChildrenTypes.Add(className);
                    }
                    mappedItem.AllowedChildTypes = allowedChildrenTypes;

                    var classQueries = QueryInfoProvider.GetQueries().Where("ClassID", QueryOperator.Equals, dci.ClassID).ToList();
                    var queries      = new Dictionary <string, BridgeClassQuery>();
                    foreach (var classQuery in classQueries)
                    {
                        var bcq = classQuery.Adapt <BridgeClassQuery>();
                        queries.Add(classQuery.QueryName, bcq);
                    }
                    mappedItem.Queries = queries;

                    var stringBuilder = new StringBuilder();
                    var res           = serializer.Serialize(mappedItem);
                    stringBuilder.AppendLine(res);

                    var      pathToMatching = $"{tempSerializationPath}/{mappedItem.ClassName.ToLower()}.yaml";
                    var      tempPath       = this.GetRootPath(pathToMatching);
                    FileInfo file           = new FileInfo(tempPath);
                    file.Directory.Create(); // If the directory already exists, this method does nothing.
                    File.WriteAllText(tempPath, res);
                }
            }
            watch.Stop();
            _outputToStream(stream, $"Generating temp {coreConfig.Name} - {watch.ElapsedMilliseconds}ms");
            _processDifferences(stream, watch, serializationPath, tempSerializationPath);
        }
示例#25
0
        public Diff()
        {
            this.RequiresAuthentication(HttpContext.Current);
            Get("/diffcore/{id}", parameters =>
            {
                var response = new Response();

                response.ContentType = "text/plain";
                response.Contents    = stream =>
                {
                    var bridgeCoreConfigs = BridgeConfiguration.GetConfig().CoreConfigs;
                    string configName     = parameters.id;
                    foreach (BridgeCoreConfig coreConfig in bridgeCoreConfigs)
                    {
                        if (configName.ToLower() == coreConfig.Name.ToLower())
                        {
                            _processCoreConfig(coreConfig, stream);
                        }
                    }
                };
                return(response);
            });


            Get("/diffcontent/{id}", parameters =>
            {
                var response = new Response();

                response.ContentType = "text/plain";
                response.Contents    = stream =>
                {
                    var bridgeContentConfigs = BridgeConfiguration.GetConfig().ContentConfigs;
                    string configName        = parameters.id;
                    foreach (BridgeContentConfig contentConfig in bridgeContentConfigs)
                    {
                        if (configName.ToLower() == contentConfig.Name.ToLower())
                        {
                            _processContentConfig(contentConfig, stream);
                        }
                    }
                };
                return(response);
            });

            Get("/viewdiff", parameters =>
            {
                var response = new Response();

                response.ContentType = "text/plain";
                response.Contents    = stream =>
                {
                    var bridgeContentConfigs = BridgeConfiguration.GetConfig().ContentConfigs;
                    string origFolder        = Request.Query["origFolder"];
                    string tempFolder        = Request.Query["tempFolder"];
                    string file = Request.Query["file"];

                    var origPath             = this.GetRootPath($"{origFolder}/{file}");
                    var origYamlFileContents = File.ReadAllText(origPath);
                    var tempPath             = this.GetRootPath($"{tempFolder}/{file}");
                    var tempFileContents     = File.ReadAllText(tempPath);

                    var diffBuilder = new InlineDiffBuilder(new Differ());
                    var diff        = diffBuilder.BuildDiffModel(origYamlFileContents, tempFileContents);

                    foreach (var line in diff.Lines)
                    {
                        string linePrefix = "";
                        string lineSuffix = "";
                        switch (line.Type)
                        {
                        case ChangeType.Inserted:
                            linePrefix = "K <strong>";
                            lineSuffix = "</strong>";
                            break;

                        case ChangeType.Deleted:
                            linePrefix = "F <em>";
                            lineSuffix = "</em>";
                            break;

                        default:
                            linePrefix = "  ";
                            lineSuffix = "";
                            break;
                        }
                        _outputToStream(stream, $"{linePrefix}{line.Text}{lineSuffix}");
                    }
                };
                return(response);
            });
        }
示例#26
0
文件: Program.cs 项目: michlG/wcf
            private bool Parse(string[] args)
            {
                // Build a dictionary of all command line arguments.
                // This allows us to initialize BridgeConfiguration from it.
                // Precedence of values in the BridgeConfiguration is this:
                //   - Lowest precedence is the BridgeConfiguration ctor defaults
                //   - Next precedence is any value found in a specified configuration file
                //   - Next precedence is environment variables
                //   - Highest precedence is a BridgeConfiguration value explicitly set on the command line

                Dictionary <string, string> argumentDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                foreach (string arg in args)
                {
                    if (!arg.StartsWith("/") && !arg.StartsWith("-"))
                    {
                        return(false);
                    }

                    // Cannot use split because some argument values could contain colons
                    int    index    = arg.IndexOf(':');
                    string argName  = (index < 0) ? arg.Substring(1) : arg.Substring(1, index - 1);
                    string argValue = (index < 0) ? String.Empty : arg.Substring(index + 1);

                    if (String.Equals(argName, "?", StringComparison.OrdinalIgnoreCase))
                    {
                        return(false);
                    }

                    argumentDictionary[argName] = argValue;
                }

                BridgeConfiguration = new BridgeConfiguration();

                // If the user specified a configuration file, deserialize it as json
                // and treat each name-value pair as if it had been on the command line.
                // But options explicitly on the command line take precedence over these file options.
                string argumentValue;

                if (argumentDictionary.TryGetValue("bridgeConfig", out argumentValue))
                {
                    if (!File.Exists(argumentValue))
                    {
                        Console.WriteLine("The configuration file '{0}' does not exist.");
                        return(false);
                    }

                    // Read the configuration file as json and deserialize it
                    string configurationAsJson = File.ReadAllText(argumentValue);
                    Dictionary <string, string> deserializedConfig = null;

                    try
                    {
                        deserializedConfig = JsonSerializer.DeserializeDictionary(configurationAsJson);
                    }
                    catch (Exception ex)
                    {
                        // Catch all exceptions because any will cause
                        // this application to terminate.
                        Console.WriteLine("Error deserializing {0} : {1}",
                                          argumentValue, ex.Message);
                        return(false);
                    }

                    // Every name/value pair in the config file not explicitly set on the command line
                    // is treated as if it had been on the command line.
                    foreach (var pair in deserializedConfig)
                    {
                        if (!argumentDictionary.ContainsKey(pair.Key))
                        {
                            argumentDictionary[pair.Key] = pair.Value;
                        }
                    }
                }

                // For every property in the BridgeConfiguration that has not been explicitly
                // specified on the command line or via the config file, check if there is an
                // Environment variable set for it.  If so, use it as if it had been on the command line.
                foreach (string key in BridgeConfiguration.ToDictionary().Keys)
                {
                    // If the property is explicitly on the command line, it has highest precedence
                    if (!argumentDictionary.ContainsKey(key))
                    {
                        // But if it is not explicitly on the command line but
                        // an environment variable exists for it, it has higher precedence
                        // than defaults or the config file.
                        string environmentVariable = Environment.GetEnvironmentVariable(key);
                        if (!String.IsNullOrWhiteSpace(environmentVariable))
                        {
                            argumentDictionary[key] = environmentVariable;
                        }
                    }
                }

                // Finally, apply all our command line arguments to the BridgeConfiguration,
                // overwriting any values that were the default or came from the optional config file
                BridgeConfiguration = new BridgeConfiguration(BridgeConfiguration, argumentDictionary);

                // Finish parsing the command line arguments that are not part of BridgeConfiguration
                if (argumentDictionary.ContainsKey("allowRemote"))
                {
                    AllowRemote = true;
                }

                if (argumentDictionary.ContainsKey("ping"))
                {
                    Ping = true;
                }

                if (argumentDictionary.ContainsKey("stop"))
                {
                    Stop = true;
                }

                if (argumentDictionary.ContainsKey("stopiflocal"))
                {
                    StopIfLocal = true;
                }

                string remoteAddresses;

                if (argumentDictionary.TryGetValue("remoteAddresses", out remoteAddresses))
                {
                    RemoteAddresses = remoteAddresses;
                }

                if (argumentDictionary.ContainsKey("reset"))
                {
                    Reset = true;
                }

                return(true);
            }
示例#27
0
        public void AddBridgeNode()
        {
            try
            {
                _bridgeService = new NCBridgeRPCService(Server);

                if (!ValidateParameters())
                {
                    return;
                }

                _bridgeServer = _bridgeService.GetBridgeServer(TimeSpan.FromSeconds(30));


                BridgeConfiguration bconfig = _bridgeServer.GetBridgeConfiguration(BridgeId);

                ToolsUtil.VerifyBridgeConfigurations(bconfig, BridgeId);

                byte[] userId = null;
                byte[] paswd  = null;
                if (UserId != string.Empty && Password != string.Empty)
                {
                    userId = EncryptionUtil.Encrypt(UserId);
                    paswd  = EncryptionUtil.Encrypt(Password);
                }

                if (bconfig != null && bconfig.NumberOfBridgeNodes >= 2)
                {
                    OutputProvider.WriteErrorLine("You cannot add more than 2 nodes in a Bridge");
                    return;
                }


                if (!bconfig.GetBridgeNodeList().Contains(NewBridgeNode))
                {
                    if (bconfig.GetBridgeNodeList().Count != 0)
                    {
                        bconfig.DeploymentVersion++;
                        bconfig.BridgeNodes = bconfig.BridgeNodes + "," + NewBridgeNode;
                        _bridgeServer.RegisterBridge(bconfig, true, false);
                        //for registering bridge on newly added node
                        NCBridgeRPCService _bridgeNewService = new NCBridgeRPCService(NewBridgeNode);
                        IBridgeServer      _bridgeNewServer  = _bridgeNewService.GetBridgeServer(TimeSpan.FromSeconds(30));
                        _bridgeNewServer.RegisterBridge(bconfig, true, false);
                        OutputProvider.WriteLine(NewBridgeNode + " added to " + BridgeId);
                    }

                    else
                    {
                        bconfig.BridgeNodes  = NewBridgeNode;
                        bconfig.BridgeActive = NewBridgeNode;
                        NCBridgeRPCService _bridgeNewService = new NCBridgeRPCService(NewBridgeNode);
                        IBridgeServer      _bridgeNewServer  = _bridgeNewService.GetBridgeServer(TimeSpan.FromSeconds(30));
                        _bridgeNewServer.RegisterBridge(bconfig, true, false);
                        OutputProvider.WriteLine(NewBridgeNode + " added to " + BridgeId);
                    }

                    //updating target cache config
                    if (bconfig.TargetCacheConfigList != null)
                    {
                        foreach (TargetCacheCofiguration targetCacheConfig in bconfig.TargetCacheConfigList)
                        {
                            try
                            {
                                if (targetCacheConfig != null)
                                {
                                    foreach (string server in targetCacheConfig.Servers.Split(','))
                                    {
                                        NCacheRPCService NCache      = new NCacheRPCService(server);;
                                        ICacheServer     cacheServer = null;
                                        cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                                        string cacheID = targetCacheConfig.CacheID.ToString();

                                        CacheServerConfig serverConfig = cacheServer.GetCacheConfiguration(cacheID);
                                        if (serverConfig.Bridge != null)
                                        {
                                            serverConfig.Bridge.Servers = bconfig.BridgeNodes;
                                        }

                                        serverConfig.ConfigVersion++;

                                        cacheServer.ConfigureBridgeToCache(serverConfig, userId, paswd, false);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                OutputProvider.WriteErrorLine(e.Message);
                                return;
                            }
                        }
                    }
                }
                else
                {
                    OutputProvider.WriteErrorLine("Error: Node already exists in bridge");
                    return;
                }
            }
            catch (Exception e)
            {
                OutputProvider.WriteErrorLine("Error: Bridge not registered on server.\n");
                OutputProvider.WriteErrorLine(e.Message);
            }
        }
 internal static X509Certificate2 EnsureRevokedCertificateInstalled(BridgeConfiguration configuration, CertificateCreationSettings certificateCreationSettings, string resourceAddress)
 {
     return(CertificateManager.CreateAndInstallNonDefaultMachineCertificates(GetCertificateGeneratorInstance(configuration), certificateCreationSettings, resourceAddress));
 }
 internal static string EnsureSslPortCertificateInstalled(BridgeConfiguration configuration)
 {
     return(EnsureSslPortCertificateInstalled(configuration, configuration.BridgeHttpsPort));
 }
示例#30
0
        public HttpResponseMessage POST(HttpRequestMessage request)
        {
            // A configuration change can have wide impact, so we don't allow concurrent use
            lock (BridgeLock)
            {
                try
                {
                    // Handle deserialization explicitly to bypass MediaTypeFormatter use
                    string nameValuePairs = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    Dictionary <string, string> configInfo = JsonSerializer.DeserializeDictionary(nameValuePairs);

                    Trace.WriteLine(String.Format("{0:T} -- POST config received raw content:{1}{2}",
                                                  DateTime.Now, Environment.NewLine, nameValuePairs),
                                    typeof(ConfigController).Name);

                    // Create a new configuration combining the existing one with any provided properties.
                    BridgeConfiguration newConfiguration = new BridgeConfiguration(BridgeConfiguration, configInfo);
                    Trace.WriteLine(String.Format("{0:T} -- applying new config:{0}{1}",
                                                  DateTime.Now, Environment.NewLine, newConfiguration),
                                    typeof(ConfigController).Name);

                    // Take the new configuration and notify listeners of the change.
                    BridgeConfiguration oldConfiguration = BridgeConfiguration;
                    BridgeConfiguration = newConfiguration;

                    // Notify of change of resource folder
                    bool resourceFolderChanged = !String.Equals(oldConfiguration.BridgeResourceFolder, newConfiguration.BridgeResourceFolder, StringComparison.OrdinalIgnoreCase);
                    if (ResourceFolderChanged != null && resourceFolderChanged)
                    {
                        ResourceFolderChanged(this, new ChangedEventArgs <string>(
                                                  oldConfiguration.BridgeResourceFolder,
                                                  newConfiguration.BridgeResourceFolder));
                    }

                    // Notify of change of the idle timeout
                    if (IdleTimeoutChanged != null &&
                        oldConfiguration.BridgeMaxIdleTimeSpan != newConfiguration.BridgeMaxIdleTimeSpan)
                    {
                        IdleTimeoutChanged(this, new ChangedEventArgs <TimeSpan>(
                                               oldConfiguration.BridgeMaxIdleTimeSpan,
                                               newConfiguration.BridgeMaxIdleTimeSpan));
                    }

                    // When the resource folder changes, the response is an array of
                    // resource types.  Any other changes returns an empty string.
                    string configResponse = resourceFolderChanged
                                                ? PrepareConfigResponse(TypeCache.Cache[CurrentAppDomainName])
                                                : String.Empty;

                    Trace.WriteLine(String.Format("{0:T} - POST config returning raw content:{1}{2}",
                                                  DateTime.Now, Environment.NewLine, configResponse),
                                    typeof(ConfigController).Name);

                    // Directly return a json string to avoid use of MediaTypeFormatters
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(configResponse);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue(JsonSerializer.JsonMediaType);
                    return(response);
                }
                catch (Exception ex)
                {
                    var exceptionResponse = ex.Message;
                    Trace.WriteLine(String.Format("{0:T} - POST config exception:{1}{2}",
                                                  DateTime.Now, Environment.NewLine, ex),
                                    typeof(ConfigController).Name);

                    return(Request.CreateResponse(HttpStatusCode.BadRequest, exceptionResponse));
                }
            }
        }
        internal static string EnsureNonDefaultCertificateInstalled(BridgeConfiguration configuration, CertificateCreationSettings certificateCreationSettings, string resourceAddress)
        {
            X509Certificate2 cert = CertificateManager.CreateAndInstallNonDefaultMachineCertificates(GetCertificateGeneratorInstance(configuration), certificateCreationSettings, resourceAddress);

            return(cert.Thumbprint);
        }