Exemplo n.º 1
0
        public async Task MempoolNotifiesAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            using var node = await coreNode.CreateNewP2pNodeAsync();

            try
            {
                var network          = coreNode.Network;
                var rpc              = coreNode.RpcClient;
                var dir              = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());
                var indexStore       = new IndexStore(Path.Combine(dir, "indexStore"), network, new SmartHeaderChain());
                var transactionStore = new AllTransactionStore(Path.Combine(dir, "transactionStore"), network);
                var mempoolService   = new MempoolService();
                var blocks           = new FileSystemBlockRepository(Path.Combine(dir, "blocks"), network);
                var bitcoinStore     = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);
                await bitcoinStore.InitializeAsync();

                await rpc.GenerateAsync(101);

                node.Behaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior());
                node.VersionHandshake();

                var addr = new Key().PubKey.GetSegwitAddress(network);

                var txNum        = 10;
                var eventAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => bitcoinStore.MempoolService.TransactionReceived += h,
                    h => bitcoinStore.MempoolService.TransactionReceived -= h,
                    txNum);

                var txTasks = new List <Task <uint256> >();
                var batch   = rpc.PrepareBatch();
                for (int i = 0; i < txNum; i++)
                {
                    txTasks.Add(batch.SendToAddressAsync(addr, Money.Coins(1)));
                }
                var batchTask = batch.SendBatchAsync();

                var stxs = await eventAwaiter.WaitAsync(TimeSpan.FromSeconds(21));

                await batchTask;
                var   hashes = await Task.WhenAll(txTasks);

                foreach (var stx in stxs)
                {
                    Assert.Contains(stx.GetHash(), hashes);
                }
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                node.Disconnect();
                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 2
0
        public Global(string dataDir, string torLogsFile, Config config, UiConfig uiConfig, WalletManager walletManager)
        {
            using (BenchmarkLogger.Measure())
            {
                StoppingCts = new CancellationTokenSource();
                DataDir     = dataDir;
                Config      = config;
                UiConfig    = uiConfig;
                TorSettings = new TorSettings(DataDir, torLogsFile, distributionFolderPath: EnvironmentHelpers.GetFullBaseDirectory());

                HostedServices = new HostedServices();
                WalletManager  = walletManager;

                WalletManager.OnDequeue += WalletManager_OnDequeue;
                WalletManager.WalletRelevantTransactionProcessed += WalletManager_WalletRelevantTransactionProcessed;

                var networkWorkFolderPath = Path.Combine(DataDir, "BitcoinStore", Network.ToString());
                var transactionStore      = new AllTransactionStore(networkWorkFolderPath, Network);
                var indexStore            = new IndexStore(Path.Combine(networkWorkFolderPath, "IndexStore"), Network, new SmartHeaderChain());
                var mempoolService        = new MempoolService();
                var blocks = new FileSystemBlockRepository(Path.Combine(networkWorkFolderPath, "Blocks"), Network);

                BitcoinStore = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);

                HttpClientFactory = Config.UseTor
                                        ? new HttpClientFactory(Config.TorSocks5EndPoint, backendUriGetter: () => Config.GetCurrentBackendUri())
                                        : new HttpClientFactory(torEndPoint: null, backendUriGetter: () => Config.GetFallbackBackendUri());

                Synchronizer           = new WasabiSynchronizer(Network, BitcoinStore, HttpClientFactory);
                LegalChecker           = new(DataDir);
                TransactionBroadcaster = new TransactionBroadcaster(Network, BitcoinStore, HttpClientFactory, WalletManager);
            }
        }
Exemplo n.º 3
0
        public Global()
        {
            using (BenchmarkLogger.Measure())
            {
                StoppingCts = new CancellationTokenSource();
                DataDir     = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));
                TorLogsFile = Path.Combine(DataDir, "TorLogs.txt");
                Directory.CreateDirectory(DataDir);

                Logger.InitializeDefaults(Path.Combine(DataDir, "Logs.txt"));

                UiConfig = new UiConfig(Path.Combine(DataDir, "UiConfig.json"));
                UiConfig.LoadOrCreateDefaultFile();
                Config = new Config(Path.Combine(DataDir, "Config.json"));
                Config.LoadOrCreateDefaultFile();

                HostedServices = new HostedServices();
                WalletManager  = new WalletManager(Network, new WalletDirectories(DataDir));

                LegalDocuments = LegalDocuments.TryLoadAgreed(DataDir);

                WalletManager.OnDequeue += WalletManager_OnDequeue;
                WalletManager.WalletRelevantTransactionProcessed += WalletManager_WalletRelevantTransactionProcessed;
            }
        }
        public async Task NodesDifferAsync()
        {
            using var services1 = new HostedServices();
            using var services2 = new HostedServices();
            var coreNodes = await Task.WhenAll(TestNodeBuilder.CreateAsync(services1, additionalFolder: "0"), TestNodeBuilder.CreateAsync(services2, additionalFolder: "1"));

            await services1.StartAllAsync(CancellationToken.None);

            await services2.StartAllAsync(CancellationToken.None);

            CoreNode node1 = coreNodes[0];
            CoreNode node2 = coreNodes[1];

            try
            {
                Assert.NotEqual(node1.DataDir, node2.DataDir);
                Assert.NotEqual(node1.P2pEndPoint, node2.P2pEndPoint);
                Assert.NotEqual(node1.RpcEndPoint, node2.RpcEndPoint);
            }
            finally
            {
                await services1.StopAllAsync(CancellationToken.None);

                await services2.StopAllAsync(CancellationToken.None);

                await Task.WhenAll(node1.TryStopAsync(), node2.TryStopAsync());
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Generate a DPWSHostedService source file from a Wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateHostedService(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string hostedServiceClassName = serviceDesc.Name;
            string hostedServiceNs = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "HostedService.cs";

            HostedServices hostedServices = new HostedServices(hostedServiceNs);

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                HostedService hostedService = new HostedService(portType.Name, hostedServiceNs, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction = serviceDesc.TargetNamespace + "/" + operation.Name + "Request";
                    string outAction = serviceDesc.TargetNamespace + "/" + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    hostedService.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    hostedService.Messages.Add(message);
                }
            }

            HostedServiceGenerator hostedServiceGen = new HostedServiceGenerator();
            hostedServiceGen.GenerateCode(filename, hostedServices);
        }
Exemplo n.º 6
0
 public CoreNodeParams(
     Network network,
     MempoolService mempoolService,
     HostedServices hostedServices,
     string dataDir,
     bool tryRestart,
     bool tryDeleteDataDir,
     EndPointStrategy p2pEndPointStrategy,
     EndPointStrategy rpcEndPointStrategy,
     int?txIndex,
     int?prune,
     string userAgent)
 {
     Network             = Guard.NotNull(nameof(network), network);
     MempoolService      = Guard.NotNull(nameof(mempoolService), mempoolService);
     HostedServices      = Guard.NotNull(nameof(hostedServices), hostedServices);
     DataDir             = Guard.NotNullOrEmptyOrWhitespace(nameof(dataDir), dataDir);
     TryRestart          = tryRestart;
     TryDeleteDataDir    = tryDeleteDataDir;
     P2pEndPointStrategy = Guard.NotNull(nameof(p2pEndPointStrategy), p2pEndPointStrategy);
     RpcEndPointStrategy = Guard.NotNull(nameof(rpcEndPointStrategy), rpcEndPointStrategy);
     TxIndex             = txIndex;
     Prune     = prune;
     UserAgent = Guard.NotNullOrEmptyOrWhitespace(nameof(userAgent), userAgent, trim: true);
 }
Exemplo n.º 7
0
        public static async Task <CoreNode> CreateAsync(HostedServices hostedServices, [CallerFilePath] string callerFilePath = "", [CallerMemberName] string callerMemberName = "", string additionalFolder = "", MempoolService?mempoolService = null)
        {
            var network        = Network.RegTest;
            var nodeParameters = new CoreNodeParams(
                network,
                mempoolService ?? new MempoolService(),
                hostedServices,
                Path.Combine(Common.GetWorkDir(callerFilePath, callerMemberName), additionalFolder),
                tryRestart: true,
                tryDeleteDataDir: true,
                EndPointStrategy.Random,
                EndPointStrategy.Random,
                txIndex: 1,
                prune: 0,
                mempoolReplacement: "fee,optin",
                userAgent: $"/WasabiClient:{Constants.ClientVersion}/",
                fallbackFee: Money.Coins(0.0002m),                         // https://github.com/bitcoin/bitcoin/pull/16524
                new MemoryCache(new MemoryCacheOptions()));

            nodeParameters.ListenOnion    = 0;
            nodeParameters.Discover       = 0;
            nodeParameters.DnsSeed        = 0;
            nodeParameters.FixedSeeds     = 0;
            nodeParameters.Upnp           = 0;
            nodeParameters.NatPmp         = 0;
            nodeParameters.PersistMempool = 0;
            return(await CoreNode.CreateAsync(
                       nodeParameters,
                       CancellationToken.None));
        }
Exemplo n.º 8
0
        public async Task AllFeeEstimateAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            try
            {
                var rpc         = coreNode.RpcClient;
                var estimations = await rpc.EstimateAllFeeAsync(EstimateSmartFeeMode.Conservative, simulateIfRegTest : true);

                Assert.Equal(7, estimations.Estimations.Count);
                Assert.True(estimations.Estimations.First().Key < estimations.Estimations.Last().Key);
                Assert.True(estimations.Estimations.First().Value > estimations.Estimations.Last().Value);
                Assert.Equal(EstimateSmartFeeMode.Conservative, estimations.Type);
                estimations = await rpc.EstimateAllFeeAsync(EstimateSmartFeeMode.Economical, simulateIfRegTest : true);

                Assert.Equal(7, estimations.Estimations.Count);
                Assert.True(estimations.Estimations.First().Key < estimations.Estimations.Last().Key);
                Assert.True(estimations.Estimations.First().Value > estimations.Estimations.Last().Value);
                Assert.Equal(EstimateSmartFeeMode.Economical, estimations.Type);
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
    public static void Explain(this HostedServices runnable, TextWriter writer)
    {
        writer.WriteLine(@"
- Hosted Services are managed by the host and started and stopped (in reverse order) the host
- `IHostedService` is the basic abstraction. For long running background tasks use `BackgroundService`.
- GenericHost starts hosted services before everything else while WebHost starts the ASP.NET Core pipeline concurrent to the hosted services. This means initializing things in hosted services that controllers rely on can be dangerous.
");
    }
Exemplo n.º 10
0
        private volatile bool _disposedValue = false;         // To detect redundant calls

        public RegTestFixture()
        {
            RuntimeParams.SetDataDir(Path.Combine(Tests.Global.Instance.DataDir, "RegTests", "Backend"));
            RuntimeParams.LoadAsync().GetAwaiter().GetResult();
            var hostedServices = new HostedServices();

            BackendRegTestNode = TestNodeBuilder.CreateAsync(hostedServices, callerFilePath: "RegTests", callerMemberName: "BitcoinCoreData").GetAwaiter().GetResult();

            var testnetBackendDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Tests", "RegTests", "Backend"));

            IoHelpers.TryDeleteDirectoryAsync(testnetBackendDir).GetAwaiter().GetResult();
            Thread.Sleep(100);
            Directory.CreateDirectory(testnetBackendDir);
            Thread.Sleep(100);
            var config = new Config(
                BackendRegTestNode.RpcClient.Network,
                BackendRegTestNode.RpcClient.CredentialString.ToString(),
                new IPEndPoint(IPAddress.Loopback, Network.Main.DefaultPort),
                new IPEndPoint(IPAddress.Loopback, Network.TestNet.DefaultPort),
                BackendRegTestNode.P2pEndPoint,
                new IPEndPoint(IPAddress.Loopback, Network.Main.RPCPort),
                new IPEndPoint(IPAddress.Loopback, Network.TestNet.RPCPort),
                BackendRegTestNode.RpcEndPoint);
            var configFilePath = Path.Combine(testnetBackendDir, "Config.json");

            config.SetFilePath(configFilePath);
            config.ToFile();

            var roundConfig         = CreateRoundConfig(Money.Coins(0.1m), Constants.OneDayConfirmationTarget, 0.7, 0.1m, 100, 120, 60, 60, 60, 1, 24, true, 11);
            var roundConfigFilePath = Path.Combine(testnetBackendDir, "CcjRoundConfig.json");

            roundConfig.SetFilePath(roundConfigFilePath);
            roundConfig.ToFile();

            var conf = new ConfigurationBuilder()
                       .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("datadir", testnetBackendDir) })
                       .Build();

            BackendEndPoint = $"http://localhost:{new Random().Next(37130, 38000)}/";

            BackendHost = Host.CreateDefaultBuilder()
                          .ConfigureWebHostDefaults(webBuilder => webBuilder
                                                    .UseStartup <Startup>()
                                                    .UseConfiguration(conf)
                                                    .UseWebRoot("../../../../WalletWasabi.Backend/wwwroot")
                                                    .UseUrls(BackendEndPoint))
                          .Build();

            Global = (Backend.Global)BackendHost.Services.GetService(typeof(Backend.Global));
            Global.HostedServices = hostedServices;
            var hostInitializationTask = BackendHost.RunWithTasksAsync();

            Logger.LogInfo($"Started Backend webhost: {BackendEndPoint}");

            var delayTask = Task.Delay(3000);

            Task.WaitAny(delayTask, hostInitializationTask);             // Wait for server to initialize (Without this OSX CI will fail)
        }
Exemplo n.º 11
0
        private async Task InitializeP2pAsync(Network network, EndPoint endPoint, CancellationToken cancel)
        {
            Guard.NotNull(nameof(network), network);
            Guard.NotNull(nameof(endPoint), endPoint);

            // We have to find it, because it's cloned by the node and not perfectly cloned (event handlers cannot be cloned.)
            P2pNode = new P2pNode(network, endPoint, new MempoolService(), $"/WasabiCoordinator:{Constants.BackendMajorVersion}/");
            await P2pNode.ConnectAsync(cancel).ConfigureAwait(false);

            HostedServices.Register(new BlockNotifier(TimeSpan.FromSeconds(7), RpcClient, P2pNode), "Block Notifier");
        }
        public async Task CanBuildCoreNodeAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            await coreNode.TryStopAsync();

            await services.StopAllAsync(CancellationToken.None);
        }
Exemplo n.º 13
0
        public Global()
        {
            DataDir          = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));
            TorLogsFile      = Path.Combine(DataDir, "TorLogs.txt");
            WalletsDir       = Path.Combine(DataDir, "Wallets");
            WalletBackupsDir = Path.Combine(DataDir, "WalletBackups");

            Directory.CreateDirectory(DataDir);
            Directory.CreateDirectory(WalletsDir);
            Directory.CreateDirectory(WalletBackupsDir);

            HostedServices = new HostedServices();
        }
Exemplo n.º 14
0
        public async Task InitializeAsync(Config config, CoordinatorRoundConfig roundConfig, IRPCClient rpc, CancellationToken cancel)
        {
            Config      = Guard.NotNull(nameof(config), config);
            RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig);
            RpcClient   = Guard.NotNull(nameof(rpc), rpc);

            // Make sure RPC works.
            await AssertRpcNodeFullyInitializedAsync();

            // Make sure P2P works.
            await InitializeP2pAsync(config.Network, config.GetBitcoinP2pEndPoint(), cancel);

            if (roundConfig.FilePath != null)
            {
                HostedServices.Register(
                    new ConfigWatcher(
                        TimeSpan.FromSeconds(10),                         // Every 10 seconds check the config
                        RoundConfig,
                        () =>
                {
                    try
                    {
                        Coordinator.RoundConfig.UpdateOrDefault(RoundConfig, toFile: false);

                        Coordinator.AbortAllRoundsInInputRegistration($"{nameof(RoundConfig)} has changed.");
                    }
                    catch (Exception ex)
                    {
                        Logger.LogDebug(ex);
                    }
                }),
                    "Config Watcher");
            }

            await HostedServices.StartAllAsync(cancel);

            // Initialize index building
            var indexBuilderServiceDir = Path.Combine(DataDir, "IndexBuilderService");
            var indexFilePath          = Path.Combine(indexBuilderServiceDir, $"Index{RpcClient.Network}.dat");
            var blockNotifier          = HostedServices.FirstOrDefault <BlockNotifier>();

            IndexBuilderService = new IndexBuilderService(RpcClient, blockNotifier, indexFilePath);
            Coordinator         = new Coordinator(RpcClient.Network, blockNotifier, Path.Combine(DataDir, "CcjCoordinator"), RpcClient, roundConfig);
            IndexBuilderService.Synchronize();
            Logger.LogInfo($"{nameof(IndexBuilderService)} is successfully initialized and started synchronization.");

            await Coordinator.MakeSureTwoRunningRoundsAsync();

            Logger.LogInfo("Chaumian CoinJoin Coordinator is successfully initialized and started two new rounds.");
        }
Exemplo n.º 15
0
        public async Task TrustedNotifierNotifiesTxAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            try
            {
                var rpc = coreNode.RpcClient;
                await rpc.GenerateAsync(101);

                var network = rpc.Network;

                var dir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());

                var addr     = new Key().PubKey.GetSegwitAddress(network);
                var notifier = coreNode.MempoolService;

                var txNum          = 10;
                var txEventAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => notifier.TransactionReceived += h,
                    h => notifier.TransactionReceived -= h,
                    txNum);

                var txTasks = new List <Task <uint256> >();
                var batch   = rpc.PrepareBatch();
                for (int i = 0; i < txNum; i++)
                {
                    txTasks.Add(batch.SendToAddressAsync(addr, Money.Coins(1)));
                }
                var batchTask = batch.SendBatchAsync();

                var arrivedTxs = await txEventAwaiter.WaitAsync(TimeSpan.FromSeconds(21));

                await batchTask;
                var   hashes = await Task.WhenAll(txTasks);

                foreach (var hash in arrivedTxs.Select(x => x.GetHash()))
                {
                    Assert.Contains(hash, hashes);
                }
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 16
0
        public async Task CantDoubleSpendAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            try
            {
                var rpc     = coreNode.RpcClient;
                var network = rpc.Network;

                var walletName = "wallet.dat";
                await rpc.CreateWalletAsync(walletName);

                using var k1 = new Key();
                var blockId = await rpc.GenerateToAddressAsync(1, k1.PubKey.WitHash.GetAddress(network));

                var block = await rpc.GetBlockAsync(blockId[0]);

                var coinBaseTx = block.Transactions[0];

                var tx = Transaction.Create(network);
                tx.Inputs.Add(coinBaseTx, 0);
                using var k2 = new Key();
                tx.Outputs.Add(Money.Coins(49.9999m), k2.PubKey.WitHash.GetAddress(network));
                tx.Sign(k1.GetBitcoinSecret(network), coinBaseTx.Outputs.AsCoins().First());
                var valid = tx.Check();

                var doubleSpend = Transaction.Create(network);
                doubleSpend.Inputs.Add(coinBaseTx, 0);
                using var k3 = new Key();
                doubleSpend.Outputs.Add(Money.Coins(49.998m), k3.PubKey.WitHash.GetAddress(network));
                doubleSpend.Sign(k1.GetBitcoinSecret(network), coinBaseTx.Outputs.AsCoins().First());
                valid = doubleSpend.Check();

                await rpc.GenerateAsync(101);

                var txId = await rpc.SendRawTransactionAsync(tx);

                await Assert.ThrowsAsync <RPCException>(async() => await rpc.SendRawTransactionAsync(doubleSpend));
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 17
0
    public async Task InitializeAsync(Config config, CoordinatorRoundConfig roundConfig, IRPCClient rpc, CancellationToken cancel)
    {
        Config      = Guard.NotNull(nameof(config), config);
        RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig);
        RpcClient   = Guard.NotNull(nameof(rpc), rpc);

        // Make sure RPC works.
        await AssertRpcNodeFullyInitializedAsync(cancel);

        // Make sure P2P works.
        await InitializeP2pAsync(config.Network, config.GetBitcoinP2pEndPoint(), cancel);

        HostedServices.Register <MempoolMirror>(() => new MempoolMirror(TimeSpan.FromSeconds(21), RpcClient, P2pNode), "Full Node Mempool Mirror");

        if (roundConfig.FilePath is { })
        private volatile bool _disposedValue = false;         // To detect redundant calls

        public StatusBarViewModel(string dataDir, Network network, Config config, HostedServices hostedServices, SmartHeaderChain smartHeaderChain, WasabiSynchronizer synchronizer, LegalDocuments?legalDocuments)
        {
            DataDir          = dataDir;
            Network          = network;
            Config           = config;
            HostedServices   = hostedServices;
            SmartHeaderChain = smartHeaderChain;
            Synchronizer     = synchronizer;
            LegalDocuments   = legalDocuments;
            Backend          = BackendStatus.NotConnected;
            UseTor           = false;
            Tor            = TorStatus.NotRunning;
            Peers          = 0;
            BtcPrice       = "$0";
            ActiveStatuses = new StatusSet();
        }
Exemplo n.º 19
0
        private volatile bool _disposedValue = false;         // To detect redundant calls

        public StatusBarViewModel(string dataDir, Network network, Config config, HostedServices hostedServices, SmartHeaderChain smartHeaderChain, WasabiSynchronizer synchronizer)
        {
            DataDir          = dataDir;
            Network          = network;
            Config           = config;
            HostedServices   = hostedServices;
            SmartHeaderChain = smartHeaderChain;
            Synchronizer     = synchronizer;
            Backend          = BackendStatus.NotConnected;
            UseTor           = false;
            Tor                     = TorStatus.NotRunning;
            Peers                   = 0;
            _exchangeRate           = "";
            IsExchangeRateAvailable = false;
            ActiveStatuses          = new StatusSet();
        }
Exemplo n.º 20
0
        public async Task InitializeAsync(Config config, CoordinatorRoundConfig roundConfig, IRPCClient rpc, CancellationToken cancel)
        {
            Config      = Guard.NotNull(nameof(config), config);
            RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig);
            RpcClient   = Guard.NotNull(nameof(rpc), rpc);

            // Make sure RPC works.
            await AssertRpcNodeFullyInitializedAsync();

            // Make sure P2P works.
            await InitializeP2pAsync(config.Network, config.GetBitcoinP2pEndPoint(), cancel);

            CoordinatorParameters coordinatorParameters = new(DataDir);

            HostedServices.Register <WabiSabiCoordinator>(new WabiSabiCoordinator(coordinatorParameters, RpcClient), "WabiSabi Coordinator");

            if (roundConfig.FilePath is { })
Exemplo n.º 21
0
        public static async Task <CoreNode> CreateAsync(HostedServices hostedServices, [CallerFilePath] string callerFilePath = null, [CallerMemberName] string callerMemberName = null, string additionalFolder = null, MempoolService mempoolService = null)
        {
            var network = Network.RegTest;

            return(await CoreNode.CreateAsync(
                       new CoreNodeParams(
                           network,
                           mempoolService ?? new MempoolService(),
                           hostedServices,
                           Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.ExtractFileName(callerFilePath), callerMemberName, additionalFolder ?? ""),
                           tryRestart : true,
                           tryDeleteDataDir : true,
                           EndPointStrategy.Random,
                           EndPointStrategy.Random,
                           txIndex : 1,
                           prune : 0,
                           userAgent : $"/WasabiClient:{Constants.ClientVersion}/"),
                       CancellationToken.None));
        }
Exemplo n.º 22
0
    public Global(string dataDir, Config config, UiConfig uiConfig, WalletManager walletManager)
    {
        using (BenchmarkLogger.Measure())
        {
            DataDir     = dataDir;
            Config      = config;
            UiConfig    = uiConfig;
            TorSettings = new TorSettings(DataDir, distributionFolderPath: EnvironmentHelpers.GetFullBaseDirectory(), Config.TerminateTorOnExit, Environment.ProcessId);

            HostedServices = new HostedServices();
            WalletManager  = walletManager;

            var networkWorkFolderPath = Path.Combine(DataDir, "BitcoinStore", Network.ToString());
            AllTransactionStore = new AllTransactionStore(networkWorkFolderPath, Network);
            SmartHeaderChain smartHeaderChain = new(maxChainSize : 20_000);
            IndexStore = new IndexStore(Path.Combine(networkWorkFolderPath, "IndexStore"), Network, smartHeaderChain);
            var mempoolService = new MempoolService();
            var blocks         = new FileSystemBlockRepository(Path.Combine(networkWorkFolderPath, "Blocks"), Network);

            BitcoinStore = new BitcoinStore(IndexStore, AllTransactionStore, mempoolService, blocks);

            if (Config.UseTor)
            {
                BackendHttpClientFactory  = new HttpClientFactory(TorSettings.SocksEndpoint, backendUriGetter: () => Config.GetCurrentBackendUri());
                ExternalHttpClientFactory = new HttpClientFactory(TorSettings.SocksEndpoint, backendUriGetter: null);
            }
            else
            {
                BackendHttpClientFactory  = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => Config.GetFallbackBackendUri());
                ExternalHttpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: null);
            }

            Synchronizer           = new WasabiSynchronizer(BitcoinStore, BackendHttpClientFactory);
            LegalChecker           = new(DataDir);
            TransactionBroadcaster = new TransactionBroadcaster(Network, BitcoinStore, BackendHttpClientFactory, WalletManager);

            RoundStateUpdaterCircuit = new PersonCircuit();

            Cache = new MemoryCache(new MemoryCacheOptions
            {
                SizeLimit = 1_000,
                ExpirationScanFrequency = TimeSpan.FromSeconds(30)
            });
        public async Task RpcWorksAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            try
            {
                var blockCount = await coreNode.RpcClient.GetBlockCountAsync();

                Assert.Equal(0, blockCount);
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 24
0
        public Global(string dataDir, string torLogsFile, Config config, UiConfig uiConfig, WalletManager walletManager)
        {
            using (BenchmarkLogger.Measure())
            {
                CrashReporter = new CrashReporter();
                StoppingCts   = new CancellationTokenSource();
                DataDir       = dataDir;
                Config        = config;
                UiConfig      = uiConfig;
                TorSettings   = new TorSettings(DataDir, torLogsFile, distributionFolderPath: EnvironmentHelpers.GetFullBaseDirectory());

                Logger.InitializeDefaults(Path.Combine(DataDir, "Logs.txt"));

                HostedServices = new HostedServices();
                WalletManager  = walletManager;

                LegalDocuments = LegalDocuments.TryLoadAgreed(DataDir);

                WalletManager.OnDequeue += WalletManager_OnDequeue;
                WalletManager.WalletRelevantTransactionProcessed += WalletManager_WalletRelevantTransactionProcessed;

                var networkWorkFolderPath = Path.Combine(DataDir, "BitcoinStore", Network.ToString());
                var transactionStore      = new AllTransactionStore(networkWorkFolderPath, Network);
                var indexStore            = new IndexStore(Path.Combine(networkWorkFolderPath, "IndexStore"), Network, new SmartHeaderChain());
                var mempoolService        = new MempoolService();
                var blocks = new FileSystemBlockRepository(Path.Combine(networkWorkFolderPath, "Blocks"), Network);

                BitcoinStore = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);

                SingleInstanceChecker = new SingleInstanceChecker(Network);

                if (Config.UseTor)
                {
                    Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, () => Config.GetCurrentBackendUri(), Config.TorSocks5EndPoint);
                }
                else
                {
                    Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, Config.GetFallbackBackendUri(), null);
                }
            }
        }
Exemplo n.º 25
0
        public async Task VerboseBlockInfoAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            try
            {
                var rpc       = coreNode.RpcClient;
                var blockInfo = await rpc.GetVerboseBlockAsync(coreNode.Network.GenesisHash);

                Assert.NotNull(blockInfo.Transactions.ElementAt(0).Inputs.ElementAt(0).Coinbase);
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 26
0
        public static async Task <CoreNode> CreateAsync(HostedServices hostedServices, [CallerFilePath] string callerFilePath = null, [CallerMemberName] string callerMemberName = null, string additionalFolder = null, MempoolService mempoolService = null)
        {
            var network = Network.RegTest;

            return(await CoreNode.CreateAsync(
                       new CoreNodeParams(
                           network,
                           mempoolService ?? new MempoolService(),
                           hostedServices,
                           Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.ExtractFileName(callerFilePath), callerMemberName, additionalFolder ?? ""),
                           tryRestart : true,
                           tryDeleteDataDir : true,
                           EndPointStrategy.Random,
                           EndPointStrategy.Random,
                           txIndex : 1,
                           prune : 0,
                           mempoolReplacement : "fee,optin",
                           userAgent : $"/WasabiClient:{Constants.ClientVersion}/",
                           fallbackFee : Money.Coins(0.0002m),             // https://github.com/bitcoin/bitcoin/pull/16524
                           new MemoryCache(new MemoryCacheOptions())),
                       CancellationToken.None));
        }
        /// <summary>
        /// Generate a DPWSHostedService source file from a Wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateHostedService(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string hostedServiceClassName = serviceDesc.Name;
            string hostedServiceNs        = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "HostedService.cs";

            HostedServices hostedServices = new HostedServices(hostedServiceNs);

            string ns = serviceDesc.TargetNamespace.Trim();

            if (!ns.EndsWith("/"))
            {
                ns += "/";
            }

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                HostedService hostedService = new HostedService(portType.Name, hostedServiceNs, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction  = ns + operation.Name + "Request";
                    string outAction = ns + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    hostedService.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    hostedService.Messages.Add(message);
                }
            }

            HostedServiceGenerator hostedServiceGen = new HostedServiceGenerator();

            hostedServiceGen.GenerateCode(filename, hostedServices);
        }
        public async Task P2pWorksAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            using var node = await coreNode.CreateNewP2pNodeAsync();

            try
            {
                var blocks  = node.GetBlocks(new[] { Network.RegTest.GenesisHash });
                var genesis = Assert.Single(blocks);
                Assert.Equal(genesis.GetHash(), Network.RegTest.GenesisHash);
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                node.Disconnect();
                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 29
0
        public async Task AllFeeEstimateAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            try
            {
                var rpc         = coreNode.RpcClient;
                var estimations = await rpc.EstimateAllFeeAsync(EstimateSmartFeeMode.Conservative, simulateIfRegTest : true, tolerateBitcoinCoreBrainfuck : true);

                Assert.Equal(WalletWasabi.Helpers.Constants.OneDayConfirmationTarget, estimations.Estimations.Count);
                Assert.True(estimations.Estimations.First().Key < estimations.Estimations.Last().Key);
                Assert.True(estimations.Estimations.First().Value > estimations.Estimations.Last().Value);
                Assert.Equal(EstimateSmartFeeMode.Conservative, estimations.Type);
                estimations = await rpc.EstimateAllFeeAsync(EstimateSmartFeeMode.Economical, simulateIfRegTest : true, tolerateBitcoinCoreBrainfuck : true);

                Assert.Equal(145, estimations.Estimations.Count);
                Assert.True(estimations.Estimations.First().Key < estimations.Estimations.Last().Key);
                Assert.True(estimations.Estimations.First().Value > estimations.Estimations.Last().Value);
                Assert.Equal(EstimateSmartFeeMode.Economical, estimations.Type);
                estimations = await rpc.EstimateAllFeeAsync(EstimateSmartFeeMode.Economical, simulateIfRegTest : true, tolerateBitcoinCoreBrainfuck : false);

                Assert.Equal(145, estimations.Estimations.Count);
                Assert.True(estimations.Estimations.First().Key < estimations.Estimations.Last().Key);
                Assert.True(estimations.Estimations.First().Value > estimations.Estimations.Last().Value);
                Assert.Equal(EstimateSmartFeeMode.Economical, estimations.Type);
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 30
0
        public Global(string dataDir, Config config, UiConfig uiConfig, WalletManager walletManager)
        {
            using (BenchmarkLogger.Measure())
            {
                DataDir     = dataDir;
                Config      = config;
                UiConfig    = uiConfig;
                TorSettings = new TorSettings(DataDir, distributionFolderPath: EnvironmentHelpers.GetFullBaseDirectory(), Config.TerminateTorOnExit, Environment.ProcessId);

                HostedServices = new HostedServices();
                WalletManager  = walletManager;

                var networkWorkFolderPath = Path.Combine(DataDir, "BitcoinStore", Network.ToString());
                var transactionStore      = new AllTransactionStore(networkWorkFolderPath, Network);
                var indexStore            = new IndexStore(Path.Combine(networkWorkFolderPath, "IndexStore"), Network, new SmartHeaderChain());
                var mempoolService        = new MempoolService();
                var blocks = new FileSystemBlockRepository(Path.Combine(networkWorkFolderPath, "Blocks"), Network);

                BitcoinStore = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);

                if (Config.UseTor)
                {
                    BackendHttpClientFactory  = new HttpClientFactory(TorSettings.SocksEndpoint, backendUriGetter: () => Config.GetCurrentBackendUri());
                    ExternalHttpClientFactory = new HttpClientFactory(TorSettings.SocksEndpoint, backendUriGetter: null);
                }
                else
                {
                    BackendHttpClientFactory  = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => Config.GetFallbackBackendUri());
                    ExternalHttpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: null);
                }

                Synchronizer           = new WasabiSynchronizer(BitcoinStore, BackendHttpClientFactory);
                LegalChecker           = new(DataDir);
                TransactionBroadcaster = new TransactionBroadcaster(Network, BitcoinStore, BackendHttpClientFactory, WalletManager);
            }
        }
Exemplo n.º 31
0
 public Global(string dataDir)
 {
     DataDir        = dataDir ?? EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Backend"));
     HostedServices = new HostedServices();
 }
        private void processUpdate()
        {
            if (!checkPorts())
            {
                UpdateMessage.Text = UpdateMessage.Text + "<br/><span style=\"color:Yellow \">You are already using the same port for another endpoint with a different" +
                " network scheme (protocol) within this service host. You must choose a different port.</span>";
                return;
            }
            int success = ConfigUtility.CLUSTER_UPDATE_FULL_SUCCESS;
            UpdateMessage.Text = "";
            LabelBaseAddressWarning.Text = "";
            List<HostedServices> thisServiceHostServices = compositeServiceData[0].HostedServices.FindAll(delegate(HostedServices hsExist) { return hsExist.ServiceHostID == SHID; });
            if (!validateBaseAddresses(thisServiceHostServices, action))
                return;
            Page.Validate();
            if (!Page.IsValid)
                return;
            if (DropDownListBindingConfig.Items.Count == 0 || DropDownListInternalClient.Items.Count == 0)
            {
                UpdateMessage.Text = "You must ensure this host has valid Binding Configurations for both the host binding and the internal client binding defined in it's config file.  Currently, for the selected binding type, this is not the case. Please see tutorial: Binding Configurations names must be prefaced with 'Host_' and 'Client_' to appear properly in this page.";
                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                return;
            }
            HostedServices updateHostedService = new HostedServices();
            if (TextBoxOnlineMethod.Text.Trim() == null || TextBoxOnlineMethod.Text.Trim() == "")
                updateHostedService.OnlineMethod = ConfigUtility.NO_ONLINE_METHOD;
            else
                updateHostedService.OnlineMethod = TextBoxOnlineMethod.Text;
            if (CheckBoxOnlineParms.Checked)
                updateHostedService.OnlineParms = TextBoxOnlineParms.Text;
            else
                updateHostedService.OnlineParms = ConfigUtility.NO_ONLINE_PARMS;
            switch (thisServiceHost.ServiceType)
            {
                case ConfigUtility.HOST_TYPE_CONFIG:
                    {
                        if (action == ConfigUtility.REMOVE_HOSTED_SERVICE || action == ConfigUtility.UPDATE_HOSTED_SERVICE)
                        {
                            List<HostedServices> configList = compositeServiceData[0].HostedServices.FindAll(delegate(HostedServices hsExist) { return hsExist.ServiceType == ConfigUtility.HOST_TYPE_CONFIG; });
                            if (configList.Count < 2 && action == ConfigUtility.REMOVE_HOSTED_SERVICE)
                            {
                                if (action == ConfigUtility.REMOVE_HOSTED_SERVICE || !CheckBoxActivate.Checked)
                                    UpdateMessage.Text = "You must have at least one active Configuration Service Endpoint!";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                CheckBoxActivate.Checked = true;
                                return;
                            }
                        }
                        break;
                    }
                case ConfigUtility.HOST_TYPE_NODE:
                    {
                        ConfigurationKeyValues activeNodeID = compositeServiceData[0].ConfigurationData.Find(delegate(ConfigurationKeyValues keyExist) { return keyExist.ConfigurationKeyFieldName == "NODE_ACTIVE_SERVICE_ID"; });
                        if (activeNodeID.ConfigurationKeyValue.Equals(thisService.HostedServiceID.ToString()))
                        {
                            if (!CheckBoxActivate.Checked)
                            {
                                UpdateMessage.Text = "You cannot deactivate the configured Active Node Endpoint!";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                CheckBoxActivate.Checked = true;
                                return;
                            }
                            if (action == ConfigUtility.REMOVE_HOSTED_SERVICE)
                            {
                                UpdateMessage.Text = "You cannot delete the configured Active Node Endpoint!";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                return;
                            }
                            if (DropDownListInternalClient.SelectedValue.Equals(ConfigUtility.NO_CLIENT_CONFIGURATION))
                            {

                                UpdateMessage.Text = "You cannot define an Active Node Service Endpoint without selecting a valid Internal Client Configuration from your existing definitions in the applications 'client' section of config.  Please either select an existing client configuration above, or add a new client definition to your configuration if needed.";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                return;
                            }
                        }
                        break;
                    }

                case ConfigUtility.HOST_TYPE_NODE_DC:
                    {
                        ConfigurationKeyValues activeNodeDCID = compositeServiceData[0].ConfigurationData.Find(delegate(ConfigurationKeyValues keyExist) { return keyExist.ConfigurationKeyFieldName == "NODE_ACTIVE_DC_SERVICE_ID"; });
                        if (activeNodeDCID.ConfigurationKeyValue.Equals(thisService.HostedServiceID.ToString()))
                        {
                            if (!CheckBoxActivate.Checked)
                            {
                                UpdateMessage.Text = "You cannot deactivate the configured Active Node Distributed Cache Endpoint!";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                CheckBoxActivate.Checked = true;
                                return;
                            }
                            if (action == ConfigUtility.REMOVE_HOSTED_SERVICE)
                            {
                                UpdateMessage.Text = "You cannot delete the configured Active Node Distributed Cache Endpoint!";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                return;
                            }
                            if (DropDownListInternalClient.SelectedValue.Equals(ConfigUtility.NO_CLIENT_CONFIGURATION))
                            {

                                UpdateMessage.Text = "You cannot define an Active Node DC Service Endpoint without selecting a valid Internal Client Configuration from your existing definitions in the applications 'client' section of config.  Please either select an existing client configuration above, or add a new client definition to your configuration if needed.";
                                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                                return;
                            }
                        }
                        break;
                    }
            }
            if (CheckBoxActivate.Checked)
                updateHostedService.Activated = true;
            else
                updateHostedService.Activated = false;
            updateHostedService.BindingType = RadioButtonListBindingType.SelectedValue;
            updateHostedService.UseHttps = CheckBoxHttps.Checked;
            updateHostedService.VirtualPath = TextBoxVirtualPath.Text.ToLower().Trim().Trim(new char[] { '/' });
            TextBoxVirtualPath.Text = updateHostedService.VirtualPath;
            int port = -1;
            try
            {
                port = Convert.ToInt32(TextBoxPort.Text.Trim().Trim(new char[] { ':' }));
            }
            catch
            {
                UpdateMessage.Text = "You must specify a port in the form of an integer!";
                UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                return;
            }
            if (updateHostedService.BindingType != ConfigUtility.NET_MSMQ_BINDING && updateHostedService.BindingType != ConfigUtility.CUSTOM_BINDING_NET_MSMQ)
            {
                if (port < 80 || port > 65534)
                {
                    UpdateMessage.Text = "You must specify a port between 80 and 65534!";
                    UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                    return;
                }
            }
            if (!CheckBoxIdentity.Checked)
                updateHostedService.IdentityConfigName = ConfigUtility.NO_ENDPOINT_IDENTITY;
            else
                updateHostedService.IdentityConfigName = DropDownListIdentity.SelectedValue;
            updateHostedService.Port = TextBoxPort.Text.Trim().Trim(new char[] { ':' });
            TextBoxPort.Text = updateHostedService.Port;
            if (thisServiceHost.ServiceType == ConfigUtility.HOST_TYPE_PRIMARY || thisServiceHost.ServiceType == ConfigUtility.HOST_TYPE_CONFIG)
            {
                int userKey = -1;
                if (DropDownListCsUser.Items.Count > 0)
                    userKey = Convert.ToInt32(DropDownListCsUser.SelectedValue);
                updateHostedService.csUserKey = userKey;
            }
            else
                updateHostedService.csUserKey = -1;
            string scheme = ConfigUtility.getBindingScheme(updateHostedService.BindingType, updateHostedService.UseHttps);
            string defaultAddress = null;
            if (DropDownListEPB.Items.Count == 0 || !CheckBoxEPB.Checked)
                updateHostedService.EndPointBehavior = ConfigUtility.NO_ENDPOINT_BEHAVIOR;
            else
                if (DropDownListEPB.Items.Count == 0)
                    updateHostedService.EndPointBehavior = ConfigUtility.NO_ENDPOINT_BEHAVIOR;
                else
                    updateHostedService.EndPointBehavior = DropDownListEPB.SelectedValue;
            updateHostedService.FriendlyName = TextBoxHostedServiceName.Text.Trim();
            if (action != ConfigUtility.ADD_HOSTED_SERVICE)
                updateHostedService.HostedServiceID = thisService.HostedServiceID;
            else
                updateHostedService.HostedServiceID = -1;
            updateHostedService.HostName = LabelVHostName.Text;
            updateHostedService.InternalClientConfiguration = DropDownListInternalClient.SelectedValue;
            updateHostedService.IsBaseAddress = CheckBoxBaseAddress.Checked;
            if (thisServiceHost.ServiceType != ConfigUtility.HOST_TYPE_NODE && thisServiceHost.ServiceType != ConfigUtility.HOST_TYPE_NODE_DC)
                updateHostedService.LoadBalanceType = Convert.ToInt32(RadioButtonListLoadBalanceType.SelectedValue);
            else
                updateHostedService.LoadBalanceType = ConfigUtility.LOAD_BALANCE_TYPE_HOST_ADDRESS;
            if (updateHostedService.LoadBalanceType == ConfigUtility.LOAD_BALANCE_TYPE_VIRTUAL_ADDRESS)
            {
                string lba = TextBoxLoadBalanceAddress.Text.ToLower().Trim().Trim(new char[] { '/' });
                if (lba == null || lba.Length < 1)
                {
                    UpdateMessage.Text = "If using external load balancing, you must supply the load balanced address!";
                    UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                    return;
                }
                updateHostedService.LoadBalanceAddress = lba;
            }
            else
                updateHostedService.LoadBalanceAddress = "Not Implemented";
            if (thisServiceHost.ServiceType == ConfigUtility.HOST_TYPE_PRIMARY)
                if (updateHostedService.LoadBalanceType.Equals(ConfigUtility.LOAD_BALANCE_TYPE_HOST_ADDRESS))
                    defaultAddress = updateHostedService.LoadBalanceAddress;
                else
                    defaultAddress = "[enter servername here]";
            else
                defaultAddress = "none";
            updateHostedService.DefaultAddress = defaultAddress;
            updateHostedService.MarkedForFailover = CheckBoxFailover.Checked;
            updateHostedService.mex = CheckBoxMex.Checked;
            updateHostedService.OnlineMethod = TextBoxOnlineMethod.Text.Trim();
            if (updateHostedService.OnlineMethod == null || updateHostedService.OnlineMethod == "")
                updateHostedService.OnlineMethod = ConfigUtility.NO_ONLINE_METHOD;
            if (CheckBoxOnlineParms.Checked)
            {
                string parms = TextBoxOnlineParms.Text.Trim();
                if (parms == null || parms.Length < 1)
                {
                    UpdateMessage.Text = "If your online method expects parameters as you indicate, you must supply here in form of delimited list like 'string=strvalue;int=6;bool=true' or combination thereof.";
                    UpdateMessage.ForeColor = System.Drawing.Color.Maroon;
                    return;
                }
                updateHostedService.OnlineParms = parms;
            }
            else
                updateHostedService.OnlineParms = ConfigUtility.NO_ONLINE_PARMS;
            updateHostedService.ServiceBinding = DropDownListBindingConfig.SelectedValue;
            updateHostedService.ServiceHostID = SHID;
            updateHostedService.ServiceImplementationClassName = thisServiceHost.ServiceImplementationClass;
            updateHostedService.ServiceType = thisServiceHost.ServiceType;
            updateHostedService.ServiceContract = DropDownListContracts.SelectedValue;
            traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy,  address, binding, user);

            //OK, enough checking for valid settings---lets do it! Make the call to update or add or delete this endpoint!!
            success = configProxy.receiveService(hostNameIdentifier, configName, thisOldService, updateHostedService, null, null, null, null, null, true, action, traversePath, user);
            if (success == ConfigUtility.CLUSTER_UPDATE_FULL_SUCCESS)
            {
                Thread.Sleep(5000);
                if (compositeServiceData[0].RunTimePlatform.ToLower().Contains("azure"))
                {
                    if (!updateHostedService.LoadBalanceType.Equals(ConfigUtility.LOAD_BALANCE_TYPE_VIRTUAL_ADDRESS) && updateHostedService.ServiceType != ConfigUtility.HOST_TYPE_NODE)
                    {
                        UpdateMessageAzureLB.Text = "<br/><span style=\"color:#FFFF99;\">WARNING: You are hosting on Windows Azure so typically, you should mark your Configuration Service and Primary endpoints as externally load balanced on this page; and supply " +
                            "the Azure hosted service DNS base address + port for this endpoint.  Windows Azure will <strong>always</strong> externally load balance input endpoints.  By not specifiying the external load balance address and port" +
                            " (for example azurestocktraderbsl.cloudapp.net:443) on this page, Configuration Service may not work properly. It is very important to get the address and port exactly right.  The update has gone through, " +
                            "but after considering this message, you can make any adjustments and update the endpoint again with the correct Azure public-facing address + port.  If this is an internal endpoint, you can ignore this message.</span>";
                    }
                }
                try
                {
                    configProxy.Channel = null;
                    traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy, address, binding, user);
                    compositeServiceData = configProxy.getServiceConfiguration(hostNameIdentifier, configName, ConfigUtility.CONFIG_LEVEL_BASIC, false, traversePath, user);
                }
                catch (Exception)
                {
                    //Try again for good measure.
                    Thread.Sleep(3000);
                    try
                    {
                        traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy, address, binding, user);
                        compositeServiceData = null;
                        compositeServiceData = configProxy.getServiceConfiguration(hostNameIdentifier, configName, ConfigUtility.CONFIG_LEVEL_BASIC, false, traversePath, user);
                        if (compositeServiceData == null || compositeServiceData[0] == null)
                        {
                            UpdateMessage.Text = "<br/><span style=\"color:Maroon\">Error! The Configuration Service was not able to restart with your new definition.  Please check the event log.  You will" +
                                "not be able to continue until this is fixed, since ConfigWeb has no way to establish a connection to the Configuration Service, since it is no longer running at the remote host(s).</span>";
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        UpdateMessage.Text = "<br/><span style=\"color:Maroon\">Error! The Configuration Service was not able to restart with your new definition.  Please check the event log.  You will" +
                               "not be able to continue until you login in again.  If there is an errror starting the Configuration Service Host, you will not be able to login until this issue is fixed.</span>";
                        SessionInfo info = new SessionInfo();
                        info.setSessionData(null, null, null, null, null, null, null, null, null);
                        return;
                    }
                }
                switch (action)
                {
                    case ConfigUtility.ADD_HOSTED_SERVICE:
                        {
                            if (compositeServiceData != null)
                            {
                                thisService = compositeServiceData[0].HostedServices.Find(delegate(HostedServices hsExist) { return hsExist.FriendlyName == updateHostedService.FriendlyName && hsExist.ServiceHostID == SHID; });
                                //thisService = updateHostedService;
                                if (thisService != null)
                                {
                                    thisOldService = thisService;
                                    SHID = thisService.ServiceHostID;
                                    ViewState["SHID"] = SHID;
                                    HSID = thisService.HostedServiceID;
                                    ViewState["HSID"] = HSID;
                                    ViewState["CompositeServiceData"] = compositeServiceData;
                                    ViewState["thisOldService"] = thisService;
                                    ViewState["thisService"] = thisService;
                                    action = ConfigUtility.UPDATE_HOSTED_SERVICE;
                                    ViewState["action"] = action;
                                    Add.Enabled = false;
                                    Update.Enabled = true;
                                    Delete.Enabled = true;
                                }
                            }
                            break;
                        }
                    case ConfigUtility.REMOVE_HOSTED_SERVICE:
                        {
                            Add.Enabled = false;
                            Update.Enabled = false;
                            Delete.Enabled = false;
                            break;
                        }
                }
                if (compositeServiceData!=null)
                    UpdateMessage.Text = "<br/><span style=\"color:PaleGreen \">The Hosted Service definition was sucessfully " + actiontext + ".</span>";
                else
                    UpdateMessage.Text = "<br/><span style=\"color:Maroon \">The Hosted Service definition was sucessfully sent.  However, there was an error retrieving updated results.</span>";
            }
            else
            {
                string message = null;
                switch (success)
                {
                    case ConfigUtility.CLUSTER_UPDATE_FAIL_PERSISTED:
                        {
                            message = ConfigSettings.EXCEPTION_MESSAGE_FAIL_PERSISTED;
                            break;
                        }

                    case ConfigUtility.CLUSTER_UPDATE_FAIL_VALIDATION:
                        {
                            message = ConfigSettings.EXCEPTION_MESSAGE_FAIL_VALIDATION;
                            break;
                        }

                    case ConfigUtility.CLUSTER_UPDATE_FAIL_AUTHENTICATION:
                        {
                            message = ConfigSettings.EXCEPTION_MESSAGE_FAIL_AUTHORIZATION;
                            break;
                        }
                    case ConfigUtility.CLUSTER_UPDATE_FAIL_REMOTE:
                        {
                            message = ConfigSettings.EXCEPTION_MESSAGE_FAIL_REMOTE_UPDATE;
                            break;
                        }
                    default:
                        {
                            message = ConfigSettings.EXCEPTION_MESSAGE_FAIL_REMOTE_PEER + success.ToString();
                            break;
                        }
                }
                UpdateMessage.Text = "<br/><span style=\"color:Maroon\">" + message + "</span>";
                thisOldService = (HostedServices)ViewState["thisOldService"];
                thisService = thisOldService;
                ViewState["thisService"] = thisService;
            }
        }
 protected override void OnLoad(EventArgs e)
 {
     Page.Form.DefaultFocus = DropDownListContracts.ClientID;
     Input.getHostData(IsPostBack, ViewState, out userid, out address, out user, out binding, out hostNameIdentifier, out configName, out version, out platform, out hoster, false);
     if (!IsPostBack)
     {
         ViewState["processing"] = false;
         action = Request["action"];
         string idString = Request["HSID"];
         string vidString = Request["SHID"];
         SHID = Convert.ToInt32(vidString);
         if (vidString == null || vidString == "")
             Response.Redirect(ConfigSettings.PAGE_NODES,true);
         if (idString != null)
             HSID = Convert.ToInt32(idString);
         traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy,  address, binding, user);
         compositeServiceData = configProxy.getServiceConfiguration(hostNameIdentifier, configName, ConfigUtility.CONFIG_LEVEL_BASIC, false, traversePath, user);
         serviceHosts = configProxy.getVirtualServiceHosts(hostNameIdentifier, configName, traversePath, user);
         serviceUsers = configProxy.getServiceUsers(hostNameIdentifier, configName, traversePath, user);
         serviceUsers.RemoveAll(delegate(ServiceUsers userExist) { return !userExist.LocalUser || userExist.Rights != ConfigUtility.CONFIG_CONNECTED_SERVICE_RIGHTS; });
         if (compositeServiceData == null)
         {
             Response.Redirect(ConfigSettings.PAGE_NODES,true);
         }
         thisService = compositeServiceData[0].HostedServices.Find(delegate(HostedServices hsExist) { return hsExist.HostedServiceID == HSID; });
         thisServiceHost = serviceHosts.Find(delegate(MasterServiceHostInstance mshExist) { return mshExist.ServiceHostID == SHID; });
         if (thisServiceHost.HostEnvironment == ConfigUtility.HOSTING_ENVIRONMENT_IIS)
         {
             LabelVDirWarning.Text = "This is an IIS-Hosted Service.  If you mark this endpoint as a BASE address (below), you must specify the exact virtual directory + filename for your .svc file, as this is what WCF will expect as a base address. Relative addresses for an IIS-hosted service, become " +
             "the virtual directory + /[.svcfilename]/path.  For example, you can add a relative address to /myVdir/myservice.svc as /myVDir/myservice.svc/mynewendpoint.";
             LabelPortWarning.Text = "As an IIS-hosted service endpoint, typically this will be 80 for non-SSL services, and 443 for SSL services, unless you have otherwise configured your IIS site that hosts your service.";
             LabelPortWarning.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFF99");
             LabelVDirWarning.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFF99");
         }
         if (thisServiceHost.ServiceType.Equals(ConfigUtility.HOST_TYPE_NODE) || thisServiceHost.ServiceType.Equals(ConfigUtility.HOST_TYPE_NODE_DC))
             RadioButtonListLoadBalanceType.Enabled=false;
         DropDownListEPB.Items.Clear();
         for (int i = 0; i < compositeServiceData[0].EndpointBehaviorNames.Count; i++)
         {
             DropDownListEPB.Items.Add(new ListItem(compositeServiceData[0].EndpointBehaviorNames[i], compositeServiceData[0].EndpointBehaviorNames[i]));
         }
         if (DropDownListEPB.Items.Count == 0)
         {
             DropDownListEPB.Enabled = false;
             LabelEPB.Text = "No Endpoint Behaviors were initialized as part of your service startup procedure.  Hence, you cannot select any endpoint behaviors at this time.";
             CheckBoxEPB.Enabled = false;
         }
         else
         {
             DropDownListEPB.Enabled = true;
             CheckBoxEPB.Enabled = true;
         }
         DropDownListIdentity.Items.Clear();
         for (int i = 0; i < compositeServiceData[0].EndpointIdentityNames.Count; i++)
         {
             DropDownListIdentity.Items.Add(new ListItem(compositeServiceData[0].EndpointIdentityNames[i], compositeServiceData[0].EndpointIdentityNames[i]));
         }
         if (DropDownListIdentity.Items.Count == 0)
         {
             DropDownListEPB.Enabled = false;
             LabelIdentity.Text = "No Endpoint identities have been configured in the config file section <endpointIdentities>. Hence, you cannot select any endpoint identities at this time, default values will be used.";
             CheckBoxIdentity.Enabled = false;
         }
         ViewState["CompositeServiceData"] = compositeServiceData;
         ViewState["SHID"] = SHID;
         ViewState["HSID"] = HSID;
         ViewState["thisOldService"] = thisService;
         ViewState["thisService"] = thisService;
         ViewState["action"] = action;
         ViewState["serviceHosts"] = serviceHosts;
         ViewState["serviceUsers"] = serviceUsers;
         initRadioButtons();
         narrowSelections();
         if (!action.Equals(ConfigUtility.ADD_HOSTED_SERVICE))
             getData();
         else
             initData();
         buildBindingLists(false);
     }
     else
     {
         UpdateMessageAzureLB.Text = "";
         compositeServiceData = (List<ServiceConfigurationData>)ViewState["CompositeServiceData"];
         SHID = (int)ViewState["SHID"];
         HSID = (int)ViewState["HSID"];
         serviceHosts = (List<MasterServiceHostInstance>)ViewState["serviceHosts"];
         serviceUsers = (List<ServiceUsers>)ViewState["serviceUsers"];
         thisOldService = (HostedServices)ViewState["thisOldService"];
         thisService = (HostedServices)ViewState["thisService"];
         action = (string)ViewState["action"];
         thisServiceHost = serviceHosts.Find(delegate(MasterServiceHostInstance mshExist) { return mshExist.ServiceHostID == SHID; });
     }
     TopNode.PostBackUrl = ConfigSettings.PAGE_NODES;
     ServiceVersion.Text = version;
     ServicePlatform.Text = platform;
     ServiceHoster.Text = hoster;
     TopNodeName.Text = hostNameIdentifier;
     ReturnLabel.Text = "<a class=\"Return\" href=\"" + ConfigSettings.PAGE_HOSTED_SERVICES + "?name=" + hostNameIdentifier + "&cfgSvc=" + configName + "&version=" + version + "&platform=" + platform + "&hoster=" + hoster + "&ID=" + SHID + "&hostname=" + thisServiceHost.HostName + "\">Return to Hosted Services for this Virtual Host</a>";
     GetImageButton.runtimePoweredBy(platform, RuntimePlatform);
     if (action.Equals(ConfigUtility.ADD_HOSTED_SERVICE))
     {
         Update.Enabled = false;
         Delete.Enabled = false;
     }
     else
     {
         Add.Enabled = false;
     }
     thisServiceHost = serviceHosts.Find(delegate(MasterServiceHostInstance mshExist) { return mshExist.ServiceHostID == SHID; });
     LabelClassName.Text = thisServiceHost.ServiceImplementationClass;
     LabelVHostName.Text = thisServiceHost.HostName;
 }
 protected void Add_Click(object sender, EventArgs e)
 {
     processing = (bool)ViewState["processing"];
     if (processing)
         return;
     ViewState["processing"] = true;
     action = ConfigUtility.ADD_HOSTED_SERVICE;
     actiontext = "added";
     thisService = new HostedServices();
     processUpdate();
     ViewState["processing"] = false;
 }
Exemplo n.º 35
0
        /// <summary>
        /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types,
        /// HostedServices and Client Proxies.
        /// </summary>
        /// <remarks>Currently only generates C# source files.</remarks>
        /// <param name="contractFilename">The name of a contract source code (.cs) file.</param>
        /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param>
        /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param>
        /// <param name="targetPlatform">Specifies the target runtime platform.</param>
        public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform)
        {
            m_platform = targetPlatform;

            Logger.WriteLine("", LogLevel.Normal);
            Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal);

            if (contractFilename == null)
                throw new ArgumentNullException("codeFilename", "You must pass a valid code filename.");

            if (m_svcDesc.Types == null)
            {
                throw new Exception("No wsdl types found.");
            }

            string path = Path.GetDirectoryName(contractFilename).Trim();

            if(!string.IsNullOrEmpty(path) && !Directory.Exists(path)) 
            {
                Directory.CreateDirectory(path);
            }

            // Create code file stream
            FileStream dcStream = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter dcStreamWriter = new StreamWriter(dcStream);

            // Write the auto generated header
            dcStreamWriter.Write(AutoGenTextHeader.Message);

            try
            {

                // Set up data contract code generator
                CSharpCodeProvider cSharpCP = new CSharpCodeProvider();
                ICodeGenerator codeGen = cSharpCP.CreateGenerator(dcStreamWriter);
                CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
                codeGenOptions.BracingStyle = "C";

                // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.'
                string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace);

                // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh!
                foreach (XmlSchema schema in m_svcDesc.Types.Schemas)
                {
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema);
                    schemaSet.Compile();
                }
                

                // Create new code namespace
                CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName);

                // Add data contract using directives
                CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;");
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using System.Xml;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                if (m_platform == TargetPlatform.MicroFramework)
                {
                    compileUnit.Value = "using System.Ext;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                    compileUnit.Value = "using System.Ext.Xml;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                }
                compileUnit.Value = "using Ws.ServiceModel;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Mtom;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Serialization;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Namespaces.Add(targetNamespace);
                m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces;

                Logger.WriteLine("", LogLevel.Normal);

                // Create HostedServices and ClientProxies collections
                HostedServices hostedServices = new HostedServices(targetNamespaceName);
                ClientProxies clientProxies = new ClientProxies(targetNamespaceName);

                // For each PortType process
                foreach (PortType portType in m_svcDesc.PortTypes)
                {
                    // For each operation in the port type:
                    // Get input and output message parts.
                    // If the message part is a simple type:
                    //   Build HostedService operation.
                    // Else if the message part is an element:
                    //   Find elements in Schema
                    //   If element type is native xml type:
                    //     Build HostedService operation.
                    //   Else if element references a simple or complex type:
                    //     If simpleType is base xml type with restrictions:
                    //       Build HostedService operation.
                    //     Else
                    //       Build DataContract and DataContractSerializer.
                    //       Build HostedService Operation.
                    //     

                    if (!CodeGenUtils.IsSoapBinding(portType, m_svcDesc))
                    {
                        continue;
                    }

                    // Create instance of a HostedService to hold the port type details
                    HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform);

                    // Create instance of ClientProxyGenerator
                    ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform);

                    // Create service contract interface
                    CodeTypeDeclaration serviceCodeType = new CodeTypeDeclaration("I" + portType.Name);
                    CodeAttributeArgument codeAttr = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace));
                    CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("ServiceContract", codeAttr);
                    serviceCodeType.CustomAttributes.Add(codeAttrDecl);

                    // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes
                    // are required to regenerate policy assertions when converting a service to Wsdl.
                    List<PolicyAssertion> policyAssertions = GetPolicyAssertions();
                    bool OptimizedMimeEncoded = false;
                    foreach (PolicyAssertion assert in policyAssertions)
                    {
                        serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID));
                    
                        // if Optimized Mime assertion id found set a processing flag
                        if (assert.Name == "OptimizedMimeSerialization")
                        {
                            OptimizedMimeEncoded = true;
                        }
                    }

                    // Add type declaration
                    serviceCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCodeType.IsInterface = true;

                    // Create service contract callback client interface
                    CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback");

                    // Add type declaration
                    serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCallbackCodeType.IsInterface = true;

                    // If the binding contains a ref to Mtom encoding type set the Mtom flag
                    if (OptimizedMimeEncoded)
                    {
                        m_dcCodeGen.EncodingType = MessageEncodingType.Mtom;
                        hostedService.EncodingType = MessageEncodingType.Mtom;
                        clientProxy.EncodingType = MessageEncodingType.Mtom;
                    }

                    // Step through port operations, get method names and parse elements.
                    for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index)
                    {
                        Operation operation = portType.Operations[pt_index];
                        string operationName = operation.Name;

                        string inputMessageName = null;
                        string outputMessageName = null;
                        MessagePartCollection inputMessageParts = null;
                        MessagePartCollection outputMessageParts = null;
                        string inAction = null;
                        string outAction = null;
                        GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction);

                        // Oneway request port type
                        if (operation.Messages.Flow == OperationFlow.OneWay)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Twoway request/response pattern
                        else if (operation.Messages.Flow == OperationFlow.RequestResponse)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Event pattern
                        else if (operation.Messages.Flow == OperationFlow.Notification)
                        {
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }

                        // Find input and output message parts collection in messages collection
                        // and store for later.
                        foreach (Message message in m_svcDesc.Messages)
                        {
                            if (inputMessageName != null)
                                if (message.Name == inputMessageName)
                                {
                                    inputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }

                            if (outputMessageName != null)
                                if (message.Name == outputMessageName)
                                {
                                    outputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                        }

                        try
                        {
                            // Try to generate Data Contracts and DataContractSerializers
                            GenerateTypeContracts(operation, inputMessageParts, outputMessageParts);

                            // If operation flow is notification (event) add OperationContract to ServiceContractCallback
                            // else add OperationContract to ServiceContract
                            if (operation.Messages.Flow == OperationFlow.Notification)
                            {
                                AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType);
                            }
                            else
                                AddServiceOperationToInterface(operation, inAction, serviceCodeType);
                        }
                        catch (Exception e)
                        {
                            dcStreamWriter.Close();
                            File.Delete(contractFilename);
                            Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                            return;
                        }
                    }

                    // Add serviceCodeType Service Contract interface to namespace
                    // A serviceCodeType is added even if the wsdl only contains notifications. In that case
                    // the contract will be empty but the ServiceContract attribute and CallbackContract argument
                    // will be used to point to the notification or callback contract interace
                    targetNamespace.Types.Add(serviceCodeType);

                    // If service contract callback type contains members add callback contract to namespace
                    // and add CallbackContract reference attribute to serviceCodeType contract.
                    if (serviceCallbackCodeType.Members.Count > 0)
                    {
                        // Add the callback argument to the service description attribute
                        CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract",
                            new CodeTypeOfExpression(serviceCallbackCodeType.Name)
                        );
                        serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg);

                        // Add the callback interface to namespace
                        targetNamespace.Types.Add(serviceCallbackCodeType);
                    }

                    // If the hosted service has opeations add to Hosted Services collection for Code Gen
                    if (hostedService.ServiceOperations.Count > 0)
                        hostedServices.Add(hostedService);

                    // If the client Proxy service has opeations add to client proxy collection for Code Gen
                    if (clientProxy.ServiceOperations.Count > 0)
                        clientProxies.Add(clientProxy);
                }

                // MOD: 12-02-08 Added code to handle multiple type namespaces
                // Generate contract source file
                foreach (CodeNamespace codeNamespace in compileUnit.Namespaces)
                {
                    codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions);
                }
                dcStreamWriter.Flush();
                dcStreamWriter.Close();

                // Generate Hosted Service code
                Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal);
                HostedServiceGenerator hsGen = new HostedServiceGenerator();
                hsGen.GenerateCode(hostedServiceFilename, hostedServices);

                // Generate Client proxy code
                Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal);
                ClientProxyGenerator cpGen = new ClientProxyGenerator();
                cpGen.GenerateCode(clientProxyFilename, clientProxies);
            }
            catch (Exception e)
            {
                dcStreamWriter.Close();
                File.Delete(contractFilename);
                Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                throw new Exception("Failed to generate service code. ", e);
            }
        }
        protected void AutoGenButton_Click(object sender, EventArgs e)
        {
            if (TextBoxConfigLoginAddress.Text == null || TextBoxConfigLoginAddress.Text == "")
            {
                LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                LabelGetServices.Text = "Please enter an address to the remote Configuration Service.";
                return;
            }
            try
            {
                Uri testConfigUri = new Uri(TextBoxConfigLoginAddress.Text);
            }
            catch (Exception)
            {
                LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                LabelGetServices.Text = "Please enter a valid address.  The address you entered is not a valid URI; no connection was attempted.";
                return;
            }
            string addressSes = null;
            string IDSes = null;
            ServiceUsers csUserSes = null;
            string confignameSes = null;
            string hosterSes = null;
            string versionSes = null;
            string platformSes = null;
            string clientSession = null;
            string nameSes = null;
            SessionInfo info = new SessionInfo();
            info.getSessionData(false, out addressSes, out csUserSes, out clientSession, out nameSes, out confignameSes, out hosterSes, out versionSes, out platformSes, out IDSes);
            address = addressSes;
            string currentbinding = clientSession;
            user = csUserSes;
            if (address == null || user == null)
                Response.Redirect(FormsAuthentication.LoginUrl,true);
            traversePath = DynamicTraversePath.getTraversePath(hostNameIdentifier, configName, ref configProxy, address, currentbinding, user);
            DropDownListServiceName.Items.Clear();
            string addressConfig = TextBoxConfigLoginAddress.Text.Trim();
            ClientInformation theClient = clients.Find(delegate(ClientInformation ciExist) { return ciExist.ElementName.Equals(DropDownListConfigClient.SelectedValue); });
            BindingInformation binding = bindings.Find(delegate(BindingInformation bindingItem) { return bindingItem.BindingConfigurationName.Equals(theClient.BindingConfiguration); });
            string selectedBinding = theClient.ElementName;
            if (binding != null && binding.BindingType != null)
            {
                switch (binding.BindingType)
                {
                    case ConfigUtility.BASIC_HTTP_BINDING:
                        {
                            if (!addressConfig.ToLower().StartsWith("http"))
                            {

                                LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                                LabelGetServices.Text = "You have selected an <b>Http</b> binding: Please enter a valid http address.";
                                return;
                            }
                            break;
                        }
                    case ConfigUtility.WS_HTTP_BINDING:
                        {
                            goto case ConfigUtility.BASIC_HTTP_BINDING;
                        }

                    case ConfigUtility.WS_2007_HTTP_BINDING:
                        {
                            goto case ConfigUtility.BASIC_HTTP_BINDING;
                        }



                    case ConfigUtility.NET_TCP_BINDING:
                        {
                            if (!addressConfig.ToLower().StartsWith("net.tcp"))
                            {
                                LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                                LabelGetServices.Text = "You have selected a <b>Tcp</b> binding: Please enter a valid tcp address in form of net.tcp://";
                                return;
                            }
                            break;
                        }
                }
            }
            ServiceUsers configUser = new ServiceUsers();
            configUser = user;
            csusername= TextBoxConfigLoginUserId.Text.ToLower().Trim();
            cspassword = TextBoxConfigLoginPassword.Text.Trim();
            ServiceConfigurationClient newConfigProxy = null;
            try
            {
                newConfigProxy = new ServiceConfigurationClient(currentbinding, address, configUser);
                configServices = newConfigProxy.getMyConfigServiceDetails(hostNameIdentifier, configName, traversePath, addressConfig, selectedBinding,csusername,cspassword, configUser);
                if (configServices != null)
                {
                    if (configServices.Count == 0)
                    {
                        LabelGetServices.Text = "The remote host is currently not returning any Configuration Service Hosts to connect to.";
                        LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                        return;
                    }
                    LabelGetServices.Text = "<span style=\"font-size:1.2em;color:palegreen\">Connected!</span>";
                    ViewState["configServices"] = configServices;
                }
                else
                {
                    LabelGetServices.Text = "Service refused to supply information. Check userid/password and try again.";
                    LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                    return;
                }
                HostNameID.Text = configServices[0].HostNameIdentifier;
                TextBoxConfigLoginUserId.Text = configServices[0].InitialCSUserID;
                TextBoxConfigLoginPassword.Text = configServices[0].InitialCSPassword;
                TextBoxConfigLoginPassword.Attributes.Add("value", configServices[0].InitialCSPassword);
                string hsContractSelected = null;
                List<ConnectedServices> csList = compositeServiceData[0].ConnectedServices;
                for (int i = 0; i < configServices[0].PrimaryHostedServices.Count; i++)
                {
                    if (configServices[0].PrimaryHostedServices[i].ServiceType == ConfigUtility.HOST_TYPE_PRIMARY || configServices[0].PrimaryHostedServices[i].ServiceType == ConfigUtility.HOST_TYPE_GENERIC)
                    {
                        ConnectedServices csCheck = csList.Find(delegate(ConnectedServices csExist) { return csExist.ServiceFriendlyName.Equals(configServices[0].PrimaryHostedServices[i].FriendlyName); });
                        if (csCheck == null)
                        {
                            if (hsContractSelected == null)
                                hsContractSelected = configServices[0].PrimaryHostedServices[i].FriendlyName;
                            DropDownListServiceName.Items.Add(new ListItem(configServices[0].PrimaryHostedServices[i].FriendlyName, configServices[0].PrimaryHostedServices[i].FriendlyName));
                        }
                        else
                        {
                            UpdateMessage.Text = "There are services you already have established definitions for, and these have been removed from the available list!";
                            UpdateMessage.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFF99");
                        }
                    }
                }
                if (DropDownListServiceName.Items.Count > 0)
                {
                    DropDownListServiceName.SelectedIndex = 0;
                    string serviceName = DropDownListServiceName.SelectedValue;
                    hsSelected = configServices[0].PrimaryHostedServices.Find(delegate(HostedServices hsExist) { return hsExist.FriendlyName.Equals(DropDownListServiceName.Items[0].Text); });
                    TextBoxOnlineMethod.Text = hsSelected.OnlineMethod;
                    TextBoxOnlineParms.Text = hsSelected.OnlineParms;
                    DropDownListServiceName.SelectedValue = hsContractSelected;
                    DropDownListServiceName.Text = hsContractSelected;
                    DropDownListServiceName.Enabled = true;
                    Add.Enabled = true;
                    LabelContract.Text = hsSelected.ServiceContract;
                    LabelServiceFriendlyName.Text = hsSelected.FriendlyName;
                    try
                    {
                        DropDownListPrimaryContract.SelectedValue = hsSelected.ServiceContract;
                    }
                    catch { }
                    LabelSvcBindingType.Text = hsSelected.BindingType;
                    LabelPort.Text = hsSelected.Port;
                    LabelUseHttps.Text = hsSelected.UseHttps.ToString();
                    LabelVPath.Text = hsSelected.VirtualPath;
                    SecurityMode.Text = hsSelected.SecurityMode;
                    DropDownListPrimaryClients.Items.Clear();
                    string thisHssecurityMode = hsSelected.SecurityMode;
                    string thisHsBindingType = hsSelected.BindingType;
                    for (int i = 0; i < clients.Count; i++)
                    {
                        if (DropDownListPrimaryContract.SelectedValue.Equals(clients[i].Contract))
                        {
                            BindingInformation theClientBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(clients[i].BindingConfiguration); });
                            if (theClientBinding != null)
                            {
                                string tsSecMode = null;
                                if (thisService == null)
                                    tsSecMode = "unknown";
                                else
                                    tsSecMode = thisService.SecurityMode;
                                if (theClientBinding.BindingType.Equals(thisHsBindingType) || thisHsBindingType.ToLower().Contains("custom"))
                                {
                                    if (theClientBinding.SecurityMode.Equals(tsSecMode) || tsSecMode.Equals("unknown"))
                                    {
                                        if (!clients[i].ElementName.ToLower().Contains("host") && !clients[i].ElementName.ToLower().Contains("client_configsvc") && !clients[i].ElementName.ToLower().Contains("client_nodesvc"))
                                        {
                                            DropDownListPrimaryClients.Items.Add(new ListItem(clients[i].ElementName, clients[i].ElementName));
                                            DropDownListPrimaryClients.SelectedValue = clients[i].ElementName;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    theClient = clients.Find(delegate(ClientInformation ciExist) { return ciExist.ElementName.Equals(DropDownListPrimaryClients.SelectedValue); });
                    if (theClient != null)
                    {
                        BindingInformation theSelectedBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(theClient.BindingConfiguration); });
                        if (theSelectedBinding != null)
                        {
                            LabelBindingTypePrimary.Text = theSelectedBinding.BindingType;
                        }
                        LabelIntroService.Text = "<div style=\"font-size:.9em;color:#FFFF99;padding-bottom:10px\">These are the available service endpoints by friendly names as assigned by the Service Hoster. Each has its own binding requirements " +
                            "(network scheme, security, encoding, etc.). Please select the desired service from this list. Client configurations and bindings can be generated by svcutil.exe, " + 
                            "named to Configuration Service standards, and inserted into this application's configuration file to appear in this page as selectable. You will also need to supply the service contract " +
                            "your client uses in your startup call per the StockTrader example and the documentation.<br/>";
                        Add.Enabled = true;
                    }
                    else
                    {
                        LabelIntroService.Text = "Please change the selected Primary Hosted Service, or the Client Contract.  The current combination yields no valid client configuration to connect with. The check was performed against binding type, and security mode. You may need to add and appropriate client definition to your config file.";
                        Add.Enabled = false;
                        LabelIntroService.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFF99");
                    }
                }
                else
                {
                    DropDownListServiceName.Enabled = false;
                    Add.Enabled = false;
                    LabelIntroService.Text = "Either this host does not expose services via the Config Service (try as a Generic Service); or you already have established definitions for all available services this virtual host exposes.";
                    LabelIntroService.ForeColor = System.Drawing.Color.Maroon;
                }
                LabelIntroPrimary.Text = "Please Select the Primary Service";
            }
            catch (Exception eConfig)
            {
                LabelGetServices.ForeColor = System.Drawing.Color.Maroon;
                LabelGetServices.Text = "Cannot Connect!<br/><br/>Please make sure the address to the remote configuration service endpoint is correct and you have chosen the appropriate client configuration/binding.  For example" +
                    " if specifying https, you must choose a client configuration using https/transport security.<br/>" +
                    "Full connect exception is: <br/>" + ConfigUtility.reMapExceptionForDisplay(eConfig.ToString());
                if (eConfig.InnerException != null)
                    LabelGetServices.Text = LabelGetServices.Text + "<br/> Inner Exception is:<br/>" + eConfig.InnerException.ToString();
                return;
            }
            generateClicked = "true";
            ViewState["generateClicked"] = generateClicked;
            ConnectedPanel.Visible = true;
            panelConnectedService1.Visible = true;
            panelConnectedService2.Visible = false;
        }
        protected void DropDownListServiceName_SelectedIndexChanged(object sender, EventArgs e)
        {
            configServices = (List<ConnectedConfigServices>)ViewState["configServices"];
            thisServiceConfig = (ConnectedConfigServices)ViewState["thisServiceConfig"];
            bindings = compositeServiceData[0].BindingInformation;
            List<ClientInformation> clients = new List<ClientInformation>();
            clients.AddRange(compositeServiceData[0].ClientInformation);
            DropDownListPrimaryClients.Items.Clear();
            switch (action)
            {
                case ConfigUtility.ADD_CONNECTED_SERVICE:
                    {
                        HostedServices thisHS = configServices[0].PrimaryHostedServices.Find(delegate(HostedServices hsExists) { return hsExists.FriendlyName.Equals(DropDownListServiceName.SelectedValue); });
                        clients.RemoveAll(delegate(ClientInformation clientExist) { return !clientExist.Contract.Equals(thisHS.ServiceContract); });
                        LabelContract.Text = thisHS.ServiceContract;
                        LabelServiceFriendlyName.Text = thisHS.FriendlyName;
                        LabelSvcBindingType.Text = thisHS.BindingType;
                        LabelPort.Text = thisHS.Port;
                        LabelUseHttps.Text = thisHS.UseHttps.ToString();
                        LabelVPath.Text = thisHS.VirtualPath;
                        SecurityMode.Text = thisHS.SecurityMode;
                        TextBoxOnlineMethod.Text = thisHS.OnlineMethod;
                        TextBoxOnlineParms.Text = thisHS.OnlineParms;
                        string svcName = DropDownListServiceName.SelectedValue;
                        hsSelected = configServices[0].PrimaryHostedServices.Find(delegate(HostedServices hsExist) { return hsExist.FriendlyName.Equals(svcName); });
                        string thisHssecurityMode = hsSelected.SecurityMode;
                        string thisHsBindingType = hsSelected.BindingType;
                        for (int i = 0; i < clients.Count; i++)
                        {
                            if (DropDownListPrimaryContract.SelectedValue.Equals(clients[i].Contract))
                            {
                                BindingInformation theClientBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(clients[i].BindingConfiguration); });
                                if (theClientBinding != null)
                                {
                                    string tsSecMode = null;
                                    if (thisService == null)
                                        tsSecMode = "unknown";
                                    else
                                        tsSecMode = thisService.SecurityMode;
                                    if (theClientBinding.BindingType.Equals(thisHsBindingType) || thisHsBindingType.ToLower().Contains("custom"))
                                    {
                                        if (theClientBinding.SecurityMode.Equals(tsSecMode) || tsSecMode.Equals("unknown"))
                                        {
                                            if (!clients[i].ElementName.ToLower().Contains("host") && !clients[i].ElementName.ToLower().Contains("client_configsvc") && !clients[i].ElementName.ToLower().Contains("client_nodesvc"))
                                            {
                                                DropDownListPrimaryClients.Items.Add(new ListItem(clients[i].ElementName, clients[i].ElementName));
                                                DropDownListPrimaryClients.SelectedValue = clients[i].ElementName;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                case ConfigUtility.UPDATE_CONNECTED_SERVICE:
                    {
                        clients.RemoveAll(delegate(ClientInformation clientExist) { return !clientExist.Contract.Equals(thisService.ServiceContract); });
                        LabelContract.Text = thisService.ServiceContract;
                        LabelServiceFriendlyName.Text = thisService.ServiceFriendlyName;
                        LabelSvcBindingType.Text = thisService.BindingType;
                        LabelUseHttps.Text = thisService.UseHttps.ToString();
                        SecurityMode.Text = thisService.SecurityMode;
                        TextBoxOnlineMethod.Text = thisService.OnlineMethod;
                        TextBoxOnlineParms.Text = thisService.OnlineParms;
                        string svcName = DropDownListServiceName.SelectedValue;
                        string thisCssecurityMode = thisService.SecurityMode;
                        string thisCsBindingType = thisService.BindingType;
                        for (int i = 0; i < clients.Count; i++)
                        {
                            if (DropDownListPrimaryContract.SelectedValue.Equals(clients[i].Contract))
                            {
                                BindingInformation theClientBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(clients[i].BindingConfiguration); });
                                if (theClientBinding != null)
                                {
                                    string tsSecMode = null;
                                    if (thisService == null)
                                        tsSecMode = "unknown";
                                    else
                                        tsSecMode = thisService.SecurityMode;
                                    if (theClientBinding.BindingType.Equals(thisCsBindingType) || thisCsBindingType.ToLower().Contains("custom"))
                                    {
                                        if (theClientBinding.SecurityMode.Equals(tsSecMode) || tsSecMode.Equals("unknown"))
                                        {
                                            if (!clients[i].ElementName.ToLower().Contains("host") && !clients[i].ElementName.ToLower().Contains("client_configsvc") && !clients[i].ElementName.ToLower().Contains("client_nodesvc"))
                                            {
                                                DropDownListPrimaryClients.Items.Add(new ListItem(clients[i].ElementName, clients[i].ElementName));
                                                DropDownListPrimaryClients.SelectedValue = clients[i].ElementName;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
            }
            if (DropDownListPrimaryClients.Items.Count > 0)
            {
                string configName = DropDownListPrimaryClients.SelectedValue;
                ClientInformation theClient = clients.Find(delegate(ClientInformation ciExist) { return ciExist.ElementName.Equals(configName); });
                if (theClient != null)
                {
                    string theBindingName = theClient.BindingConfiguration;
                    BindingInformation theSelectedBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(theClient.BindingConfiguration); });
                    if (theSelectedBinding != null)
                        LabelBindingTypePrimary.Text = theSelectedBinding.BindingType;
                }
                Add.Enabled = true;
            }
            else
            {
                Add.Enabled = false;
                LabelIntroService.Text = LabelIntroService.Text = "Please change the selected Primary Hosted Service, or the Client Contract.  The current combination yields no valid client configuration to connect with. The check was performed against binding type, and security mode. You may need to add and appropriate client definition to your config file.";
                LabelBindingTypePrimary.Text = "";
            }

        }
 protected void DropDownListPrimaryContract_SelectedIndexChanged(object sender, EventArgs e)
 {
     thisService = (ConnectedServices)ViewState["thisService"];
     configServices = (List<ConnectedConfigServices>)ViewState["configServices"];
     string svcName = DropDownListServiceName.SelectedValue;
     switch (action)
     {
         case ConfigUtility.ADD_CONNECTED_SERVICE:
             {
                 hsSelected = configServices[0].PrimaryHostedServices.Find(delegate(HostedServices hsExist) { return hsExist.FriendlyName.Equals(svcName); });
                 DropDownListPrimaryClients.Items.Clear();
                 if (hsSelected != null)
                 {
                     string thisHssecurityMode = hsSelected.SecurityMode;
                     string thisHsBindingType = hsSelected.BindingType;
                     for (int i = 0; i < clients.Count; i++)
                     {
                         if (DropDownListPrimaryContract.SelectedValue.Equals(clients[i].Contract))
                         {
                             BindingInformation theClientBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(clients[i].BindingConfiguration); });
                             if (theClientBinding != null)
                             {
                                 string tsSecMode = null;
                                 if (thisService == null)
                                     tsSecMode = "unknown";
                                 else
                                     tsSecMode = thisService.SecurityMode;
                                 if (theClientBinding.BindingType.Equals(thisHsBindingType) || thisHsBindingType.ToLower().Contains("custom"))
                                 {
                                     if (theClientBinding.SecurityMode.Equals(tsSecMode) || tsSecMode.Equals("unknown"))
                                     {
                                         if (!clients[i].ElementName.ToLower().Contains("host") && !clients[i].ElementName.ToLower().Contains("client_configsvc") && !clients[i].ElementName.ToLower().Contains("client_nodesvc"))
                                         {
                                             DropDownListPrimaryClients.Items.Add(new ListItem(clients[i].ElementName, clients[i].ElementName));
                                             DropDownListPrimaryClients.SelectedValue = clients[i].ElementName;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 break;
             }
         case ConfigUtility.UPDATE_CONNECTED_SERVICE:
             {
                     DropDownListPrimaryClients.Items.Clear();
                     string thisCssecurityMode = thisService.SecurityMode;
                     string thisCsBindingType = thisService.BindingType;
                     for (int i = 0; i < clients.Count; i++)
                     {
                         if (DropDownListPrimaryContract.SelectedValue.Equals(clients[i].Contract))
                         {
                             BindingInformation theClientBinding = bindings.Find(delegate(BindingInformation biExist) { return biExist.BindingConfigurationName.Equals(clients[i].BindingConfiguration); });
                             if (theClientBinding != null)
                             {
                                 string tsSecMode = null;
                                 if (thisService == null)
                                     tsSecMode = "unknown";
                                 else
                                     tsSecMode = thisService.SecurityMode;
                                 if (theClientBinding.BindingType.Equals(thisCsBindingType) || thisCsBindingType.ToLower().Contains("custom"))
                                 {
                                     if (theClientBinding.SecurityMode.Equals(tsSecMode) || tsSecMode.Equals("unknown"))
                                     {
                                         if (!clients[i].ElementName.ToLower().Contains("host") && !clients[i].ElementName.ToLower().Contains("client_configsvc") && !clients[i].ElementName.ToLower().Contains("client_nodesvc"))
                                         {
                                             DropDownListPrimaryClients.Items.Add(new ListItem(clients[i].ElementName, clients[i].ElementName));
                                             DropDownListPrimaryClients.SelectedValue = clients[i].ElementName;
                                         }
                                     }
                                 }
                             }
                         }
                     }
             }
             break;
     }
     if (DropDownListPrimaryClients.Items.Count == 0)
         LabelIntroService.Text = LabelIntroService.Text = "Please change the selected Primary Hosted Service, or the Client Contract.  The current combination yields no valid client configuration to connect with. The check was performed against binding type, and security mode. You may need to add and appropriate client definition to your config file.";
                     
 }