Example #1
0
        //public string PingCmd {get; protected set;}
        //public Predicate<string> PingCorrect { get; protected set; }

        /// <summary>
        /// Finds an open port that responds to a given command.
        /// </summary>
        /// <param name="board"></param>
        /// <param name="portLow"></param>
        /// <param name="portHigh"></param>
        /// <param name="pingCmd"></param>
        /// <param name="pingCorrect"></param>
        /// <returns></returns>
        public static int FindExistingPort(IPAddress ipAdress,
                                           int portLow,
                                           int portHigh,
                                           Func <IPAddress, int, INetworkCom> getComDevice,
                                           string pingCmd,
                                           Predicate <string> pingCorrect,
                                           IStatusProvider status = null)
        {
            //NOTE: status.UpdateStatus is a null safe extension method

            status.UpdateStatus(Status.Starting("Searhing for available port."));

            int thePort = -1;

            //using threads to speed up tha scan
            Parallel.For(portLow, portHigh - 1, (P, S) =>
            {
                try
                {
                    //is the port open
                    TcpClient client      = new TcpClient();
                    client.SendTimeout    = 2000;
                    client.ReceiveTimeout = 2000;
                    client.Connect(ipAdress, P);
                    bool open = client.Connected;
                    client.Close();

                    //test to see if it will do what we want
                    if (open)
                    {
                        INetworkCom com = getComDevice(ipAdress, P);
                        if (TestConection(com, pingCmd, pingCorrect, status))
                        {
                            thePort = P;
                            S.Break();
                        }
                    }
                    client.Close();
                }
                catch
                {
                }
            });

            status.UpdateStatus((thePort >= 0) ? Status.Done("Found working port: " + thePort):
                                Status.Error("Could not find suitable port. "));
            return(thePort);
        }
Example #2
0
        public static bool TestConection(INetworkCom connection,
                                         string pingCmd,
                                         Predicate <string> pingCorrect,
                                         IStatusProvider status = null)
        {
            //NOTE: status.UpdateStatus is a null safe extension method

            bool successful = false;
            //TelnetCom tc = new SimpleTelnetCom(Board.IpAdress, TelnetPort);
            Why telnetConected = connection.Connect();

            if (telnetConected)
            {
                Task.Delay(500);
                status.UpdateStatus(Status.Done("Coms available: " + connection));
                status.UpdateStatus(Status.Done("Banner data: " + connection.InputBuffer.ToString()));
                successful = true;

                if (!string.IsNullOrEmpty(pingCmd))
                {
                    string telnetResponce = connection.ExecuteCommand(pingCmd);
                    if (pingCorrect != null)
                    {
                        successful = pingCorrect(telnetResponce);
                        status.UpdateStatus(successful ? Status.Done("Telnet test passed: " + telnetResponce) :
                                            Status.Error("Telnet test failed: " + telnetResponce));
                    }
                    else
                    {
                        successful = !string.IsNullOrWhiteSpace(telnetResponce);
                        status.UpdateStatus(successful ? Status.Done("Telnet responded to ping command: " + telnetResponce) :
                                            Status.Error("Telnet didn't respond to ping command: " + telnetResponce));
                    }
                }
            }
            else
            {
                status.UpdateStatus(Status.Error("Telnet un-available: " + telnetConected.Reason ?? "(no information)"));
            }
            return(successful);
        }
Example #3
0
        public DescribeVpcsResponse GetAllVpcs()
        {
            _statusProvider.UpdateStatus("BUSY: Getting all the VPCs...");

            return(_service.DescribeVpcs());
        }
Example #4
0
        public void toname(string accessKey, string secretKey, TreeNode subscriptionNode)
        {
            List <Amazon.RegionEndpoint> regionsList = new List <Amazon.RegionEndpoint>();

            foreach (var region in Amazon.RegionEndpoint.EnumerableAllRegions)
            {
                try
                {
                    _awsObjectRetriever = new AwsObjectRetriever(accessKey, secretKey, region, _LogProvider, _StatusProvider);
                    //// todo, not needed in this method_templateGenerator = new TemplateGenerator(_logProvider, _statusProvider, _awsObjectRetriever, telemetryProvider);

                    TreeNode amazonRegionNode = new TreeNode(region.DisplayName);
                    amazonRegionNode.Text = region.DisplayName;
                    amazonRegionNode.Tag  = region;

                    //DescribeVolumesResponse ebsVolumesResponse;

                    _StatusProvider.UpdateStatus("BUSY: Getting the VPC details");
                    DescribeVpcsResponse vpcResponse = getVPCs();
                    Application.DoEvents();

                    List <Azure.MigrationTarget.VirtualNetwork> targetVirtualNetworks = new List <Azure.MigrationTarget.VirtualNetwork>();
                    _StatusProvider.UpdateStatus("BUSY: Processing VPC");
                    foreach (var vpc in vpcResponse.Vpcs)
                    {
                        MigAz.AWS.MigrationSource.VirtualNetwork sourceVirtualNetwork = new MigrationSource.VirtualNetwork(_awsObjectRetriever, vpc);
                        Azure.MigrationTarget.VirtualNetwork     targetVirtualNetwork = new Azure.MigrationTarget.VirtualNetwork(sourceVirtualNetwork, null);
                        targetVirtualNetworks.Add(targetVirtualNetwork);

                        TreeNode vpcTreeNode = new TreeNode(sourceVirtualNetwork.Id + " - " + sourceVirtualNetwork.Name);
                        vpcTreeNode.Tag              = targetVirtualNetwork;
                        vpcTreeNode.ImageKey         = "VirtualNetwork";
                        vpcTreeNode.SelectedImageKey = "VirtualNetwork";
                        amazonRegionNode.Nodes.Add(vpcTreeNode);

                        //    // todo, this is foreach subnet
                        //    foreach (Subnet subnet in subnets)
                        //    {
                        //        //QUES: Single Sec group?
                        //        // add Network Security Group if exists - 2 subnets - each acl is associated with both
                        //        List<Amazon.EC2.Model.NetworkAcl> networkAcls = _awsObjectRetriever.getNetworkAcls(subnetnode.SubnetId);
                        //        List<Amazon.EC2.Model.RouteTable> routeTable = _awsObjectRetriever.getRouteTables(subnetnode.SubnetId);



                        //        //var nodes = networkAcls.SelectSingleNode("DescribeNetworkAclsResponse ").SelectSingleNode("networkAclSet").SelectNodes("item");

                        //        if (networkAcls.Count > 0)
                        //        {
                        //            NetworkSecurityGroup networksecuritygroup = BuildNetworkSecurityGroup(networkAcls[0]);

                        //            //NetworkSecurityGroup networksecuritygroup = BuildNetworkSecurityGroup(subnet.name);

                        //            // Add NSG reference to the subnet
                        //            Reference networksecuritygroup_ref = new Reference();
                        //            networksecuritygroup_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name + "')]";

                        //            properties.networkSecurityGroup = networksecuritygroup_ref;

                        //            // Add NSG dependsOn to the Virtual Network object
                        //            if (!virtualnetwork.dependsOn.Contains(networksecuritygroup_ref.id))
                        //            {
                        //                virtualnetwork.dependsOn.Add(networksecuritygroup_ref.id);
                        //            }

                        //        }

                        //        if (routeTable.Count > 0)
                        //        {
                        //            RouteTable routetable = BuildRouteTable(routeTable[0]);

                        //            if (routetable.properties != null)
                        //            {
                        //                // Add Route Table reference to the subnet
                        //                Reference routetable_ref = new Reference();
                        //                routetable_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/routeTables/" + routetable.name + "')]";

                        //                properties.routeTable = routetable_ref;

                        //                // Add Route Table dependsOn to the Virtual Network object
                        //                if (!virtualnetwork.dependsOn.Contains(routetable_ref.id))
                        //                {
                        //                    virtualnetwork.dependsOn.Add(routetable_ref.id);
                        //                }
                        //            }
                        //        }
                        //    }

                        //}

                        Application.DoEvents();
                    }

                    DescribeInstancesResponse instResponse = getEC2Instances();
                    Application.DoEvents();

                    foreach (LoadBalancerDescription loadBalancerDescription in _awsObjectRetriever.GetAllLBs().LoadBalancerDescriptions)
                    {
                        MigAz.AWS.MigrationSource.LoadBalancer sourceLoadBalancer = new MigAz.AWS.MigrationSource.LoadBalancer(loadBalancerDescription);

                        Azure.MigrationTarget.LoadBalancer targetLoadBalancer = new Azure.MigrationTarget.LoadBalancer();
                        targetLoadBalancer.SetTargetName(loadBalancerDescription.LoadBalancerName, null);

                        Azure.MigrationTarget.FrontEndIpConfiguration targetFrontEndIpConfiguration = new Azure.MigrationTarget.FrontEndIpConfiguration(targetLoadBalancer);
                        targetFrontEndIpConfiguration.Name = "ipconfig1";        // can this come from Amazon?

                        if (loadBalancerDescription.Scheme != "internet-facing") // if internal load balancer
                        {
                            foreach (Azure.MigrationTarget.VirtualNetwork targetVirtualNetwork in targetVirtualNetworks)
                            {
                                if (targetVirtualNetwork.SourceVirtualNetwork != null)
                                {
                                    AWS.MigrationSource.VirtualNetwork amazonVirtualNetwork = (AWS.MigrationSource.VirtualNetwork)targetVirtualNetwork.SourceVirtualNetwork;
                                    if (amazonVirtualNetwork.Id == loadBalancerDescription.VPCId)
                                    {
                                        targetFrontEndIpConfiguration.TargetVirtualNetwork = targetVirtualNetwork;

                                        foreach (Azure.MigrationTarget.Subnet targetSubnet in targetVirtualNetwork.TargetSubnets)
                                        {
                                            if (targetSubnet.SourceSubnet.Id == loadBalancerDescription.Subnets[0])
                                            {
                                                targetFrontEndIpConfiguration.TargetSubnet = targetSubnet;
                                                break;
                                            }
                                        }

                                        break;
                                    }
                                }
                            }

                            targetFrontEndIpConfiguration.TargetPrivateIPAllocationMethod = IPAllocationMethodEnum.Static;
                            try
                            {
                                IPHostEntry host = Dns.GetHostEntry(loadBalancerDescription.DNSName);
                                targetFrontEndIpConfiguration.TargetPrivateIpAddress = host.AddressList[0].ToString();
                            }
                            catch
                            {
                                targetFrontEndIpConfiguration.TargetPrivateIPAllocationMethod = IPAllocationMethodEnum.Dynamic;
                            }
                        }
                        else // if external (public) load balancer
                        {
                            Azure.MigrationTarget.PublicIp targetPublicIp = new Azure.MigrationTarget.PublicIp();
                            targetPublicIp.SetTargetName(loadBalancerDescription.LoadBalancerName, null);
                            targetPublicIp.DomainNameLabel = loadBalancerDescription.LoadBalancerName;

                            targetLoadBalancer.LoadBalancerType    = Azure.MigrationTarget.LoadBalancerType.Public;
                            targetFrontEndIpConfiguration.PublicIp = targetPublicIp;

                            TreeNode loadBalancerPublicIpNode = new TreeNode(targetPublicIp.TargetName);
                            loadBalancerPublicIpNode.Tag              = targetPublicIp;
                            loadBalancerPublicIpNode.ImageKey         = "PublicIp";
                            loadBalancerPublicIpNode.SelectedImageKey = "PublicIp";
                            amazonRegionNode.Nodes.Add(loadBalancerPublicIpNode);
                        }

                        TreeNode loadBalancerNode = new TreeNode(targetLoadBalancer.TargetName);
                        loadBalancerNode.Tag              = targetLoadBalancer;
                        loadBalancerNode.ImageKey         = "LoadBalancer";
                        loadBalancerNode.SelectedImageKey = "LoadBalancer";
                        amazonRegionNode.Nodes.Add(loadBalancerNode);
                    }

                    if (instResponse != null)
                    {
                        _StatusProvider.UpdateStatus("BUSY: Processing Instances");
                        if (instResponse.Reservations.Count > 0)
                        {
                            foreach (var instanceResp in instResponse.Reservations)
                            {
                                foreach (var instance in instanceResp.Instances)
                                {
                                    var selectedInstances = _awsObjectRetriever.getInstancebyId(instance.InstanceId);

//                                    List<NetworkProfile_NetworkInterface> networkinterfaces = new List<NetworkProfile_NetworkInterface>();

                                    String vpcId = selectedInstances.Instances[0].VpcId.ToString();

                                    //Process LBs
                                    var    LBs            = _awsObjectRetriever.GetAllLBs().LoadBalancerDescriptions;
                                    string instanceLBName = "";

                                    foreach (var LB in LBs)
                                    {
                                        foreach (var LBInstance in LB.Instances)
                                        {
                                            if ((LB.VPCId == vpcId) && (LBInstance.InstanceId == instance.InstanceId))
                                            {
                                                if (LB.Scheme == "internet-facing")
                                                {
                                                    // BuildPublicIPAddressObject(LB);
                                                }

                                                instanceLBName = LB.LoadBalancerName;
                                                //BuildLoadBalancerObject(LB, instance.InstanceId.ToString());
                                            }
                                        }
                                    }

                                    //Process Network Interface
                                    // todo now BuildNetworkInterfaceObject(selectedInstances.Instances[0], ref networkinterfaces, LBs);

                                    //Process EC2 Instance
                                    // todo now BuildVirtualMachineObject(selectedInstances.Instances[0], networkinterfaces, storageAccountName, instanceLBName);

                                    string name = "";
                                    foreach (var tag in instance.Tags)
                                    {
                                        if (tag.Key == "Name")
                                        {
                                            name = tag.Value;
                                        }
                                    }

                                    TreeNode instanceTreeNode = new TreeNode(instance.InstanceId + " - " + name);
                                    instanceTreeNode.Tag = instance;
                                    amazonRegionNode.Nodes.Add(instanceTreeNode);

                                    Application.DoEvents();
                                }
                            }
                        }
                    }



                    if (amazonRegionNode.Nodes.Count > 0)
                    {
                        subscriptionNode.Nodes.Add(amazonRegionNode);
                    }
                    else
                    {
                        _LogProvider.WriteLog("Load_Items", "Not adding Amazon Region '" + region.DisplayName + "' to Source Node list, as it contains no resources to export.");
                    }
                }
                catch (Exception exc)
                {
                    _LogProvider.WriteLog("Load_Items", "AWS Exception - " + region.DisplayName + ": " + exc.Message);
                }
            }
        }
Example #5
0
        private async Task _AzureContextSourceASM_AfterAzureSubscriptionChange(AzureContext sender)
        {
            ResetForm();

            if (sender.AzureSubscription != null)
            {
                lblSourceSubscriptionName.Text = sender.AzureSubscription.Name;
                lblSourceSubscriptionId.Text   = sender.AzureSubscription.SubscriptionId.ToString();

                if (_AzureContextTargetARM.AzureSubscription == null)
                {
                    lblTargetSubscriptionName.Text = sender.AzureSubscription.Name;
                    lblTargetSubscriptionId.Text   = sender.AzureSubscription.SubscriptionId.ToString();
                    await _AzureContextTargetARM.SetSubscriptionContext(_AzureContextSourceASM.AzureSubscription);
                }

                btnAzureContextARM.Enabled = true;

                TreeNode subscriptionNode = new TreeNode(sender.AzureSubscription.Name);
                treeASM.Nodes.Add(subscriptionNode);
                subscriptionNode.Expand();

                List <AsmVirtualNetwork> asmVirtualNetworks = await _AzureContextSourceASM.AzureRetriever.GetAzureAsmVirtualNetworks();

                foreach (AsmVirtualNetwork asmVirtualNetwork in asmVirtualNetworks)
                {
                    if (asmVirtualNetwork.HasNonGatewaySubnet)
                    {
                        TreeNode parentNode       = GetDataCenterTreeViewNode(subscriptionNode, asmVirtualNetwork.Location, "Virtual Networks");
                        TreeNode tnVirtualNetwork = new TreeNode(asmVirtualNetwork.Name);
                        tnVirtualNetwork.Name = asmVirtualNetwork.Name;
                        tnVirtualNetwork.Tag  = asmVirtualNetwork;
                        parentNode.Nodes.Add(tnVirtualNetwork);
                        parentNode.Expand();
                    }
                }

                foreach (AsmStorageAccount asmStorageAccount in await _AzureContextSourceASM.AzureRetriever.GetAzureAsmStorageAccounts())
                {
                    TreeNode parentNode       = GetDataCenterTreeViewNode(subscriptionNode, asmStorageAccount.GeoPrimaryRegion, "Storage Accounts");
                    TreeNode tnStorageAccount = new TreeNode(asmStorageAccount.Name);
                    tnStorageAccount.Name = tnStorageAccount.Text;
                    tnStorageAccount.Tag  = asmStorageAccount;
                    parentNode.Nodes.Add(tnStorageAccount);
                    parentNode.Expand();
                }

                List <AsmCloudService> asmCloudServices = await _AzureContextSourceASM.AzureRetriever.GetAzureAsmCloudServices();

                foreach (AsmCloudService asmCloudService in asmCloudServices)
                {
                    foreach (AsmVirtualMachine asmVirtualMachine in asmCloudService.VirtualMachines)
                    {
                        TreeNode   parentNode             = GetDataCenterTreeViewNode(subscriptionNode, asmCloudService.Location, "Cloud Services");
                        TreeNode[] cloudServiceNodeSearch = parentNode.Nodes.Find(asmCloudService.ServiceName, false);
                        TreeNode   cloudServiceNode       = null;
                        if (cloudServiceNodeSearch.Count() == 1)
                        {
                            cloudServiceNode = cloudServiceNodeSearch[0];
                        }

                        if (cloudServiceNode == null)
                        {
                            cloudServiceNode      = new TreeNode(asmCloudService.ServiceName);
                            cloudServiceNode.Name = asmCloudService.ServiceName;
                            cloudServiceNode.Tag  = asmCloudService;
                            parentNode.Nodes.Add(cloudServiceNode);
                            parentNode.Expand();
                        }

                        TreeNode virtualMachineNode = new TreeNode(asmVirtualMachine.RoleName);
                        virtualMachineNode.Name = asmVirtualMachine.RoleName;
                        virtualMachineNode.Tag  = asmVirtualMachine;
                        cloudServiceNode.Nodes.Add(virtualMachineNode);
                        cloudServiceNode.Expand();
                    }
                }

                foreach (AsmNetworkSecurityGroup asmNetworkSecurityGroup in await _AzureContextSourceASM.AzureRetriever.GetAzureAsmNetworkSecurityGroups())
                {
                    TreeNode parentNode       = GetDataCenterTreeViewNode(subscriptionNode, asmNetworkSecurityGroup.Location, "Network Security Groups");
                    TreeNode tnStorageAccount = new TreeNode(asmNetworkSecurityGroup.Name);
                    tnStorageAccount.Name = tnStorageAccount.Text;
                    tnStorageAccount.Tag  = asmNetworkSecurityGroup;
                    parentNode.Nodes.Add(tnStorageAccount);
                    parentNode.Expand();
                }

                subscriptionNode.ExpandAll();
                await ReadSubscriptionSettings(sender.AzureSubscription);

                treeARM.Enabled = true;
                treeASM.Enabled = true;
            }

            _statusProvider.UpdateStatus("Ready");
        }
Example #6
0
        public async Task <AzureRestResponse> GetAzureRestResponse(AzureRestRequest azureRestRequest)
        {
            _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Url: " + azureRestRequest.Url);

            if (azureRestRequest.UseCached && _RestApiCache.ContainsKey(azureRestRequest.Url))
            {
                _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Using Cached Response");
                _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " End REST Request");
                AzureRestResponse cachedRestResponse = (AzureRestResponse)_RestApiCache[azureRestRequest.Url];
                return(cachedRestResponse);
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(azureRestRequest.Url);

            request.Method = azureRestRequest.Method;

            if (azureRestRequest.AccessToken != String.Empty)
            {
                string authorizationHeader = "Bearer " + azureRestRequest.AccessToken;
                request.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
                writeRetreiverResultToLog(azureRestRequest.RequestGuid, "GetAzureRestResponse", azureRestRequest.Url, authorizationHeader);
            }

            if (request.Method == "POST")
            {
                request.ContentLength = 0;
            }

            foreach (String headerKey in azureRestRequest.Headers.Keys)
            {
                request.Headers.Add(headerKey, azureRestRequest.Headers[headerKey]);
            }

            string webRequesetResult = String.Empty;

            try
            {
                _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " " + azureRestRequest.Method + " " + azureRestRequest.Url);

                // Retry Guidlines for 500 series with Backoff Timer - https://msdn.microsoft.com/en-us/library/azure/jj878112.aspx  https://msdn.microsoft.com/en-us/library/azure/gg185909.aspx
                HttpWebResponse response             = null;
                const Int32     maxRetrySecond       = 32;
                Int32           retrySeconds         = 1;
                bool            boolRetryGetResponse = true;
                while (boolRetryGetResponse)
                {
                    try
                    {
                        response = (HttpWebResponse)await request.GetResponseAsync();

                        boolRetryGetResponse = false;
                    }
                    catch (WebException webException)
                    {
                        _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " EXCEPTION " + webException.Message);

                        HttpWebResponse exceptionResponse = (HttpWebResponse)webException.Response;

                        if (exceptionResponse != null)
                        {
                            _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " EXCEPTION HttpWebResponse Status Code: " + exceptionResponse.StatusCode);

                            if (
                                (int)exceptionResponse.StatusCode == 429 || // 429 Too Many Requests
                                ((int)exceptionResponse.StatusCode >= 500 && (int)exceptionResponse.StatusCode <= 599)
                                )
                            {
                                DateTime sleepUntil   = DateTime.Now.AddSeconds(retrySeconds);
                                string   sleepMessage = "Sleeping for " + retrySeconds.ToString() + " second(s) (until " + sleepUntil.ToString() + ") before web request retry.";

                                _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " " + sleepMessage);
                                _StatusProvider.UpdateStatus(sleepMessage);
                                while (DateTime.Now < sleepUntil)
                                {
                                    Application.DoEvents();
                                }
                                retrySeconds = retrySeconds * 2;

                                if (retrySeconds > maxRetrySecond)
                                {
                                    _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Too many retry.");
                                    _StatusProvider.UpdateStatus("Too many retry.");
                                    throw webException;
                                    // too many retry -> throw exception
                                }

                                _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " Initiating retry of Web Request.");
                                _StatusProvider.UpdateStatus("Initiating retry of Web Request.");
                            }
                            else if (exceptionResponse.StatusCode == HttpStatusCode.Conflict)
                            {
                                boolRetryGetResponse = false;
                            }
                            else
                            {
                                throw webException;
                            }
                        }
                        else
                        {
                            throw webException;
                        }
                    }
                    catch (Exception exc)
                    {
                        // todo?
                    }
                }

                if (response != null)
                {
                    _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + "  Status Code " + response.StatusCode);

                    webRequesetResult = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    writeRetreiverResultToLog(azureRestRequest.RequestGuid, "GetAzureRestResponse", azureRestRequest.Url, webRequesetResult);
                }
            }
            catch (Exception exception)
            {
                _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + azureRestRequest.Url + "  EXCEPTION " + exception.Message);
                throw exception;
            }

            _LogProvider.WriteLog("GetAzureRestResponse", azureRestRequest.RequestGuid.ToString() + " End REST Request");

            AzureRestResponse azureRestResponse = new AzureRestResponse(azureRestRequest, webRequesetResult);

            if (!_RestApiCache.ContainsKey(azureRestRequest.Url))
            {
                _RestApiCache.Add(azureRestRequest.Url, azureRestResponse);
            }

            OnRestResult?.Invoke(azureRestResponse);

            return(azureRestResponse);
        }
Example #7
0
        public async Task BindArmResources(AzureContext azureContext, AzureSubscription azureSubscription, TargetSettings targetSettings)
        {
            treeAzureARM.Nodes.Clear();

            try
            {
                if (azureSubscription != null)
                {
                    await azureSubscription.BindArmResources(targetSettings);

                    if (azureSubscription != null)
                    {
                        TreeNode subscriptionNodeARM = new TreeNode(azureSubscription.Name);
                        subscriptionNodeARM.ImageKey         = "Subscription";
                        subscriptionNodeARM.SelectedImageKey = "Subscription";
                        treeAzureARM.Nodes.Add(subscriptionNodeARM);
                        subscriptionNodeARM.Expand();

                        foreach (MigrationTarget.NetworkSecurityGroup targetNetworkSecurityGroup in azureSubscription.ArmTargetNetworkSecurityGroups)
                        {
                            TreeNode networkSecurityGroupParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.NetworkSecurityGroup)targetNetworkSecurityGroup.SourceNetworkSecurityGroup).ResourceGroup);

                            TreeNode tnNetworkSecurityGroup = new TreeNode(targetNetworkSecurityGroup.SourceName);
                            tnNetworkSecurityGroup.Name             = targetNetworkSecurityGroup.SourceName;
                            tnNetworkSecurityGroup.Tag              = targetNetworkSecurityGroup;
                            tnNetworkSecurityGroup.ImageKey         = targetNetworkSecurityGroup.ImageKey;
                            tnNetworkSecurityGroup.SelectedImageKey = targetNetworkSecurityGroup.ImageKey;
                            networkSecurityGroupParentNode.Nodes.Add(tnNetworkSecurityGroup);
                        }

                        foreach (MigrationTarget.PublicIp targetPublicIP in azureSubscription.ArmTargetPublicIPs)
                        {
                            TreeNode publicIpParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.PublicIP)targetPublicIP.Source).ResourceGroup);;

                            TreeNode tnPublicIP = new TreeNode(targetPublicIP.SourceName);
                            tnPublicIP.Name             = targetPublicIP.SourceName;
                            tnPublicIP.Tag              = targetPublicIP;
                            tnPublicIP.ImageKey         = targetPublicIP.ImageKey;
                            tnPublicIP.SelectedImageKey = targetPublicIP.ImageKey;
                            publicIpParentNode.Nodes.Add(tnPublicIP);
                        }

                        foreach (MigrationTarget.RouteTable targetRouteTable in azureSubscription.ArmTargetRouteTables)
                        {
                            TreeNode routeTableParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.RouteTable)targetRouteTable.Source).ResourceGroup);

                            TreeNode tnRouteTable = new TreeNode(targetRouteTable.SourceName);
                            tnRouteTable.Name             = targetRouteTable.SourceName;
                            tnRouteTable.Tag              = targetRouteTable;
                            tnRouteTable.ImageKey         = targetRouteTable.ImageKey;
                            tnRouteTable.SelectedImageKey = targetRouteTable.ImageKey;
                            routeTableParentNode.Nodes.Add(tnRouteTable);
                        }

                        foreach (MigrationTarget.VirtualNetwork targetVirtualNetwork in azureSubscription.ArmTargetVirtualNetworks)
                        {
                            TreeNode virtualNetworkParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualNetwork)targetVirtualNetwork.SourceVirtualNetwork).ResourceGroup);

                            TreeNode tnVirtualNetwork = new TreeNode(targetVirtualNetwork.SourceName);
                            tnVirtualNetwork.Name             = targetVirtualNetwork.SourceName;
                            tnVirtualNetwork.Tag              = targetVirtualNetwork;
                            tnVirtualNetwork.ImageKey         = targetVirtualNetwork.ImageKey;
                            tnVirtualNetwork.SelectedImageKey = targetVirtualNetwork.ImageKey;
                            virtualNetworkParentNode.Nodes.Add(tnVirtualNetwork);
                        }

                        foreach (MigrationTarget.VirtualNetworkGateway targetVirtualNetworkGateway in azureSubscription.ArmTargetVirtualNetworkGateways)
                        {
                            TreeNode virtualNetworkGatewayParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualNetworkGateway)targetVirtualNetworkGateway.SourceVirtualNetworkGateway).ResourceGroup);

                            TreeNode tnVirtualNetworkGateway = new TreeNode(targetVirtualNetworkGateway.SourceName);
                            tnVirtualNetworkGateway.Name             = targetVirtualNetworkGateway.SourceName;
                            tnVirtualNetworkGateway.Tag              = targetVirtualNetworkGateway;
                            tnVirtualNetworkGateway.ImageKey         = targetVirtualNetworkGateway.ImageKey;
                            tnVirtualNetworkGateway.SelectedImageKey = targetVirtualNetworkGateway.ImageKey;
                            virtualNetworkGatewayParentNode.Nodes.Add(tnVirtualNetworkGateway);
                        }

                        foreach (MigrationTarget.LocalNetworkGateway targetLocalNetworkGateway in azureSubscription.ArmTargetLocalNetworkGateways)
                        {
                            TreeNode localNetworkGatewayParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.LocalNetworkGateway)targetLocalNetworkGateway.SourceLocalNetworkGateway).ResourceGroup);

                            TreeNode tnLocalNetworkGateway = new TreeNode(targetLocalNetworkGateway.SourceName);
                            tnLocalNetworkGateway.Name             = targetLocalNetworkGateway.SourceName;
                            tnLocalNetworkGateway.Tag              = targetLocalNetworkGateway;
                            tnLocalNetworkGateway.ImageKey         = targetLocalNetworkGateway.ImageKey;
                            tnLocalNetworkGateway.SelectedImageKey = targetLocalNetworkGateway.ImageKey;
                            localNetworkGatewayParentNode.Nodes.Add(tnLocalNetworkGateway);
                        }

                        foreach (MigrationTarget.VirtualNetworkGatewayConnection targetConnection in azureSubscription.ArmTargetConnections)
                        {
                            TreeNode connectionParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualNetworkGatewayConnection)targetConnection.SourceConnection).ResourceGroup);

                            TreeNode tnConnection = new TreeNode(targetConnection.SourceName);
                            tnConnection.Name             = targetConnection.SourceName;
                            tnConnection.Tag              = targetConnection;
                            tnConnection.ImageKey         = targetConnection.ImageKey;
                            tnConnection.SelectedImageKey = targetConnection.ImageKey;
                            connectionParentNode.Nodes.Add(tnConnection);
                        }

                        foreach (MigrationTarget.StorageAccount targetStorageAccount in azureSubscription.ArmTargetStorageAccounts)
                        {
                            TreeNode storageAccountParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.StorageAccount)targetStorageAccount.SourceAccount).ResourceGroup);

                            TreeNode tnStorageAccount = new TreeNode(targetStorageAccount.SourceName);
                            tnStorageAccount.Name             = targetStorageAccount.SourceName;
                            tnStorageAccount.Tag              = targetStorageAccount;
                            tnStorageAccount.ImageKey         = targetStorageAccount.ImageKey;
                            tnStorageAccount.SelectedImageKey = targetStorageAccount.ImageKey;
                            storageAccountParentNode.Nodes.Add(tnStorageAccount);
                        }

                        foreach (MigrationTarget.Disk targetManagedDisk in azureSubscription.ArmTargetManagedDisks)
                        {
                            Azure.Arm.ManagedDisk armManagedDisk = (Azure.Arm.ManagedDisk)targetManagedDisk.SourceDisk;
                            TreeNode managedDiskParentNode       = GetResourceGroupTreeNode(subscriptionNodeARM, armManagedDisk.ResourceGroup);

                            TreeNode tnDisk = new TreeNode(targetManagedDisk.SourceName);
                            tnDisk.Name             = targetManagedDisk.SourceName;
                            tnDisk.Tag              = targetManagedDisk;
                            tnDisk.ImageKey         = targetManagedDisk.ImageKey;
                            tnDisk.SelectedImageKey = targetManagedDisk.ImageKey;
                            managedDiskParentNode.Nodes.Add(tnDisk);
                        }

                        foreach (MigrationTarget.AvailabilitySet targetAvailabilitySet in azureSubscription.ArmTargetAvailabilitySets)
                        {
                            TreeNode availabilitySetParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.AvailabilitySet)targetAvailabilitySet.SourceAvailabilitySet).ResourceGroup);

                            TreeNode tnAvailabilitySet = new TreeNode(targetAvailabilitySet.SourceName);
                            tnAvailabilitySet.Name             = targetAvailabilitySet.SourceName;
                            tnAvailabilitySet.Tag              = targetAvailabilitySet;
                            tnAvailabilitySet.ImageKey         = targetAvailabilitySet.ImageKey;
                            tnAvailabilitySet.SelectedImageKey = targetAvailabilitySet.ImageKey;
                            availabilitySetParentNode.Nodes.Add(tnAvailabilitySet);
                        }

                        foreach (MigrationTarget.NetworkInterface targetNetworkInterface in azureSubscription.ArmTargetNetworkInterfaces)
                        {
                            TreeNode tnResourceGroup = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.NetworkInterface)targetNetworkInterface.SourceNetworkInterface).ResourceGroup);

                            TreeNode txNetworkInterface = new TreeNode(targetNetworkInterface.SourceName);
                            txNetworkInterface.Name             = targetNetworkInterface.SourceName;
                            txNetworkInterface.Tag              = targetNetworkInterface;
                            txNetworkInterface.ImageKey         = targetNetworkInterface.ImageKey;
                            txNetworkInterface.SelectedImageKey = targetNetworkInterface.ImageKey;
                            tnResourceGroup.Nodes.Add(txNetworkInterface);
                        }

                        foreach (MigrationTarget.VirtualMachine targetVirtualMachine in azureSubscription.ArmTargetVirtualMachines)
                        {
                            TreeNode tnResourceGroup = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualMachine)targetVirtualMachine.Source).ResourceGroup);

                            TreeNode tnVirtualMachine = new TreeNode(targetVirtualMachine.SourceName);
                            tnVirtualMachine.Name             = targetVirtualMachine.SourceName;
                            tnVirtualMachine.Tag              = targetVirtualMachine;
                            tnVirtualMachine.ImageKey         = targetVirtualMachine.ImageKey;
                            tnVirtualMachine.SelectedImageKey = targetVirtualMachine.ImageKey;
                            tnResourceGroup.Nodes.Add(tnVirtualMachine);
                        }

                        foreach (MigrationTarget.LoadBalancer targetLoadBalancer in azureSubscription.ArmTargetLoadBalancers)
                        {
                            TreeNode networkSecurityGroupParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.LoadBalancer)targetLoadBalancer.Source).ResourceGroup);

                            TreeNode tnNetworkSecurityGroup = new TreeNode(targetLoadBalancer.SourceName);
                            tnNetworkSecurityGroup.Name             = targetLoadBalancer.SourceName;
                            tnNetworkSecurityGroup.Tag              = targetLoadBalancer;
                            tnNetworkSecurityGroup.ImageKey         = targetLoadBalancer.ImageKey;
                            tnNetworkSecurityGroup.SelectedImageKey = targetLoadBalancer.ImageKey;
                            networkSecurityGroupParentNode.Nodes.Add(tnNetworkSecurityGroup);
                        }

                        //foreach (MigrationTarget.VirtualMachineImage targetVirtualMachineImage in _AzureContextSource.AzureSubscription.ArmTargetVirtualMachineImages)
                        //{
                        //    TreeNode virtualMachineImageParentNode = GetResourceGroupTreeNode(subscriptionNodeARM, ((Azure.Arm.VirtualMachineImage)targetVirtualMachineImage.Source).ResourceGroup);

                        //    TreeNode tnVirtualMachineImage = new TreeNode(targetVirtualMachineImage.SourceName);
                        //    tnVirtualMachineImage.Name = targetVirtualMachineImage.SourceName;
                        //    tnVirtualMachineImage.Tag = targetVirtualMachineImage;
                        //    tnVirtualMachineImage.ImageKey = "VirtualMachineImage";
                        //    tnVirtualMachineImage.SelectedImageKey = "VirtualMachineImage";
                        //    virtualMachineImageParentNode.Nodes.Add(tnVirtualMachineImage);
                        //}

                        subscriptionNodeARM.Expand();
                        treeAzureARM.Sort();
                        treeAzureARM.Enabled = true;
                    }
                }
            }
            catch (Exception exc)
            {
                UnhandledExceptionDialog exceptionDialog = new UnhandledExceptionDialog(_LogProvider, exc);
                exceptionDialog.ShowDialog();
            }

            _StatusProvider.UpdateStatus("Ready");
        }
Example #8
0
        public virtual XmlDocument GetAzureASMResources(string resourceType, string subscriptionId, Hashtable info, string token)
        {
            _logProvider.WriteLog("GetAzureASMResources", "Start");

            string url = null;

            switch (resourceType)
            {
            case "Subscriptions":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions";
                _statusProvider.UpdateStatus("BUSY: Getting Subscriptions...");
                break;

            case "VirtualNetworks":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/virtualnetwork";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Networks for Subscription ID : " + subscriptionId + "...");
                break;

            case "ClientRootCertificates":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway/clientrootcertificates";
                _statusProvider.UpdateStatus("BUSY: Getting Client Root Certificates for Virtual Network : " + info["virtualnetworkname"] + "...");
                break;

            case "ClientRootCertificate":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway/clientrootcertificates/" + info["thumbprint"];
                _statusProvider.UpdateStatus("BUSY: Getting certificate data for certificate : " + info["thumbprint"] + "...");
                break;

            case "NetworkSecurityGroup":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/networksecuritygroups/" + info["name"] + "?detaillevel=Full";
                _statusProvider.UpdateStatus("BUSY: Getting Network Security Group : " + info["name"] + "...");
                break;

            case "RouteTable":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/routetables/" + info["name"] + "?detailLevel=full";
                _statusProvider.UpdateStatus("BUSY: Getting Route Table : " + info["routetablename"] + "...");
                break;

            case "NSGSubnet":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/virtualnetwork/" + info["virtualnetworkname"] + "/subnets/" + info["subnetname"] + "/networksecuritygroups";
                _statusProvider.UpdateStatus("BUSY: Getting NSG for subnet " + info["subnetname"] + "...");
                break;

            case "VirtualNetworkGateway":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Network Gateway : " + info["virtualnetworkname"] + "...");
                break;

            case "VirtualNetworkGatewaySharedKey":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway/connection/" + info["localnetworksitename"] + "/sharedkey";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Network Gateway Shared Key: " + info["localnetworksitename"] + "...");
                break;

            case "StorageAccounts":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/storageservices";
                _statusProvider.UpdateStatus("BUSY: Getting Storage Accounts for Subscription ID : " + subscriptionId + "...");
                break;

            case "StorageAccount":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/storageservices/" + info["name"];
                _statusProvider.UpdateStatus("BUSY: Getting Storage Accounts for Subscription ID : " + subscriptionId + "...");
                break;

            case "StorageAccountKeys":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/storageservices/" + info["name"] + "/keys";
                _statusProvider.UpdateStatus("BUSY: Getting Storage Accounts for Subscription ID : " + subscriptionId + "...");
                break;

            case "CloudServices":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/hostedservices";
                _statusProvider.UpdateStatus("BUSY: Getting Cloud Services for Subscription ID : " + subscriptionId + "...");
                break;

            case "CloudService":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/hostedservices/" + info["name"] + "?embed-detail=true";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Machines for Cloud Service : " + info["name"] + "...");
                break;

            case "VirtualMachine":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/hostedservices/" + info["cloudservicename"] + "/deployments/" + info["deploymentname"] + "/roles/" + info["virtualmachinename"];
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Machines for Cloud Service : " + info["virtualmachinename"] + "...");
                break;

            case "VMImages":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/images";
                break;

            case "ReservedIPs":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/reservedips";
                break;

            case "AffinityGroup":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/affinitygroups/" + info["affinitygroupname"];
                break;
            }

            Application.DoEvents();

            _logProvider.WriteLog("GetAzureASMResources", "GET " + url);

            if (_documentCache.ContainsKey(url))
            {
                _logProvider.WriteLog("GetAzureASMResources", "FROM XML CACHE");
                _logProvider.WriteLog("GetAzureASMResources", "End");
                writeXMLtoFile(url, "Cached");
                return(_documentCache[url]);
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
            request.Headers.Add("x-ms-version", "2015-04-01");
            request.Method = "GET";


            string xml = "";

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                xml = new StreamReader(response.GetResponseStream()).ReadToEnd();
                _logProvider.WriteLog("GetAzureASMResources", "RESPONSE " + response.StatusCode);
            }
            catch (Exception exception)
            {
                _logProvider.WriteLog("GetAzureASMResources", "EXCEPTION " + exception.Message);
                DialogResult dialogresult = MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                xml = "";
                //Application.ExitThread();
            }

            if (xml != "")
            {
                XmlDocument xmlDoc = RemoveXmlns(xml);

                _logProvider.WriteLog("GetAzureASMResources", "End");
                writeXMLtoFile(url, xml);

                _documentCache.Add(url, xmlDoc);
                return(xmlDoc);
            }
            else
            {
                //XmlNodeList xmlnode = null;
                //return xmlnode;
                XmlDocument xmlDoc = new XmlDocument();

                _logProvider.WriteLog("GetAzureASMResources", "End");
                writeXMLtoFile(url, "");
                return(null);
            }
        }
Example #9
0
        public virtual string GetAzureARMResources(string resourceType, string subscriptionId, Hashtable info, string token, string RGName)
        {
            _logProvider.WriteLog("GetAzureARMResources", "Start");

            string url = null;

            switch (resourceType)
            {
            case "Subscriptions":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions?api-version=2015-01-01";
                _statusProvider.UpdateStatus("BUSY: Getting Subscriptions...");
                break;

            case "Tenants":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "tenants?api-version=2015-01-01";
                _statusProvider.UpdateStatus("BUSY: Getting Tenants...");
                break;

            case "RG":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourcegroups?api-version=2015-01-01";
                _statusProvider.UpdateStatus("BUSY: Getting Resource Groups...");
                break;

            case "VirtualNetworks":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Network/virtualnetworks?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Networks for Subscription ID : " + subscriptionId + " in the Resource Group " + RGName + "...");
                break;

            case "VirtualNetwork":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["VirtualNWId"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Network details...");
                break;

            case "VirtualMachines":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Compute/virtualMachines?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Machines for Subscription ID : " + subscriptionId + " in the Resource Group " + RGName + "...");
                break;

            case "VirtualMachine":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Compute/virtualMachines/" + info["virtualmachineName"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Machine for Subscription ID : " + subscriptionId + " in the Resource Group " + RGName + "...");
                break;

            case "NetworkInterface":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["networkinterfaceId"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Network Interface details...");
                break;

            case "Loadbalancer":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["LBId"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting LoadBalancer details...");
                break;

            case "NetworkSecurityGroup":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["NetworkSecurityGroup"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Network Security Group : " + info["name"] + "...");
                break;

            case "RouteTable":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["RouteTable"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Route Table : " + info["routetablename"] + "...");
                break;

            case "Subnet":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["SubnetId"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Subnet details : " + info["SubnetId"] + "...");
                break;

            case "AvailabilitySet":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["AvailId"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Availability Set details : " + info["AvailId"] + "...");
                break;

            case "VirtualNetworkGateway":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + info["RGName"] + "/providers/Microsoft.Network/virtualNetworkGateways/" + info["vnetGWName"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Network Gateway : " + info["vnetGWName"] + "...");
                break;

            case "PublicIP":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["publicipId"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting PublicIP details...");
                break;

            case "Connections":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Network/connections?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting Connections from the Resource Group : " + RGName + "...");
                break;

            case "Domains":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.GraphAuth) + "myorganization/domains?api-version=1.6";
                _statusProvider.UpdateStatus("BUSY: Getting Tenant Domain details from Graph...");
                break;

            case "sharedkey":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["connectionid"] + "/sharedkey?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting SharedKey details...");
                break;

            case "localNetworkGateway":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + info["localnwgwid"] + "?api-version=2016-03-30";
                _statusProvider.UpdateStatus("BUSY: Getting LocalNWGateway details...");
                break;

            case "ClientRootCertificates":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway/clientrootcertificates";
                _statusProvider.UpdateStatus("BUSY: Getting Client Root Certificates for Virtual Network : " + info["virtualnetworkname"] + "...");
                break;

            case "ClientRootCertificate":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway/clientrootcertificates/" + info["thumbprint"];
                _statusProvider.UpdateStatus("BUSY: Getting certificate data for certificate : " + info["thumbprint"] + "...");
                break;

            case "NSGSubnet":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/virtualnetwork/" + info["virtualnetworkname"] + "/subnets/" + info["subnetname"] + "/networksecuritygroups";
                _statusProvider.UpdateStatus("BUSY: Getting NSG for subnet " + info["subnetname"] + "...");
                break;

            case "VirtualNetworkGatewaySharedKey":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/" + info["virtualnetworkname"] + "/gateway/connection/" + info["localnetworksitename"] + "/sharedkey";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Network Gateway Shared Key: " + info["localnetworksitename"] + "...");
                break;

            case "StorageAccounts":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Storage/storageAccounts?api-version=2015-05-01-preview";
                _statusProvider.UpdateStatus("BUSY: Getting Storage Accounts for Subscription ID : " + subscriptionId + " in the Resource Group " + RGName + "...");
                break;

            case "StorageAccount":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Storage/storageAccounts/" + info["name"] + "?api-version=2015-05-01-preview";
                _statusProvider.UpdateStatus("BUSY: Getting Storage Accounts for Subscription ID : " + subscriptionId + "...");
                break;

            case "StorageAccountKeys":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + "subscriptions/" + subscriptionId + "/resourceGroups/" + RGName + "/providers/Microsoft.Storage/storageAccounts/" + info["name"] + "/listKeys?api-version=2016-01-01";
                _statusProvider.UpdateStatus("BUSY: Getting Storage Accounts for Subscription ID : " + subscriptionId + "...");
                break;

            case "CloudServices":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/hostedservices";
                _statusProvider.UpdateStatus("BUSY: Getting Cloud Services for Subscription ID : " + subscriptionId + "...");
                break;

            case "CloudService":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/hostedservices/" + info["name"] + "?embed-detail=true";
                _statusProvider.UpdateStatus("BUSY: Getting Virtual Machines for Cloud Service : " + info["name"] + "...");
                break;

            case "VMImages":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/images";
                break;

            case "ReservedIPs":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/services/networking/reservedips";
                break;

            case "AffinityGroup":
                url = ServiceUrls.GetServiceManagementUrl(app.Default.AzureEnvironment) + subscriptionId + "/affinitygroups/" + info["affinitygroupname"];
                break;
            }

            Application.DoEvents();

            _logProvider.WriteLog("GetAzureARMResources", "GET " + url);


            if (_documentCache.ContainsKey(url))
            {
                _logProvider.WriteLog("GetAzureARMResources", "FROM XML CACHE");
                _logProvider.WriteLog("GetAzureARMResources", "End");
                writeXMLtoFile(url, "Cached");
                return(_documentCache[url]);
            }


            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
            request.ContentType = "application/json";
            // request.Headers.Add("x-ms-version", "2015-04-01");
            if (resourceType == "StorageAccountKeys")
            {
                request.Method        = "POST";
                request.ContentLength = 0;
            }
            else
            {
                request.Method = "GET";
            }
            string json = "";

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                json = new StreamReader(response.GetResponseStream()).ReadToEnd();
                _logProvider.WriteLog("GetAzureARMResources", "RESPONSE " + response.StatusCode);

                /*
                 * using (var streamReader = new StreamReader(response.GetResponseStream()))
                 * {
                 *   result = streamReader.ReadToEnd();
                 * }
                 */
            }
            catch (Exception exception)
            {
                _logProvider.WriteLog("GetAzureARMResources", "EXCEPTION " + exception.Message);
                DialogResult dialogresult = MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                json = "";
                //Application.ExitThread();
            }

            if (json != "")
            {
                _logProvider.WriteLog("GetAzureARMResources", "End");
                writeXMLtoFile(url, json);

                if ((resourceType != "Subscriptions") && (resourceType != "Domains"))
                {
                    _documentCache.Add(url, json);
                }

                return(json);
            }
            else
            {
                _logProvider.WriteLog("GetAzureARMResources", "End");
                writeXMLtoFile(url, "");
                return(null);
            }
        }
Example #10
0
        public void toname(string accessKey, string secretKey, TreeNode subscriptionNode, ILogProvider logProvider, IStatusProvider statusProvider)
        {
            List <Amazon.RegionEndpoint> regionsList = new List <Amazon.RegionEndpoint>();

            foreach (var region in Amazon.RegionEndpoint.EnumerableAllRegions)
            {
                try
                {
                    _awsObjectRetriever = new AwsObjectRetriever(accessKey, secretKey, region, logProvider, statusProvider);
                    //// todo, not needed in this method_templateGenerator = new TemplateGenerator(_logProvider, _statusProvider, _awsObjectRetriever, telemetryProvider);

                    TreeNode amazonRegionNode = new TreeNode(region.DisplayName);
                    amazonRegionNode.Text = region.DisplayName;
                    amazonRegionNode.Tag  = region;

                    //DescribeVolumesResponse ebsVolumesResponse;

                    statusProvider.UpdateStatus("BUSY: Getting the VPC details");
                    DescribeVpcsResponse vpcResponse = getVPCs();
                    Application.DoEvents();

                    statusProvider.UpdateStatus("BUSY: Processing VPC");
                    foreach (var vpc in vpcResponse.Vpcs)
                    {
                        MigAz.AWS.MigrationSource.VirtualNetwork sourceVirtualNetwork = new MigrationSource.VirtualNetwork(_awsObjectRetriever, vpc);
                        Azure.MigrationTarget.VirtualNetwork     targetVirtualNetwork = new Azure.MigrationTarget.VirtualNetwork(sourceVirtualNetwork);

                        TreeNode vpcTreeNode = new TreeNode(sourceVirtualNetwork.Id + " - " + sourceVirtualNetwork.Name);
                        vpcTreeNode.Tag = targetVirtualNetwork;
                        amazonRegionNode.Nodes.Add(vpcTreeNode);

                        Application.DoEvents();
                    }

                    DescribeInstancesResponse instResponse = getEC2Instances();
                    Application.DoEvents();

                    if (instResponse != null)
                    {
                        statusProvider.UpdateStatus("BUSY: Processing Instances");
                        if (instResponse.Reservations.Count > 0)
                        {
                            foreach (var instanceResp in instResponse.Reservations)
                            {
                                foreach (var instance in instanceResp.Instances)
                                {
                                    string name = "";
                                    foreach (var tag in instance.Tags)
                                    {
                                        if (tag.Key == "Name")
                                        {
                                            name = tag.Value;
                                        }
                                    }

                                    TreeNode instanceTreeNode = new TreeNode(instance.InstanceId + " - " + name);
                                    instanceTreeNode.Tag = instance;
                                    amazonRegionNode.Nodes.Add(instanceTreeNode);

                                    Application.DoEvents();
                                }
                            }
                        }
                    }



                    if (amazonRegionNode.Nodes.Count > 0)
                    {
                        subscriptionNode.Nodes.Add(amazonRegionNode);
                    }
                    else
                    {
                        logProvider.WriteLog("Load_Items", "Not adding Amazon Region '" + region.DisplayName + "' to Source Node list, as it contains no resources to export.");
                    }
                }
                catch (Exception exc)
                {
                    logProvider.WriteLog("Load_Items", "AWS Exception - " + region.DisplayName + ": " + exc.Message);
                }
            }
        }