Example #1
0
        public unsafe void X509CredentialsRoundTripTest2()
        {
            var x509Credentials = new X509Credentials
            {
                IssuerThumbprints = { "ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff" },
                FindType          = X509FindType.FindByThumbprint,
                FindValue         = "ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff",
            };

            var pinCollection = new PinCollection();
            NativeX509CredentialConverter converter = new NativeX509CredentialConverter(x509Credentials);
            var nativeIntPtr = converter.ToNative(pinCollection);

            Assert.AreNotEqual(nativeIntPtr, IntPtr.Zero);

            var fromNative = X509Credentials.CreateFromNative((NativeTypes.FABRIC_X509_CREDENTIALS *)nativeIntPtr);

            Assert.AreEqual(x509Credentials.ProtectionLevel, fromNative.ProtectionLevel);
            Assert.AreEqual(x509Credentials.StoreName, fromNative.StoreName);
            Assert.AreEqual(x509Credentials.StoreLocation, fromNative.StoreLocation);
            Assert.AreEqual(x509Credentials.FindType, fromNative.FindType);
            Assert.AreEqual(x509Credentials.FindValue, fromNative.FindValue);
            Assert.AreEqual(x509Credentials.FindValueSecondary, fromNative.FindValueSecondary);
            Assert.IsTrue(x509Credentials.RemoteCommonNames.SequenceEqual(fromNative.RemoteCommonNames));
            Assert.IsTrue(x509Credentials.IssuerThumbprints.SequenceEqual(fromNative.IssuerThumbprints));
            Assert.IsTrue(x509Credentials.RemoteCertThumbprints.SequenceEqual(fromNative.RemoteCertThumbprints));
            Assert.IsTrue(x509Credentials.RemoteX509Names.SequenceEqual(fromNative.RemoteX509Names));
            Assert.IsTrue(x509Credentials.RemoteCertIssuers.SequenceEqual(fromNative.RemoteCertIssuers));
        }
Example #2
0
        private IImageStore CreateImageStore(string connectionEndpoint, string imageStoreConnectionString, string workingDirectory, string certThumbprint)
        {
            if (!imageStoreConnectionString.StartsWith("file:", StringComparison.OrdinalIgnoreCase) &&
                !imageStoreConnectionString.StartsWith("fabric:", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException();
            }

            string[]        connectionEndpoints = { connectionEndpoint };
            X509Credentials securityCredentials = null;

            if (certThumbprint != null && certThumbprint.Length > 0)
            {
                securityCredentials = new X509Credentials();
                securityCredentials.RemoteCertThumbprints.Add(certThumbprint);
                securityCredentials.FindType      = X509FindType.FindByThumbprint;
                securityCredentials.FindValue     = certThumbprint;
                securityCredentials.StoreLocation = StoreLocation.CurrentUser;
                securityCredentials.StoreName     = "MyStore";
            }

            IImageStore imageStore = ImageStoreFactoryProxy.CreateImageStore(
                imageStoreConnectionString,
                null,
                connectionEndpoints,
                securityCredentials,
                workingDirectory,
                false);

            return(imageStore);
        }
Example #3
0
        public unsafe void X509CredentialsRoundTripTest11()
        {
            var x509Credentials = new X509Credentials
            {
                FindType        = X509FindType.FindByThumbprint,
                FindValue       = "78 12 20 5a 39 d2 23 76 da a0 37 f0 5a ed e3 60 1a 7e 64 bf",
                ProtectionLevel = ProtectionLevel.Sign
            };

            x509Credentials.RemoteX509Names.Add(new X509Name("name1", "1f ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff"));
            x509Credentials.RemoteX509Names.Add(new X509Name("name1", "2f ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff"));
            x509Credentials.RemoteX509Names.Add(new X509Name("name2", "3f ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff"));
            x509Credentials.RemoteX509Names.Add(new X509Name("name3", null));

            var pinCollection = new PinCollection();
            NativeX509CredentialConverter converter = new NativeX509CredentialConverter(x509Credentials);
            var nativeIntPtr = converter.ToNative(pinCollection);

            Assert.AreNotEqual(nativeIntPtr, IntPtr.Zero);

            var fromNative = X509Credentials.CreateFromNative((NativeTypes.FABRIC_X509_CREDENTIALS *)nativeIntPtr);

            Assert.AreEqual(x509Credentials.ProtectionLevel, fromNative.ProtectionLevel);
            Assert.AreEqual(x509Credentials.StoreName, fromNative.StoreName);
            Assert.AreEqual(x509Credentials.StoreLocation, fromNative.StoreLocation);
            Assert.AreEqual(x509Credentials.FindType, fromNative.FindType);
            Assert.AreEqual(x509Credentials.FindValue, fromNative.FindValue);
            Assert.AreEqual(x509Credentials.FindValueSecondary, fromNative.FindValueSecondary);
            Assert.IsTrue(x509Credentials.RemoteCommonNames.SequenceEqual(fromNative.RemoteCommonNames));
            Assert.IsTrue(x509Credentials.IssuerThumbprints.SequenceEqual(fromNative.IssuerThumbprints));
            Assert.IsTrue(x509Credentials.RemoteCertThumbprints.SequenceEqual(fromNative.RemoteCertThumbprints));
            Assert.IsTrue(x509Credentials.RemoteX509Names.SequenceEqual(fromNative.RemoteX509Names));
            Assert.IsTrue(x509Credentials.RemoteCertIssuers.SequenceEqual(fromNative.RemoteCertIssuers));
        }
Example #4
0
        private SecurityCredentials X509SecurityCredentialsBuilder()
        {
            var x509SecurityCredential = new X509Credentials();

            x509SecurityCredential.FindType = this.ConfigSection.GetSetting <X509FindType>(CertificateFindType,
                                                                                           x509SecurityCredential.FindType);
            x509SecurityCredential.ProtectionLevel = this.ConfigSection.GetSetting <ProtectionLevel>(
                CertificateProtectionLevel,
                x509SecurityCredential.ProtectionLevel);
            x509SecurityCredential.FindValue = this.ConfigSection.GetSetting <object>(CertificateFindValue,
                                                                                      x509SecurityCredential.FindValue);

            x509SecurityCredential.StoreLocation =
                this.ConfigSection.GetSetting <StoreLocation>(CertificateStoreLocation,
                                                              x509SecurityCredential.StoreLocation);

            x509SecurityCredential.StoreName = this.ConfigSection.GetSetting <string>(CertificateStoreName,
                                                                                      x509SecurityCredential.StoreName);
            var remoteCommonNames = this.ConfigSection.GetSettingsList <string>(CertificateRemoteCommonNames);

            foreach (var name in remoteCommonNames)
            {
                x509SecurityCredential.RemoteCommonNames.Add(name);
            }

            var remoteCertThumbPrints = this.ConfigSection.GetSettingsList <string>(CertificateRemoteThumbprints);

            foreach (var name in remoteCertThumbPrints)
            {
                x509SecurityCredential.RemoteCertThumbprints.Add(name);
            }

            var issuerCertThumbPrints = this.ConfigSection.GetSettingsList <string>(CertificateIssuerThumbprints);

            foreach (var name in issuerCertThumbPrints)
            {
                x509SecurityCredential.IssuerThumbprints.Add(name);
            }

            x509SecurityCredential.FindValueSecondary =
                this.ConfigSection.GetSetting <object>(CertificateFindValuebySecondary,
                                                       x509SecurityCredential.FindValueSecondary);

            var issuerCertStores  = this.ConfigSection.GetSettingsMapFromPrefix(CertificateApplicationIssuerStorePrefix);
            var remoteCertIssuers = new List <X509IssuerStore>();

            foreach (var issuerCertStore in issuerCertStores)
            {
                var issuerStoreLocations = issuerCertStore.Value.Split(',').ToList();
                remoteCertIssuers.Add(new X509IssuerStore(issuerCertStore.Key, issuerStoreLocations));
            }
            if (remoteCertIssuers.Count != 0)
            {
                x509SecurityCredential.RemoteCertIssuers = remoteCertIssuers;
            }

            return(x509SecurityCredential);
        }
        private static async Task RunAsync(string[] args, CancellationToken token)
        {
            var options = ConsoleHelper.ParseAndHandleArguments <ProgramOptions>("Create or updating messagecluster", args);


            X509Credentials cert = new X509Credentials
            {
                FindType        = X509FindType.FindByThumbprint,
                FindValue       = options.Thumbprint,
                ProtectionLevel = ProtectionLevel.EncryptAndSign,
                StoreLocation   = StoreLocation.CurrentUser,
                StoreName       = "My",
            };

            cert.RemoteCertThumbprints.Add(options.Thumbprint);


            var fabricClient = new FabricClient(cert,
                                                new FabricClientSettings
            {
                ClientFriendlyName = "S-Innovations VSTS Deployment Client"
            }, options.Gateway);

            var applicationType = await ProvisionApplicationTypeAsync(options, fabricClient);

            var applicationName = new Uri(options.ApplicatioName.StartsWith("fabric:/") ? options.ApplicatioName : $"fabric:/{options.ApplicatioName}");



            var application = new ApplicationDescription
            {
                ApplicationName        = applicationName,
                ApplicationTypeName    = applicationType.ApplicationTypeName,
                ApplicationTypeVersion = applicationType.ApplicationTypeVersion
            };

            application.ApplicationParameters.Add("SubscriptionId", options.ConnectedServiceName.SubscriptionId);
            application.ApplicationParameters.Add("ResourceGroupName", options.ResourceGroupName);
            application.ApplicationParameters.Add("ClusterName", options.ClusterName);
            application.ApplicationParameters.Add("TenantId", options.ConnectedServiceName.TenantId);
            application.ApplicationParameters.Add("StorageName", options.StorageName);
            application.ApplicationParameters.Add("BasicAuth", options.BasicAuth);
            application.ApplicationParameters.Add("AzureADServicePrincipal", options.AzureADServicePrincipal);
            application.ApplicationParameters.Add("PlacementConstraints", options.PlacementConstraints);


            var applications = await fabricClient.QueryManager.GetApplicationListAsync(application.ApplicationName);

            if (!applications.Any(a => a.ApplicationTypeName == application.ApplicationTypeName && a.ApplicationTypeVersion == application.ApplicationTypeVersion))
            {
                await fabricClient.ApplicationManager.CreateApplicationAsync(application);
            }
        }
Example #6
0
        static X509Credentials GetCredentials(string clientCertThumb, string serverCertThumb, string name)
        {
            X509Credentials xc = new X509Credentials();

            xc.StoreLocation = StoreLocation.CurrentUser;
            xc.StoreName     = "My";
            xc.FindType      = X509FindType.FindByThumbprint;
            xc.FindValue     = clientCertThumb;
            xc.RemoteCommonNames.Add(name);
            xc.RemoteCertThumbprints.Add(serverCertThumb);
            xc.ProtectionLevel = System.Fabric.ProtectionLevel.EncryptAndSign;
            return(xc);
        }
Example #7
0
        // Create Listener with 'NO' Transport Settings
        //protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        //{
        //    return new ServiceInstanceListener[]
        //    {
        //        new ServiceInstanceListener(serviceContext => this.CreateServiceRemotingListener(serviceContext))
        //    };
        //}

        private static SecurityCredentials GetSecurityCredentials()
        {
            var x509Credentials = new X509Credentials
            {
                FindType        = X509FindType.FindByThumbprint,
                FindValue       = "053a87f6c1e3d08ec7fc28522a2cf1921c9daa5e",
                StoreLocation   = StoreLocation.LocalMachine,
                StoreName       = "My",
                ProtectionLevel = ProtectionLevel.EncryptAndSign
            };

            x509Credentials.RemoteCommonNames.Add("jacksch.westus.cloudapp.azure.com");
            return(x509Credentials);
        }
Example #8
0
        static X509Credentials GetCredentials(string clientCertThumbprint, string clientCertStoreLocation, string clientCertStoreName, string serverCertThumb, string commonName)
        {
            var xc = new X509Credentials
            {
                StoreLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), clientCertStoreLocation),
                StoreName     = clientCertStoreName,
                FindType      = X509FindType.FindByThumbprint,
                FindValue     = clientCertThumbprint
            };

            xc.RemoteCommonNames.Add(commonName);
            xc.RemoteCertThumbprints.Add(serverCertThumb);
            xc.ProtectionLevel = ProtectionLevel.EncryptAndSign;
            return(xc);
        }
        private static SecurityCredentials GetSecurityCredentials()
        {
            // Provide certificate details.
            var x509Credentials = new X509Credentials
            {
                FindType        = X509FindType.FindByThumbprint,
                FindValue       = "fb1a3dfbb66074311a70c5c461b4c807f29f3e2a",
                StoreLocation   = StoreLocation.LocalMachine,
                StoreName       = "My",
                ProtectionLevel = ProtectionLevel.EncryptAndSign
            };

            x509Credentials.RemoteCommonNames.Add("ServiceFabric-Test-Cert");
            x509Credentials.RemoteCertThumbprints.Add("fb1a3dfbb66074311a70c5c461b4c807f29f3e2a");
            return(x509Credentials);
        }
Example #10
0
        public void FillTable(string pathToSettings)
        {
            Clusters = new List <ClusterInfo>();
            string json;

            using (var r = new StreamReader(pathToSettings))
            {
                json = r.ReadToEnd();
                r.Close();
            }

            var dataSet   = JsonConvert.DeserializeObject <DataSet>(json);
            var dataTable = dataSet.Tables["Clusters"];

            foreach (DataRow row in dataTable.Rows)
            {
                var sc = new X509Credentials
                {
                    FindType      = X509FindType.FindByThumbprint,
                    StoreLocation = StoreLocation.LocalMachine,
                    StoreName     = "My",
                    FindValue     = row["clientCertThumb"]
                };
                sc.RemoteCertThumbprints.Add(row["serverCertThumb"].ToString());

                var item = new ClusterInfo(row["name"].ToString())
                {
                    ConnectionEndpoint = row["ConnectionEndpoint"].ToString()
                };

                try
                {
                    using (var fc = new FabricClient(sc, item.ConnectionEndpoint))
                    {
                        var clusterCodeVersion = fc.ClusterManager
                                                 .GetFabricUpgradeProgressAsync(TimeSpan.FromSeconds(5), CancellationToken.None).Result;
                        item.CodeVersion = clusterCodeVersion.TargetCodeVersion;
                    }
                }
                catch (Exception e)
                {
                    item.CodeVersion = "Connection timeout.";
                }

                Clusters.Add(item);
            }
        }
Example #11
0
        static FabricClient CreateFabricClient()
        {
            string thumb           = clientThumbCert;
            string serverCertThumb = clientThumbCert;
            string CommonName      = certCommonName;
            string connection      = "localhost:19000";

            if (string.IsNullOrEmpty(thumb))
            {
                return(new FabricClient(FabricClientRole.User));
            }
            else
            {
                X509Credentials xc = GetCredentials(thumb, serverCertThumb, CommonName);
                return(new FabricClient(xc, connection));
            }
        }
Example #12
0
        private static void RunOnIIS(IUnityContainer container)
        {
            X509Credentials cert = new X509Credentials
            {
                FindType        = X509FindType.FindByThumbprint,
                FindValue       = "7B58E936E077ADCFD8ABD278C4BD895D652411CD",
                ProtectionLevel = ProtectionLevel.EncryptAndSign,
                StoreLocation   = StoreLocation.CurrentUser,
                StoreName       = "My",
            };

            cert.RemoteCertThumbprints.Add("7B58E936E077ADCFD8ABD278C4BD895D652411CD");


            var fabricClient = new FabricClient(cert,
                                                new FabricClientSettings
            {
                ClientFriendlyName = "S-Innovations VSTS Deployment Client"
            }, "sf-gateway-test.westeurope.cloudapp.azure.com:19000");

            container.RegisterInstance(fabricClient);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseWebRoot("artifacts")
                       .ConfigureLogging(logbuilder =>
            {
                logbuilder.AddSerilog();
            })
                       .UseIISIntegration()
                       .UseStartup <Startup>()
                       .UseApplicationInsights()
                       .UseUnityServiceProvider(container)
                       .ConfigureServices((ctx, collection) => { collection.AddSingleton(container); })
                       .Build();

            host.Run();
        }
        public static SecurityCredentials GetSecurityCredentials(string thumbprint, IEnumerable <string> remoteThumbprint, IEnumerable <string> remoteCommonName)
        {
            // Provide certificate details.
            var x509Credentials = new X509Credentials
            {
                FindType        = X509FindType.FindByThumbprint,
                FindValue       = thumbprint,
                StoreLocation   = StoreLocation.LocalMachine,
                StoreName       = "My",
                ProtectionLevel = ProtectionLevel.EncryptAndSign
            };

            foreach (var cn in remoteThumbprint ?? new string[0])
            {
                x509Credentials.RemoteCommonNames.Add(cn);
            }
            foreach (var thumb in remoteThumbprint ?? new string[0])
            {
                x509Credentials.RemoteCertThumbprints.Add(thumb);
            }
            return(x509Credentials);
        }
        static SF_Services()
        {
            try
            {
                partitions_ = null;

                if (EnvoyDefaults.client_cert_subject_name != null)
                {
                    X509Credentials creds = new X509Credentials();
                    creds.FindType  = X509FindType.FindBySubjectName;
                    creds.FindValue = EnvoyDefaults.client_cert_subject_name;
                    if (EnvoyDefaults.client_cert_issuer_thumbprints != null)
                    {
                        foreach (var issuer in EnvoyDefaults.client_cert_issuer_thumbprints)
                        {
                            creds.IssuerThumbprints.Add(issuer);
                        }
                    }
                    if (EnvoyDefaults.server_cert_common_names != null)
                    {
                        foreach (var commonName in EnvoyDefaults.server_cert_common_names)
                        {
                            creds.RemoteCommonNames.Add(commonName);
                        }
                    }
                    else
                    {
                        creds.RemoteCommonNames.Add(EnvoyDefaults.client_cert_subject_name);
                    }
                    if (EnvoyDefaults.server_cert_issuer_thumbprints != null)
                    {
                        foreach (var issuer in EnvoyDefaults.server_cert_issuer_thumbprints)
                        {
                            creds.RemoteCertThumbprints.Add(issuer);
                        }
                    }
                    else if (EnvoyDefaults.client_cert_issuer_thumbprints != null)
                    {
                        foreach (var issuer in EnvoyDefaults.client_cert_issuer_thumbprints)
                        {
                            creds.RemoteCertThumbprints.Add(issuer);
                        }
                    }
                    creds.StoreLocation = StoreLocation.LocalMachine;
                    creds.StoreName     = "/app/sfcerts";

                    client = new FabricClient(creds, EnvoyDefaults.fabricUri);
                }
                else
                {
                    client = new FabricClient(EnvoyDefaults.fabricUri);
                }
                EnvoyDefaults.LogMessage("Client sucessfully created");

                EnableResolveNotifications.RegisterNotificationFilter("fabric:", client, Handler);
                EnvoyDefaults.LogMessage("Notification handler sucessfully set");
            }
            catch (Exception e)
            {
                EnvoyDefaults.LogMessage(String.Format("Error={0}", e));
            }
        }
Example #15
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Enter IoT Hub Connection String: ");
            connectionString = Console.ReadLine();

            Console.WriteLine("Enter Service Fabric cluster Address Where your IoT Solution is Deployed (or blank for local): ");
            clusterAddress = Console.ReadLine();

            registryManager = RegistryManager.CreateFromConnectionString(connectionString);


            // let's deal with collecting credentials information for the cluster connection
            if (!String.IsNullOrEmpty(clusterAddress))
            {
                Console.WriteLine("Enter Credential Type [none, x509, Windows] (or blank for unsecured Service Fabric): ");
                credentialType = Console.ReadLine();

                Console.WriteLine("Enter Server Certificate Thumbprint  (or blank for not working with server certificate): ");
                serverCertThumbprint = Console.ReadLine();

                if (!String.IsNullOrEmpty(credentialType) || !String.Equals(credentialType, "none"))
                {
                    Console.WriteLine("Enter Credential Find Type [FindByThumbprint, ... ] (or blank for not working with find type): ");
                    findType = Console.ReadLine();
                }

                if (!String.IsNullOrEmpty(findType))
                {
                    Console.WriteLine("Enter Credential Find Value: ");
                    findValue = Console.ReadLine();

                    Console.WriteLine("Enter Credential Find Location: ");
                    storeLocation = Console.ReadLine();

                    Console.WriteLine("Enter Credential Find Location Name: ");
                    storeName = Console.ReadLine();
                }
            }

            if (!String.IsNullOrEmpty(findType))
            {
                credential = new X509Credentials();

                credential.RemoteCertThumbprints.Add(serverCertThumbprint);

                if (String.Equals(storeLocation.ToUpper(), "CURRENTUSER"))
                {
                    credential.StoreLocation = System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser;
                }
                else
                {
                    credential.StoreLocation = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine;
                }

                credential.StoreName = storeName;
                credential.FindValue = findValue;

                if (String.Equals(findType.ToUpper(), "FINDBYTHUMBPRINT"))
                {
                    credential.FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint;
                }
                else
                {
                    Console.WriteLine("X509 Find Type Not Supported [{0}]", findType);
                }
            }

            fabricClient = String.IsNullOrEmpty(clusterAddress)
            ? new FabricClient()
            : credential == null ? new FabricClient(clusterAddress) : new FabricClient(credential, clusterAddress);

            Task.Run(
                async() =>
            {
                while (true)
                {
                    try
                    {
                        devices     = await registryManager.GetDevicesAsync(Int32.MaxValue);
                        targetSites = (await fabricClient.QueryManager.GetApplicationListAsync())
                                      .Where(x => x.ApplicationTypeName == Names.InsightApplicationTypeName)
                                      .Select(x => x.ApplicationName.ToString().Replace(Names.InsightApplicationNamePrefix + "/", ""));

                        Console.WriteLine();
                        Console.WriteLine("Devices IDs: ");
                        foreach (Device device in devices)
                        {
                            Console.WriteLine(device.Id);
                        }

                        Console.WriteLine();
                        Console.WriteLine("Insight Application URI: ");
                        foreach (string targetSiteName in targetSites)
                        {
                            Console.WriteLine(targetSiteName);
                        }

                        Console.WriteLine();
                        Console.WriteLine("Commands:");
                        Console.WriteLine("1: Register a device");
                        Console.WriteLine("2: Register random devices");
                        Console.WriteLine("3: Send data from a device");
                        Console.WriteLine("4: Send data from all devices");
                        Console.WriteLine("5: Send data from a CSV File from a device ");
                        Console.WriteLine("6: Send data from a CSV File");
                        Console.WriteLine("7: Send data from a JSON File");
                        Console.WriteLine("8: Exit");

                        string command              = Console.ReadLine();
                        string deviceId             = "";
                        string targetSite           = "";
                        string fileDataPath         = "";
                        string fieldDefinitionsPath = "";
                        string messageContent       = "";

                        switch (command)
                        {
                        case "1":
                            Console.WriteLine("Make up a Device ID: ");
                            deviceId = Console.ReadLine();
                            await AddDeviceAsync(deviceId);
                            break;

                        case "2":
                            Console.WriteLine("How many devices? ");
                            int num = Int32.Parse(Console.ReadLine());
                            await AddRandomDevicesAsync(num);
                            break;

                        case "3":
                            Console.WriteLine("Target Application URI: ");
                            targetSite = Console.ReadLine();
                            Console.WriteLine("Device ID: ");
                            deviceId = Console.ReadLine();
                            Console.WriteLine("Message Content or ENTER to create dummy messages:");
                            messageContent = Console.ReadLine();
                            await SendDeviceToCloudMessagesAsync(deviceId, targetSite, messageContent);
                            break;

                        case "4":
                            Console.WriteLine("Target Site Application URI: ");
                            targetSite = Console.ReadLine();
                            Console.WriteLine("Iterations: ");
                            int iterations = Int32.Parse(Console.ReadLine());
                            await SendAllDevices(targetSite, iterations);
                            break;

                        case "5":
                            Console.WriteLine("Target Site Application URI: ");
                            targetSite = Console.ReadLine();
                            Console.WriteLine("Device ID: ");
                            deviceId = Console.ReadLine();
                            Console.WriteLine("CSV File Path ([data only] or [data + fieldefinitions]): ");
                            fileDataPath = Console.ReadLine();
                            Console.WriteLine("CSV File Path ([fieldefinitions] or ENTER in case of [data + fieldefinitions]): ");
                            fieldDefinitionsPath = Console.ReadLine();

                            if (fileDataPath.Length > 0)
                            {
                                await SendEventsFromCSVFile(deviceId, targetSite, fileDataPath, fieldDefinitionsPath);
                            }
                            else
                            {
                                Console.WriteLine("No valid path provided for CSV data file");
                            }
                            break;

                        case "6":
                            Console.WriteLine("CSV File Path ([data only] or [data + fieldefinitions]): ");
                            fileDataPath = Console.ReadLine();
                            Console.WriteLine("CSV File Path ([fieldefinitions] or ENTER in case of [data + fieldefinitions]): ");
                            fieldDefinitionsPath = Console.ReadLine();

                            if (fileDataPath.Length > 0)
                            {
                                await SendEventsFromCSVFile(deviceId, targetSite, fileDataPath, fieldDefinitionsPath);
                            }
                            else
                            {
                                Console.WriteLine("No valid path provided for CSV data file");
                            }
                            break;

                        case "7":
                            Console.WriteLine("Target Application URI: ");
                            targetSite = Console.ReadLine();
                            Console.WriteLine("Device ID: ");
                            deviceId = Console.ReadLine();
                            Console.WriteLine("JSON File Path:");
                            fileDataPath = Console.ReadLine();
                            await SendEventsFromJSONFile(deviceId, targetSite, fileDataPath);
                            break;

                        case "8":
                            return;

                        default:
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Oops, {0}", ex.Message);
                    }
                }
            })
            .GetAwaiter().GetResult();
        }
        private static async Task MainAsync(string[] args)
        {
            // Read the parameters from the configuration file and command line
            Parameters parameters = new Parameters();

            parameters.ReadFromConfigFile();
            parameters.OverrideFromCommandLine(args);

            // Create the test specifications for each client
            int numClients = (int)parameters.ParameterValues[Parameters.Id.NumClients];

            TestSpecifications[] testSpecifications = CreateTestSpecifications(parameters, numClients);

            // Wait until the load driver service (that hosts the clients) is ready
            X509Credentials credentials = new X509Credentials()
            {
                StoreLocation = StoreLocation.LocalMachine,
                StoreName     = new X509Store(StoreName.My, StoreLocation.LocalMachine).Name,
                FindType      = X509FindType.FindByThumbprint,
                FindValue     = (string)parameters.ParameterValues[Parameters.Id.ClientCertificateThumbprint],
            };

            credentials.RemoteCertThumbprints.Add(
                (string)parameters.ParameterValues[Parameters.Id.ServerCertificateThumbprint]);

            FabricClient fabricClient = new FabricClient(
                credentials,
                new FabricClientSettings(),
                GetEndpointAddress(
                    (string)parameters.ParameterValues[Parameters.Id.ClusterAddress],
                    (int)parameters.ParameterValues[Parameters.Id.ClientConnectionPort]));
            ServicePartitionList partitionList = await AwaitPartitionReadyOperation.PerformAsync(
                fabricClient,
                LoadDriverServiceUri);

            // Verify that the load driver service has at least as many partitions as the number of
            // clients that we need to create.
            if (partitionList.Count < numClients)
            {
                string message = String.Format(
                    "The value for parameter '{0}' ({1}) should not be greater than the number of partitions ({2}) of the '{3}' service.",
                    Parameters.ParameterNames.Single(kvp => (kvp.Value == Parameters.Id.NumClients)).Key,
                    numClients,
                    partitionList.Count,
                    LoadDriverServiceUri.AbsoluteUri);
                throw new ConfigurationErrorsException(message);
            }

            // Get the interfaces for each instance of the load driver service.
            ILoadDriver[] loadDrivers = CreateLoadDrivers(
                GetEndpointAddress(
                    (string)parameters.ParameterValues[Parameters.Id.ClusterAddress],
                    (int)parameters.ParameterValues[Parameters.Id.ReverseProxyPort]),
                partitionList);

            // Create and initialize the clients inside the load driver service.
            Task[] initializationTasks = new Task[numClients];
            for (int i = 0; i < numClients; i++)
            {
                initializationTasks[i] = loadDrivers[i].InitializeAsync(testSpecifications[i]);
            }
            await Task.WhenAll(initializationTasks);

            // Run the tests
            TestResults writeTestResults = await RunTestAsync(
                numClients,
                loadDrivers,
                ld => ld.RunWriteTestAsync());

            TestResults readTestResults = await RunTestAsync(
                numClients,
                loadDrivers,
                ld => ld.RunReadTestAsync());

            // Display the results
            Console.WriteLine("Write test results - {0}", writeTestResults);
            Console.WriteLine("Read test results - {0}", readTestResults);
        }