Beispiel #1
0
 ///GENMHASH:2357B38E494D9F10171A28E135CB1715:3961EA7B900ECE15CB8B6D76F00F665B
 internal PacketCaptureImpl(string name, NetworkWatcherImpl parent, PacketCaptureResultInner innerObject, IPacketCapturesOperations client)
     : base(name, innerObject)
 {
     this.client           = client;
     this.parent           = parent;
     this.createParameters = new PacketCaptureInner();
 }
        private static async Task <INetworkWatcher> EnsureNetworkWatcherExists(IAzure azure, Region region, TraceWriter log = null)
        {
            // Retrieve appropriate Network Watcher, or create one
            INetworkWatcher networkWatcher = azure.NetworkWatchers.List().First(x => x.Region == region);

            if (networkWatcher == null)
            {
                try
                {
                    // Create Resource Group for Network Watcher if Network Watcher does not exist
                    IResourceGroup networkWatcherRG = azure.ResourceGroups.GetByName("NetworkWatcherRG");
                    if (networkWatcherRG == null)
                    {
                        // The RG is conventionally created in USWestCentral even though the Network Watcher region may be different
                        networkWatcherRG = await azure.ResourceGroups
                                           .Define("NetworkWatcherRG")
                                           .WithRegion(Region.USWestCentral)
                                           .CreateAsync();
                    }

                    string networkWatcherName = "NetworkWatcher_" + region.Name.ToString().ToLower();
                    networkWatcher = await azure.NetworkWatchers.Define(networkWatcherName).WithRegion(region).WithExistingResourceGroup(networkWatcherRG).CreateAsync();
                }
                catch (Exception ex)
                {
                    log?.Error($"Unable to create ResourceGroup or Network Watcher: {ex}. Exiting.");
                    throw;
                }
            }

            return(networkWatcher);
        }
Beispiel #3
0
 public BroadcastService(IBroadcastFactory broadcastFactory, INetworkWatcher networkWatcher, INetworkUtility networkUtility)
 {
     _broadcastFactory = broadcastFactory ?? throw new ArgumentNullException(nameof(broadcastFactory));
     _networkWatcher   = networkWatcher ?? throw new ArgumentNullException(nameof(networkWatcher));
     _networkUtility   = networkUtility ?? throw new ArgumentNullException(nameof(networkUtility));
     _networkWatcher.NetworkStateChanged += NetworkStateChangedHandler;
 }
Beispiel #4
0
        private static async Task <INetworkWatcher> EnsureNetworkWatcherExists(IAzure azure, Region region, TraceWriter log = null)
        {
            // Retrieve appropriate Network Watcher, or create one
            INetworkWatcher networkWatcher = null;
            IEnumerable <INetworkWatcher> networkWatcherList = azure.NetworkWatchers.List();

            if (networkWatcherList != null && networkWatcherList.Count() > 0)
            {
                log.Verbose($"Network Watchers found in subscription - checking if any are in region {region.Name}");
                try
                {
                    networkWatcher = azure.NetworkWatchers.List().First(x => x.Region == region);
                }
                catch (Exception)
                {
                    log.Info($"No network watchers found in region {region.Name}");
                }
            }
            else
            {
                log.Verbose("No Network Watchers found in subscription.");
            }
            if (networkWatcher == null)
            {
                try
                {
                    string networkWatcherRGName = "NetworkWatcherRG";
                    log.Info($"No Network Watcher exists in region {region.Name}. Will attempt to create in ResourceGroup {networkWatcherRGName}");
                    // Create Resource Group for Network Watcher if Network Watcher does not exist
                    IResourceGroup networkWatcherRG = azure.ResourceGroups.GetByName(networkWatcherRGName);
                    if (networkWatcherRG == null)
                    {
                        Region targetNetworkWatcherRGRegion = region;
                        log.Info($"Resource Group {networkWatcherRGName} does not exist. Creating it in region: {targetNetworkWatcherRGRegion.Name}. Note - the region of the Network Watcher's Resource Group does not have to match the region of the Network Watcher.");
                        networkWatcherRG = await azure.ResourceGroups
                                           .Define(networkWatcherRGName)
                                           .WithRegion(targetNetworkWatcherRGRegion)
                                           .CreateAsync();

                        log.Info("Created Resource Group");
                    }

                    string networkWatcherName = "NetworkWatcher_" + region.Name.ToString().ToLower();
                    log.Info($"Creating the network watcher {networkWatcherName} in resource group {networkWatcherRG.Name}");
                    networkWatcher = await azure.NetworkWatchers.Define(networkWatcherName).WithRegion(region).WithExistingResourceGroup(networkWatcherRG).CreateAsync();

                    log.Info($"Network Watcher created successfully");
                }
                catch (Exception ex)
                {
                    log?.Error($"Unable to create ResourceGroup or Network Watcher: {ex}. Exiting.");
                    throw ex;
                }
            }

            return(networkWatcher);
        }
Beispiel #5
0
 ///GENMHASH:5FF6F22B17DD7078FE6B3E25A08DAF00:C76EE92DA65DAA991DB405193AE42CE5
 internal ConnectionMonitorImpl(string name, NetworkWatcherImpl parent, ConnectionMonitorResultInner innerObject, IConnectionMonitorsOperations client)
     : base(name, innerObject)
 {
     this.client           = client;
     this.parent           = parent;
     this.createParameters = new ConnectionMonitorInner()
     {
         Location = parent.RegionName
     };
 }
Beispiel #6
0
    public App()
    {
        var broadcastFactory      = new ChainerFactory(16384);
        var networkServiceFactory = new NetworkServiceFactory();

        _watcher          = networkServiceFactory.CreateWatcher();
        _broadcastService = new BroadcastService(broadcastFactory, _watcher, networkServiceFactory.CreateUtility());
        InitializeBroadcastService(networkServiceFactory, _broadcastService);
        var frameworkDialogFactory = new DefaultFrameworkDialogFactory();
        var dialogService          = new DefaultDialogService(frameworkDialogFactory);
        var fileService            = new DefaultFileService(new [] { ".lpsnp" });

        _paintDataContext = new PaintViewModel(_broadcastService, dialogService, fileService, networkServiceFactory);
    }
Beispiel #7
0
        /**
         * Azure Network sample for managing virtual network gateway.
         *  - Create 2 virtual networks with subnets and 2 virtual network gateways corresponding to each network
         *  - Create VPN VNet-to-VNet connection
         *  - Troubleshoot the connection
         *    - Create network watcher in the same region as virtual network gateway
         *    - Create storage account to store troubleshooting information
         *    - Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first
         *  - Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'.
         *  - List VPN Gateway connections for the first gateway
         *  - Create 2 virtual machines, each one in its network and verify connectivity between them
         */
        public static void RunSample(IAzure azure)
        {
            string rgName          = SdkContext.RandomResourceName("rg", 24);
            string vnetName        = SdkContext.RandomResourceName("vnet", 20);
            string vnet2Name       = SdkContext.RandomResourceName("vnet", 20);
            string vpnGatewayName  = SdkContext.RandomResourceName("vngw", 20);
            string vpnGateway2Name = SdkContext.RandomResourceName("vngw2", 20);
            string connectionName  = SdkContext.RandomResourceName("con", 20);
            string connection2Name = SdkContext.RandomResourceName("con2", 20);
            string nwName          = SdkContext.RandomResourceName("nw", 20);
            string vm1Name         = SdkContext.RandomResourceName("vm1", 20);
            string vm2Name         = SdkContext.RandomResourceName("vm2", 20);
            string rootname        = Utilities.CreateUsername();
            string password        = SdkContext.RandomResourceName("pWd!", 15);
            string containerName   = "results";

            try
            {
                //============================================================
                // Create virtual network
                Utilities.Log("Creating virtual network...");
                INetwork network1 = azure.Networks.Define(vnetName)
                                    .WithRegion(region)
                                    .WithNewResourceGroup(rgName)
                                    .WithAddressSpace("10.11.0.0/16")
                                    .WithSubnet("GatewaySubnet", "10.11.255.0/27")
                                    .WithSubnet("Subnet1", "10.11.0.0/24")
                                    .Create();
                Utilities.Log("Created network");
                // Print the virtual network
                Utilities.PrintVirtualNetwork(network1);

                //============================================================
                // Create virtual network gateway
                Utilities.Log("Creating virtual network gateway...");
                IVirtualNetworkGateway vngw1 = azure.VirtualNetworkGateways.Define(vpnGatewayName)
                                               .WithRegion(region)
                                               .WithNewResourceGroup(rgName)
                                               .WithExistingNetwork(network1)
                                               .WithRouteBasedVpn()
                                               .WithSku(VirtualNetworkGatewaySkuName.VpnGw1)
                                               .Create();
                Utilities.Log("Created virtual network gateway");

                //============================================================
                // Create second virtual network
                Utilities.Log("Creating virtual network...");
                INetwork network2 = azure.Networks.Define(vnet2Name)
                                    .WithRegion(region)
                                    .WithNewResourceGroup(rgName)
                                    .WithAddressSpace("10.41.0.0/16")
                                    .WithSubnet("GatewaySubnet", "10.41.255.0/27")
                                    .WithSubnet("Subnet2", "10.41.0.0/24")
                                    .Create();
                Utilities.Log("Created virtual network");

                //============================================================
                // Create second virtual network gateway
                Utilities.Log("Creating second virtual network gateway...");
                IVirtualNetworkGateway vngw2 = azure.VirtualNetworkGateways.Define(vpnGateway2Name)
                                               .WithRegion(region)
                                               .WithNewResourceGroup(rgName)
                                               .WithExistingNetwork(network2)
                                               .WithRouteBasedVpn()
                                               .WithSku(VirtualNetworkGatewaySkuName.VpnGw1)
                                               .Create();
                Utilities.Log("Created second virtual network gateway");

                //============================================================
                // Create virtual network gateway connection
                Utilities.Log("Creating virtual network gateway connection...");
                IVirtualNetworkGatewayConnection connection = vngw1.Connections
                                                              .Define(connectionName)
                                                              .WithVNetToVNet()
                                                              .WithSecondVirtualNetworkGateway(vngw2)
                                                              .WithSharedKey("MySecretKey")
                                                              .Create();
                Utilities.Log("Created virtual network gateway connection");

                //============================================================
                // Troubleshoot the connection

                // create Network Watcher
                INetworkWatcher nw = azure.NetworkWatchers.Define(nwName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(rgName)
                                     .Create();
                // Create storage account to store troubleshooting information
                IStorageAccount storageAccount = azure.StorageAccounts.Define("sa" + SdkContext.RandomResourceName("", 8))
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(rgName)
                                                 .Create();
                // Create storage container to store troubleshooting results
                string accountKey       = storageAccount.GetKeys()[0].Value;
                string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccount.Name, accountKey);
                Utilities.CreateContainer(connectionString, containerName);

                // Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first
                ITroubleshooting troubleshooting = nw.Troubleshoot()
                                                   .WithTargetResourceId(connection.Id)
                                                   .WithStorageAccount(storageAccount.Id)
                                                   .WithStoragePath(storageAccount.EndPoints.Primary.Blob + containerName)
                                                   .Execute();
                Utilities.Log("Troubleshooting status is: " + troubleshooting.Code);

                //============================================================
                //  Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'.
                vngw2.Connections
                .Define(connection2Name)
                .WithVNetToVNet()
                .WithSecondVirtualNetworkGateway(vngw1)
                .WithSharedKey("MySecretKey")
                .Create();
                // Delay before running troubleshooting to wait for connection settings to propagate
                SdkContext.DelayProvider.Delay(250000);
                troubleshooting = nw.Troubleshoot()
                                  .WithTargetResourceId(connection.Id)
                                  .WithStorageAccount(storageAccount.Id)
                                  .WithStoragePath(storageAccount.EndPoints.Primary.Blob + containerName)
                                  .Execute();
                Utilities.Log("Troubleshooting status is: " + troubleshooting.Code);

                //============================================================
                // List VPN Gateway connections for particular gateway
                var connections = vngw1.ListConnections();
                foreach (var conn in connections)
                {
                    Utilities.Print(conn);
                }

                //============================================================
                // Create 2 virtual machines, each one in its network and verify connectivity between them
                List <ICreatable <IVirtualMachine> > vmDefinitions = new List <ICreatable <IVirtualMachine> >();

                vmDefinitions.Add(azure.VirtualMachines.Define(vm1Name)
                                  .WithRegion(region)
                                  .WithExistingResourceGroup(rgName)
                                  .WithExistingPrimaryNetwork(network1)
                                  .WithSubnet("Subnet1")
                                  .WithPrimaryPrivateIPAddressDynamic()
                                  .WithoutPrimaryPublicIPAddress()
                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                  .WithRootUsername(rootname)
                                  .WithRootPassword(password)
                                  // Extension currently needed for network watcher support
                                  .DefineNewExtension("networkWatcher")
                                  .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                  .WithType("NetworkWatcherAgentLinux")
                                  .WithVersion("1.4")
                                  .Attach());
                vmDefinitions.Add(azure.VirtualMachines.Define(vm2Name)
                                  .WithRegion(region)
                                  .WithExistingResourceGroup(rgName)
                                  .WithExistingPrimaryNetwork(network2)
                                  .WithSubnet("Subnet2")
                                  .WithPrimaryPrivateIPAddressDynamic()
                                  .WithoutPrimaryPublicIPAddress()
                                  .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                  .WithRootUsername(rootname)
                                  .WithRootPassword(password)
                                  // Extension currently needed for network watcher support
                                  .DefineNewExtension("networkWatcher")
                                  .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                  .WithType("NetworkWatcherAgentLinux")
                                  .WithVersion("1.4")
                                  .Attach());
                ICreatedResources <IVirtualMachine> createdVMs = azure.VirtualMachines.Create(vmDefinitions);
                IVirtualMachine vm1 = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key);
                IVirtualMachine vm2 = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key);

                IConnectivityCheck connectivity = nw.CheckConnectivity()
                                                  .ToDestinationResourceId(vm2.Id)
                                                  .ToDestinationPort(22)
                                                  .FromSourceVirtualMachine(vm1.Id)
                                                  .Execute();
                Utilities.Log("Connectivity status: " + connectivity.ConnectionStatus);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
Beispiel #8
0
        /**
         * Azure Network sample for managing network watcher -
         *  - Create Network Watcher
         *	- Manage packet capture – track traffic to and from a virtual machine
         *      Create a VM
         *      Start a packet capture
         *      Stop a packet capture
         *      Get a packet capture
         *      Delete a packet capture
         *  - Verify IP flow – verify if traffic is allowed to or from a virtual machine
         *      Get the IP address of a NIC on a virtual machine
         *      Test IP flow on the NIC
         *  - Analyze next hop – get the next hop type and IP address for a virtual machine
         *  - Retrieve network topology for a resource group
         *  - Analyze Virtual Machine Security by examining effective network security rules applied to a VM
         *      Get security group view for the VM
         *  - Configure Network Security Group Flow Logs
         *      Get flow log settings
         *      Enable NSG flow log
         *      Disable NSG flow log
         *  - Delete network watcher
         */
        public static void RunSample(IAzure azure)
        {
            string nwName = SdkContext.RandomResourceName("nw", 8);

            string          userName          = "******";
            string          vnetName          = SdkContext.RandomResourceName("vnet", 20);
            string          subnetName        = "subnet1";
            string          nsgName           = SdkContext.RandomResourceName("nsg", 20);
            string          dnsLabel          = SdkContext.RandomResourceName("pipdns", 20);
            string          rgName            = SdkContext.RandomResourceName("rg", 24);
            string          saName            = SdkContext.RandomResourceName("sa", 24);
            string          vmName            = SdkContext.RandomResourceName("vm", 24);
            string          packetCaptureName = SdkContext.RandomResourceName("pc", 8);
            INetworkWatcher nw = null;

            try
            {
                //============================================================
                // Create network watcher
                Utilities.Log("Creating network watcher...");
                nw = azure.NetworkWatchers.Define(nwName)
                     .WithRegion(region)
                     .WithNewResourceGroup()
                     .Create();

                Utilities.Log("Created network watcher");
                // Print the network watcher
                Utilities.Print(nw);

                //============================================================
                // Manage packet capture – track traffic to and from a virtual machine

                // Create network security group, virtual network and VM; add packetCapture extension to enable packet capture
                Utilities.Log("Creating network security group...");
                INetworkSecurityGroup nsg = azure.NetworkSecurityGroups.Define(nsgName)
                                            .WithRegion(region)
                                            .WithNewResourceGroup(rgName)
                                            .DefineRule("DenyInternetInComing")
                                            .DenyInbound()
                                            .FromAddress("INTERNET")
                                            .FromAnyPort()
                                            .ToAnyAddress()
                                            .ToPort(443)
                                            .WithAnyProtocol()
                                            .Attach()
                                            .Create();
                Utilities.Log("Creating virtual network...");
                ICreatable <INetwork> virtualNetwork = azure.Networks.Define(vnetName)
                                                       .WithRegion(region)
                                                       .WithExistingResourceGroup(rgName)
                                                       .WithAddressSpace("192.168.0.0/16")
                                                       .DefineSubnet(subnetName)
                                                       .WithAddressPrefix("192.168.2.0/24")
                                                       .WithExistingNetworkSecurityGroup(nsg)
                                                       .Attach();
                Utilities.Log("Creating virtual machine...");
                IVirtualMachine vm = azure.VirtualMachines.Define(vmName)
                                     .WithRegion(region)
                                     .WithExistingResourceGroup(rgName)
                                     .WithNewPrimaryNetwork(virtualNetwork)
                                     .WithPrimaryPrivateIPAddressDynamic()
                                     .WithNewPrimaryPublicIPAddress(dnsLabel)
                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer14_04_Lts)
                                     .WithRootUsername(userName)
                                     .WithRootPassword("Abcdef.123456")
                                     .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                     .DefineNewExtension("packetCapture")
                                     .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                     .WithType("NetworkWatcherAgentLinux")
                                     .WithVersion("1.4")
                                     .WithMinorVersionAutoUpgrade()
                                     .Attach()
                                     .Create();

                // Create storage account
                Utilities.Log("Creating storage account...");
                IStorageAccount storageAccount = azure.StorageAccounts.Define(saName)
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(rgName)
                                                 .Create();

                // Start a packet capture
                Utilities.Log("Creating packet capture...");
                IPacketCapture packetCapture = nw.PacketCaptures
                                               .Define(packetCaptureName)
                                               .WithTarget(vm.Id)
                                               .WithStorageAccountId(storageAccount.Id)
                                               .WithTimeLimitInSeconds(1500)
                                               .DefinePacketCaptureFilter()
                                               .WithProtocol(PcProtocol.TCP)
                                               .Attach()
                                               .Create();
                Utilities.Log("Created packet capture");
                Utilities.Print(packetCapture);

                // Stop a packet capture
                Utilities.Log("Stopping packet capture...");
                packetCapture.Stop();
                Utilities.Print(packetCapture);

                // Get a packet capture
                Utilities.Log("Getting packet capture...");
                IPacketCapture packetCapture1 = nw.PacketCaptures.GetByName(packetCaptureName);
                Utilities.Print(packetCapture1);

                // Delete a packet capture
                Utilities.Log("Deleting packet capture");
                nw.PacketCaptures.DeleteByName(packetCapture.Name);

                //============================================================
                // Verify IP flow – verify if traffic is allowed to or from a virtual machine
                // Get the IP address of a NIC on a virtual machine
                String ipAddress = vm.GetPrimaryNetworkInterface().PrimaryPrivateIP;
                // Test IP flow on the NIC
                Utilities.Log("Verifying IP flow for vm id " + vm.Id + "...");
                IVerificationIPFlow verificationIPFlow = nw.VerifyIPFlow()
                                                         .WithTargetResourceId(vm.Id)
                                                         .WithDirection(Direction.Outbound)
                                                         .WithProtocol(IpFlowProtocol.TCP)
                                                         .WithLocalIPAddress(ipAddress)
                                                         .WithRemoteIPAddress("8.8.8.8")
                                                         .WithLocalPort("443")
                                                         .WithRemotePort("443")
                                                         .Execute();
                Utilities.Print(verificationIPFlow);

                //============================================================
                // Analyze next hop – get the next hop type and IP address for a virtual machine
                Utilities.Log("Calculating next hop...");
                INextHop nextHop = nw.NextHop().WithTargetResourceId(vm.Id)
                                   .WithSourceIPAddress(ipAddress)
                                   .WithDestinationIPAddress("8.8.8.8")
                                   .Execute();
                Utilities.Print(nextHop);

                //============================================================
                // Retrieve network topology for a resource group
                Utilities.Log("Getting topology...");
                ITopology topology = nw.Topology()
                                     .WithTargetResourceGroup(rgName)
                                     .Execute();
                Utilities.Print(topology);

                //============================================================
                // Analyze Virtual Machine Security by examining effective network security rules applied to a VM
                // Get security group view for the VM
                Utilities.Log("Getting security group view for a vm");
                ISecurityGroupView sgViewResult = nw.GetSecurityGroupView(vm.Id);
                Utilities.Print(sgViewResult);

                //============================================================
                // Configure Network Security Group Flow Logs

                // Get flow log settings
                IFlowLogSettings flowLogSettings = nw.GetFlowLogSettings(nsg.Id);
                Utilities.Print(flowLogSettings);

                // Enable NSG flow log
                flowLogSettings.Update()
                .WithLogging()
                .WithStorageAccount(storageAccount.Id)
                .WithRetentionPolicyDays(5)
                .WithRetentionPolicyEnabled()
                .Apply();
                Utilities.Print(flowLogSettings);

                // Disable NSG flow log
                flowLogSettings.Update()
                .WithoutLogging()
                .Apply();
                Utilities.Print(flowLogSettings);

                //============================================================
                // Delete network watcher
                Utilities.Log("Deleting network watcher");
                azure.NetworkWatchers.DeleteById(nw.Id);
                Utilities.Log("Deleted network watcher");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    if (nw != null)
                    {
                        Utilities.Log("Deleting network watcher resource group: " + nw.ResourceGroupName);
                        azure.ResourceGroups.BeginDeleteByName(nw.ResourceGroupName);
                    }
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        /**
         * Azure Network sample for enabling and updating network peering between two virtual networks
         *
         * Summary ...
         *
         * - This sample uses Azure Network Watcher's connectivity check to verify connectivity between
         *   two peered virtual networks.
         *
         * Details ...
         *
         * 1. Define two virtual networks network "A" and network "B" with one subnet each
         *
         * 2. Create two virtual machines, each within a separate network
         *   - The virtual machines currently must use a special extension to support Network Watcher
         *
         * 3. Peer the networks...
         *   - the peering will initially have default settings:
         *   - each network's IP address spaces will be accessible from the other network
         *   - no traffic forwarding will be enabled between the networks
         *   - no gateway transit between one network and the other will be enabled
         *
         * 4. Use Network Watcher to check connectivity between the virtual machines in different peering scenarios:
         *   - both virtual machines accessible to each other (bi-directional)
         *   - virtual machine A accessible to virtual machine B, but not the other way
         */

        public static void RunSample(IAzure azure)
        {
            Region region            = Region.USEast;
            string resourceGroupName = SdkContext.RandomResourceName("rg", 15);
            string vnetAName         = SdkContext.RandomResourceName("net", 15);
            string vnetBName         = SdkContext.RandomResourceName("net", 15);

            string[] vmNames       = SdkContext.RandomResourceNames("vm", 15, 2);
            string[] vmIPAddresses = new String[] {
                /* within subnetA */ "10.0.0.8",
                /* within subnetB */ "10.1.0.8"
            };

            string peeringABName      = SdkContext.RandomResourceName("peer", 15);
            string rootname           = "tirekicker";
            string password           = SdkContext.RandomResourceName("pWd!", 15);
            string networkWatcherName = SdkContext.RandomResourceName("netwch", 20);

            try
            {
                //=============================================================
                // Define two virtual networks to peer and put the virtual machines in, at specific IP addresses

                List <ICreatable <INetwork> > networkDefinitions = new List <ICreatable <INetwork> >();
                networkDefinitions.Add(azure.Networks.Define(vnetAName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(resourceGroupName)
                                       .WithAddressSpace("10.0.0.0/27")
                                       .WithSubnet("subnetA", "10.0.0.0/27"));

                networkDefinitions.Add(azure.Networks.Define(vnetBName)
                                       .WithRegion(region)
                                       .WithNewResourceGroup(resourceGroupName)
                                       .WithAddressSpace("10.1.0.0/27")
                                       .WithSubnet("subnetB", "10.1.0.0/27"));

                //=============================================================
                // Define a couple of Windows VMs and place them in each of the networks

                List <ICreatable <IVirtualMachine> > vmDefinitions = new List <ICreatable <IVirtualMachine> >();

                for (int i = 0; i < networkDefinitions.Count; i++)
                {
                    vmDefinitions.Add(azure.VirtualMachines.Define(vmNames[i])
                                      .WithRegion(region)
                                      .WithExistingResourceGroup(resourceGroupName)
                                      .WithNewPrimaryNetwork(networkDefinitions[i])
                                      .WithPrimaryPrivateIPAddressStatic(vmIPAddresses[i])
                                      .WithoutPrimaryPublicIPAddress()
                                      .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter)
                                      .WithAdminUsername(rootname)
                                      .WithAdminPassword(password)

                                      // Extension currently needed for network watcher support
                                      .DefineNewExtension("packetCapture")
                                      .WithPublisher("Microsoft.Azure.NetworkWatcher")
                                      .WithType("NetworkWatcherAgentWindows")
                                      .WithVersion("1.4")
                                      .Attach());
                }

                // Create the VMs in parallel for better performance
                Utilities.Log("Creating virtual machines and virtual networks...");
                var             createdVMs = azure.VirtualMachines.Create(vmDefinitions);
                IVirtualMachine vmA        = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key);
                IVirtualMachine vmB        = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key);
                Utilities.Log("Created the virtual machines and networks.");

                //=============================================================
                // Peer the two networks using default settings

                INetwork networkA = vmA.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
                INetwork networkB = vmB.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();

                Utilities.PrintVirtualNetwork(networkA);
                Utilities.PrintVirtualNetwork(networkB);

                Utilities.Log(
                    "Peering the networks using default settings...\n"
                    + "- Network access enabled\n"
                    + "- Traffic forwarding disabled\n"
                    + "- Gateway use (transit) by the remote network disabled");

                INetworkPeering peeringAB = networkA.Peerings.Define(peeringABName)
                                            .WithRemoteNetwork(networkB)
                                            .Create();

                Utilities.PrintVirtualNetwork(networkA);
                Utilities.PrintVirtualNetwork(networkB);

                //=============================================================
                // Check connectivity between the two VMs/networks using Network Watcher
                INetworkWatcher networkWatcher = azure.NetworkWatchers.Define(networkWatcherName)
                                                 .WithRegion(region)
                                                 .WithExistingResourceGroup(resourceGroupName)
                                                 .Create();

                // Verify bi-directional connectivity between the VMs on port 22 (SSH enabled by default on Linux VMs)
                IExecutable <IConnectivityCheck> connectivityAtoB = networkWatcher.CheckConnectivity()
                                                                    .ToDestinationAddress(vmIPAddresses[1])
                                                                    .ToDestinationPort(22)
                                                                    .FromSourceVirtualMachine(vmA);
                Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus);

                IExecutable <IConnectivityCheck> connectivityBtoA = networkWatcher.CheckConnectivity()
                                                                    .ToDestinationAddress(vmIPAddresses[0])
                                                                    .ToDestinationPort(22)
                                                                    .FromSourceVirtualMachine(vmB);
                Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus);

                // Change the peering to allow access between A and B
                Utilities.Log("Changing the peering to disable access between A and B...");
                peeringAB.Update()
                .WithoutAccessFromEitherNetwork()
                .Apply();

                Utilities.PrintVirtualNetwork(networkA);
                Utilities.PrintVirtualNetwork(networkB);

                // Verify connectivity no longer possible between A and B
                Utilities.Log("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A...");
                Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus);
                Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + resourceGroupName);
                    azure.ResourceGroups.BeginDeleteByName(resourceGroupName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        public static async Task Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            //Parse alert request
            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            Webhook data        = new Webhook();

            data = JsonConvert.DeserializeObject <Webhook>(requestBody);
            Context alertResource = data.RequestBody.context;

            IConfigurationRoot config = new ConfigurationBuilder()
                                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();

            string tenantId  = config.GetConnectionString("TenantId");
            string clientId  = config.GetConnectionString("clientId");
            string clientKey = config.GetConnectionString("ClientKey");

            if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientKey))
            {
                log.Error("Serivice credentials are null. Check connection string settings");
                return;
            }

            AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientKey, tenantId, AzureEnvironment.AzureGlobalCloud);
            IAzure           azure       = Azure.Configure().Authenticate(credentials).WithSubscription(alertResource.subscriptionId);

            if (azure == null)
            {
                log.Error("Error: Issues logging into Azure subscription: " + alertResource.subscriptionId + ". Exiting.");
                return;
            }

            IVirtualMachine VM = await azure.VirtualMachines.GetByIdAsync(alertResource.resourceId);

            if (VM == null)
            {
                log.Error("Error: VM: " + alertResource.resourceId + "was not found. Exiting.");
                return;
            }

            INetworkWatcher networkWatcher = await EnsureNetworkWatcherExists(azure, VM.Region, log);

            InstallNetworkWatcherExtension(VM, log);

            string storageAccountId = Environment.GetEnvironmentVariable("PacketCaptureStorageAccount");
            var    storageAccount   = await azure.StorageAccounts.GetByIdAsync(storageAccountId);

            if (storageAccount == null)
            {
                log.Error("Storage Account: " + storageAccountId + " not found. Exiting.");
                return;
            }

            string packetCaptureName = VM.Name.Substring(0, System.Math.Min(63, VM.Name.Length)) + System.DateTime.Now.ToString("s").Replace(":", "");

            IPacketCaptures packetCapturesObj = networkWatcher.PacketCaptures;
            var             packetCaptures    = packetCapturesObj.List().ToList();

            if (packetCaptures.Count >= 10)
            {
                log.Info("More than 10 Captures, finding oldest.");
                var packetCaptureTasks = new List <Task <IPacketCaptureStatus> >();
                foreach (IPacketCapture pcap in packetCaptures)
                {
                    packetCaptureTasks.Add(pcap.GetStatusAsync());
                }

                var packetCaptureStatuses = new List <Tuple <IPacketCapture, IPacketCaptureStatus> >();
                for (int i = 0; i < packetCaptureTasks.Count; ++i)
                {
                    packetCaptureStatuses.Add(new Tuple <IPacketCapture, IPacketCaptureStatus>(packetCaptures[i], await packetCaptureTasks[i]));
                }

                packetCaptureStatuses.Sort((Tuple <IPacketCapture, IPacketCaptureStatus> first, Tuple <IPacketCapture, IPacketCaptureStatus> second) =>
                {
                    return(first.Item2.CaptureStartTime.CompareTo(second.Item2.CaptureStartTime));
                });
                log.Info("Removing: " + packetCaptureStatuses.First().Item1.Name);
                await networkWatcher.PacketCaptures.DeleteByNameAsync(packetCaptureStatuses.First().Item1.Name);
            }

            log.Info("Creating Packet Capture");
            await networkWatcher.PacketCaptures
            .Define(packetCaptureName)
            .WithTarget(VM.Id)
            .WithStorageAccountId(storageAccount.Id)
            .WithTimeLimitInSeconds(15)
            .CreateAsync();

            log.Info("Packet Capture created successfully");
        }