private void ValidateLogicalNetwork(LogicalNetwork logicalNetwork)
        {
            FabricCommon.ValidateResource(logicalNetwork);

            Assert.NotNull(logicalNetwork.NetworkVirtualizationEnabled);
            Assert.NotNull(logicalNetwork.Subnets);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create default LogicalNetwork and add to configuration.
        /// </summary>
        /// <param name="logicalNetworkConfig">FabricNetworkConfig instance.</param>
        public void CreateHNVLogicalNetwork(LogicalNetworkConfig logicalNetworkConfig)
        {
            // Verify arguments.
            if (logicalNetworkConfig == null)
            {
                return;
            }

            if (logicalNetworkConfig.GetLogicalNetworkById(HNVODLConstants.LOGICAL_NETWORK.LOGICALNETWORK_ID) != null)
            {
                // If exists, nothing to do.
                return;
            }

            ODLVSEMETW.EventWriteGetHNVLogicalNetworkNotFound(MethodBase.GetCurrentMethod().Name,
                                                              string.Format("Create LogicalNetwork that Guid is {0}", HNVODLConstants.LOGICAL_NETWORK.LOGICALNETWORK_ID));

            // Create LogicalNetwork instance.
            var logicalNetwork = new LogicalNetwork()
            {
                AreLogicalNetworkDefinitionsIsolated =
                    HNVODLConstants.LOGICAL_NETWORK.ARE_LOGICALNETWORK_DEFINITIONS_ISOLATED,
                Description               = HNVODLConstants.LOGICAL_NETWORK.DESCRIPTION,
                Id                        = HNVODLConstants.LOGICAL_NETWORK.LOGICALNETWORK_ID,
                LastModifiedTimeStamp     = DateTime.Now,
                LogicalNetworkDefinitions = new LogicalNetworkDefinition[1],
                Name                      = string.Format(HNVODLConstants.LOGICAL_NETWORK.NAME, this.VtnHostName)
            };

            logicalNetwork.LogicalNetworkDefinitions[0] = this.CreateDefaultLogicalNetworkDefinition();

            // Add created logical network to the configuration.
            logicalNetworkConfig.LogicalNetworks.Add(logicalNetwork);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Validate whether the specified LogicalNetwork is correct configuration or not.
        /// </summary>
        /// <param name="logicalNetwork">LogicalNetwork instance.</param>
        /// <returns>True if correct configuraton or not HNV resource, else false.</returns>
        public bool IsLogicalNetworkValid(LogicalNetwork logicalNetwork)
        {
            if (logicalNetwork == null)
            {
                return(false);
            }

            // IsHNV check.
            if (this.IsHNVLogicalNetwork(logicalNetwork) == false)
            {
                // Not HNV resource.
                return(true);
            }

            // Validate NetworkSites.
            bool ret;

            ret = this.IsLogicalNetworkDefinitionsValid(logicalNetwork);

            if (ret == false)
            {
                ODLVSEMETW.EventWriteValidateLogicalNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format("LogicalNetwork name is {0}", logicalNetwork.Name));
            }

            return(ret);
        }
        private void AssertLogicalNetworksAreSame(LogicalNetwork expected, LogicalNetwork found)
        {
            if (expected == null)
            {
                Assert.Null(found);
            }
            else
            {
                Assert.True(FabricCommon.ResourceAreSame(expected, found));

                Assert.Equal(expected.NetworkVirtualizationEnabled, found.NetworkVirtualizationEnabled);
                if (expected.Subnets != null)
                {
                    Assert.Equal(expected.Subnets.Count, found.Subnets.Count);
                }
                else
                {
                    Assert.Null(found.Subnets);
                }

                if (expected.Metadata != null)
                {
                    Assert.Equal(expected.Metadata.Count, found.Metadata.Count);
                }
                else
                {
                    Assert.Null(found.Metadata);
                }
            }
        }
        internal static LogicalNetwork CreateNetwork(LogicalNetworkFactory factory, IEnumerable<LogicalNetworkGene> geneSequence)
        {
            int nodeIndex = 0;
            int lastNodeIndex = -1;
            var uppers = new List<LogicalConnectionGene>();
            var lowers = new List<LogicalConnectionGene>();

            foreach (var gene in geneSequence)
            {
                var connGene = gene as LogicalConnectionGene;
                if (connGene != null)
                {
                    if (connGene.IsUpper) uppers.Add(connGene); else lowers.Add(connGene);
                }
                else
                {
                    var nodeGene = (LogicalNodeGene)gene;
                    nodeIndex = nodeGene.Index;
                    foreach (var ucg in uppers)
                    {
                        int uni = nodeIndex + ucg.Index;
                        if (uni >= 0)
                        {
                            var connIndex = new ConnectionIndex(uni, nodeIndex);
                            factory.TryAddConnectionFactory(connIndex, new Factory<ComputationalConnection<bool>>(ucg.CreateConnection));
                        }
                    }
                    if (lastNodeIndex != -1)
                    {
                        foreach (var lcg in lowers)
                        {
                            int lni = lastNodeIndex + lcg.Index;
                            if (lni >= 0)
                            {
                                var connIndex = new ConnectionIndex(lastNodeIndex, lni);
                                factory.TryAddConnectionFactory(connIndex, new Factory<ComputationalConnection<bool>>(lcg.CreateConnection));
                            }
                        }
                    }
                    factory.TryAddNodeFactory(nodeIndex, new Factory<ComputationalNode<bool>>(nodeGene.CreateNode));
                    lastNodeIndex = nodeIndex;
                    uppers.Clear();
                    lowers.Clear();
                }
            }

            var network = new LogicalNetwork(factory);
            return network;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Update the existing logical network.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="logicalNetwork">Updated logical network.</param>
        public void UpdateLogicalNetwork(TransactionManager txnMng, LogicalNetwork logicalNetwork)
        {
            var logicalNetworkConfig = new LogicalNetworkConfig(this.VtnHostName);

            txnMng.SetConfigManager(logicalNetworkConfig, TransactionManager.OpenMode.WriteMode);

            int target;

            target = logicalNetworkConfig.ReplaceLogicalNetwork(logicalNetwork);
            if (target == -1)
            {
                ODLVSEMETW.EventWriteGetHNVLogicalNetworkNotFound(MethodBase.GetCurrentMethod().Name,
                                                                  string.Format("LogicalNetwork name is {0}", logicalNetwork.Name));
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Replace logical network.
 /// </summary>
 /// <param name="src">Logical network instance.</param>
 /// <returns>List index if replace successfully, else -1.</returns>
 public int ReplaceLogicalNetwork(LogicalNetwork src)
 {
     if (this.LogicalNetworks != null)
     {
         int i = this.LogicalNetworks.FindIndex(nw => nw.Id == src.Id);
         if (i >= 0)
         {
             this.LogicalNetworks[i] = src;
         }
         return(i);
     }
     else
     {
         return(-1);
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Verify whether the specified LogicalNetwork is HNV resource or not.
        /// </summary>
        /// <param name="logicalNetwork">LogicalNetwork instance.</param>
        /// <returns>True if HNV resource, else false.</returns>
        public bool IsHNVLogicalNetwork(LogicalNetwork logicalNetwork)
        {
            if (logicalNetwork == null)
            {
                return(false);
            }

            LogicalNetworkDefinition tmpLogicalNetworkDefinition =
                logicalNetwork.LogicalNetworkDefinitions.FirstOrDefault(l => l.Id == HNVODLConstants.LOGICAL_NETWORK_DEFINITION.ID);

            if (tmpLogicalNetworkDefinition != null &&
                tmpLogicalNetworkDefinition.ManagedByNetworkServiceId == VSEMODLConstants.SYSTEM_INFO_ID &&
                logicalNetwork.AreLogicalNetworkDefinitionsIsolated == false)
            {
                return(true);
            }
            ODLVSEMETW.EventWriteNotHNVLogicalNetwork(MethodBase.GetCurrentMethod().Name,
                                                      string.Format("LogicalNetwork name is {0}", logicalNetwork.Name));

            return(false);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Verify whether the specified VMNetwork is HNV resource or not.
        /// </summary>
        /// <param name="vmnetwork">VMNetwork instance.</param>
        /// <returns>True if HNV resource, else false.</returns>
        public bool IsHNVVMNetwork(VMNetwork vmnetwork)
        {
            if (vmnetwork == null)
            {
                return(false);
            }

            // Create txn and read configuration.
            var txnMng = new TransactionManager();

            txnMng.StartTransaction();
            var logicalNetworkConfig = new LogicalNetworkConfig(this.VtnHostName);

            txnMng.SetConfigManager(logicalNetworkConfig, TransactionManager.OpenMode.ReadMode);

            bool ret;

            // Get LogicalNetowork that Guid equals vmnetwork.LogicalNetwork.
            LogicalNetwork logicalnetwork = logicalNetworkConfig.GetLogicalNetworkById(vmnetwork.LogicalNetwork);

            if (logicalnetwork == null)
            {
                ret = false;
                goto txnEnd;
            }

            var hnvLogicalNetworkManagement = new HNVLogicalNetworkManagement(this.VtnHostName);

            ret = hnvLogicalNetworkManagement.IsHNVLogicalNetwork(logicalnetwork);

            if (ret == false)
            {
                ODLVSEMETW.EventWriteNotHNVVMNetwork(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format("VMNetwork name is {0}", vmnetwork.Name));
            }
txnEnd:
            txnMng.EndTransaction(TransactionManager.Operation.None);
            return(ret);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Validate whether the specified LogicalNetwork.LogicalNetworkDefinitions are correct configuration or not.
        /// </summary>
        /// <param name="logicalNetwork">LogicalNetwork instance.</param>
        /// <returns>True if correct configuraton, else false.</returns>
        private bool IsLogicalNetworkDefinitionsValid(LogicalNetwork logicalNetwork)
        {
            bool ret = true;

            for (int i = 0; i < logicalNetwork.LogicalNetworkDefinitions.Length; i++)
            {
                LogicalNetworkDefinition tmpLogicalNetworkDefinition = logicalNetwork.LogicalNetworkDefinitions[i];
                if (tmpLogicalNetworkDefinition.Id == HNVODLConstants.LOGICAL_NETWORK_DEFINITION.ID)
                {
                    continue;
                }
                else
                {
                    // Invalid NetworkSite.
                    string ErrorString =
                        string.Format(HNVODLConstants.ERROR_STRING.INVALID_NETWORKSITE, tmpLogicalNetworkDefinition.Name);
                    List <string> msg = new List <string>();
                    msg.Add(ErrorString);
                    tmpLogicalNetworkDefinition.SynchronizationErrors = msg.ToArray();
                    ret = false;
                }
            }
            return(ret);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Create logical networks for HNV and non HNV openflow networks.
        /// </summary>
        /// <returns>List of LogicalNetwork instances.</returns>
        private List<LogicalNetwork> CreateLogicalNetworks()
        {
            List<LogicalNetwork> logicalNetworks = new List<LogicalNetwork>();

            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal)) {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            // Create a logical network for the non HNV OpenFlow network
            LogicalNetwork logicalNet = new LogicalNetwork();
            logicalNet.Id = VSEMODLConstants.LOGICAL_NETWORK_ID;
            logicalNet.LastModifiedTimeStamp = DateTime.Now;
            logicalNet.Name = VSEMODLConstants.LOGICAL_NETWORK_NAME;
            logicalNet.Name += VtnHostName;
            logicalNet.AreLogicalNetworkDefinitionsIsolated =
                VSEMODLConstants.LOGICAL_NETWORK_ARE_LOGICAL_NETWORK_DEFINITIONS_ISOLATED;
            logicalNet.Description = VSEMODLConstants.LOGICAL_NETWORK_DESCRIPTION;
            logicalNet.LogicalNetworkDefinitions = new LogicalNetworkDefinition[1];
            logicalNet.LogicalNetworkDefinitions[0] = new LogicalNetworkDefinition {
                AllowsIntraPortCommunication =
                    VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_ALLOWS_INTRAPORT_COMMUNICATION,
                EditableByNonOwners =
                    VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_EDITABLE_BY_NON_OWNERS,
                Id = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_ID,
                LastModifiedTimeStamp = DateTime.Now,
                LogicalNetworkId = VSEMODLConstants.LOGICAL_NETWORK_ID,
                ManagedByNetworkServiceId = VSEMODLConstants.SYSTEM_INFO_ID,
                MarkedForDeletion =
                    VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_MARKED_FOR_DELETION,
                MaximumVMSubnetsPerVMNetwork =
                    VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_MAX_VM_NETWORK_DEFINITIONS_PER_VM_NETWORK,
                Name = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_NAME,
                SegmentIds = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_SEGMENT_IDS,
                SegmentType = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_SEGMENT_TYPE,
                SupportsIPSubnetConfigurationOnVMSubnets =
                    VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_SUPPORTS_IP_SUBNET_CONFIGURATION_ON_VMSUBNETS,
                SupportsVMNetworkProvisioning =
                    VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_SUPPORTS_VM_NETWORK_PROVISIONING,
                SynchronizationErrors = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_SYNCHRONIZATION_ERRORS,
                IPSubnets = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_IP_SUBNETS,
                LastModifiedBySystemId = VSEMODLConstants.LOGICAL_NETWORK_DEFINITION_LAST_MODIIED_BY_SYSTEM_ID
            };
            logicalNet.LogicalNetworkDefinitions[0].Name += VtnHostName;

            logicalNetworks.Add(logicalNet);

            return logicalNetworks;
        }
Ejemplo n.º 12
0
 private static string GetConnectionsAsString(LogicalNetwork network)
 {
     StringBuilder sb = new StringBuilder();
     foreach (var conn in network.GetConnections())
     {
         if (sb.Length != 0) sb.Append(' ');
         sb.AppendFormat("{0},{1}", conn.Index.UpperNodeIndex, conn.Index.LowerNodeIndex);
     }
     return sb.ToString();
 }
Ejemplo n.º 13
0
 private static string GetNodesAsString(LogicalNetwork network)
 {
     StringBuilder sb = new StringBuilder();
     foreach (var node in network.ConnectedNodes.Select(cn => cn.Node))
     {
         if (sb.Length != 0) sb.Append(',');
         sb.AppendFormat("{0}:{1}", node.Index, GetNodeName(node));
     }
     return sb.ToString();
 }
Ejemplo n.º 14
0
 public static LogicalNetwork CreateLogicalNetwork(global::System.Guid ID, global::System.Guid stampId)
 {
     LogicalNetwork logicalNetwork = new LogicalNetwork();
     logicalNetwork.ID = ID;
     logicalNetwork.StampId = stampId;
     return logicalNetwork;
 }
        /// <summary>
        /// Gets a VM logical network.
        /// </summary>
        /// <param name='fabricName'>
        /// Required. Fabric unique name.
        /// </param>
        /// <param name='logicalNetworkName'>
        /// Required. Network name.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the Logical Network object.
        /// </returns>
        public async Task <LogicalNetworkResponse> GetAsync(string fabricName, string logicalNetworkName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (fabricName == null)
            {
                throw new ArgumentNullException("fabricName");
            }
            if (logicalNetworkName == null)
            {
                throw new ArgumentNullException("logicalNetworkName");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("fabricName", fabricName);
                tracingParameters.Add("logicalNetworkName", logicalNetworkName);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/Subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceType);
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceName);
            url = url + "/replicationFabrics/";
            url = url + Uri.EscapeDataString(fabricName);
            url = url + "/replicationLogicalNetworks/";
            url = url + Uri.EscapeDataString(logicalNetworkName);
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2015-11-10");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2015-01-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    LogicalNetworkResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new LogicalNetworkResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            LogicalNetwork logicalNetworkInstance = new LogicalNetwork();
                            result.LogicalNetwork = logicalNetworkInstance;

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                LogicalNetworkProperties propertiesInstance = new LogicalNetworkProperties();
                                logicalNetworkInstance.Properties = propertiesInstance;

                                JToken friendlyNameValue = propertiesValue["friendlyName"];
                                if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
                                {
                                    string friendlyNameInstance = ((string)friendlyNameValue);
                                    propertiesInstance.FriendlyName = friendlyNameInstance;
                                }

                                JToken logicalNetworkDefinitionsStatusValue = propertiesValue["logicalNetworkDefinitionsStatus"];
                                if (logicalNetworkDefinitionsStatusValue != null && logicalNetworkDefinitionsStatusValue.Type != JTokenType.Null)
                                {
                                    string logicalNetworkDefinitionsStatusInstance = ((string)logicalNetworkDefinitionsStatusValue);
                                    propertiesInstance.LogicalNetworkDefinitionsStatus = logicalNetworkDefinitionsStatusInstance;
                                }

                                JToken networkVirtualizationStatusValue = propertiesValue["networkVirtualizationStatus"];
                                if (networkVirtualizationStatusValue != null && networkVirtualizationStatusValue.Type != JTokenType.Null)
                                {
                                    string networkVirtualizationStatusInstance = ((string)networkVirtualizationStatusValue);
                                    propertiesInstance.NetworkVirtualizationStatus = networkVirtualizationStatusInstance;
                                }

                                JToken logicalNetworkUsageValue = propertiesValue["logicalNetworkUsage"];
                                if (logicalNetworkUsageValue != null && logicalNetworkUsageValue.Type != JTokenType.Null)
                                {
                                    string logicalNetworkUsageInstance = ((string)logicalNetworkUsageValue);
                                    propertiesInstance.LogicalNetworkUsage = logicalNetworkUsageInstance;
                                }
                            }

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                logicalNetworkInstance.Id = idInstance;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                logicalNetworkInstance.Name = nameInstance;
                            }

                            JToken typeValue = responseDoc["type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                string typeInstance = ((string)typeValue);
                                logicalNetworkInstance.Type = typeInstance;
                            }

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                logicalNetworkInstance.Location = locationInstance;
                            }

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey   = ((string)property.Name);
                                    string tagsValue = ((string)property.Value);
                                    logicalNetworkInstance.Tags.Add(tagsKey, tagsValue);
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 /// <summary>
 /// Replace logical network.
 /// </summary>
 /// <param name="src">Logical network instance.</param>
 /// <returns>List index if replace successfully, else -1.</returns>
 public int ReplaceLogicalNetwork(LogicalNetwork src)
 {
     if (this.LogicalNetworks != null) {
         int i = this.LogicalNetworks.FindIndex(nw => nw.Id == src.Id);
         if (i >= 0) {
             this.LogicalNetworks[i] = src;
         }
         return i;
     } else {
         return -1;
     }
 }
        /// <summary>
        /// Create default LogicalNetwork and add to configuration.
        /// </summary>
        /// <param name="logicalNetworkConfig">FabricNetworkConfig instance.</param>
        public void CreateHNVLogicalNetwork(LogicalNetworkConfig logicalNetworkConfig)
        {
            // Verify arguments.
            if (logicalNetworkConfig == null) {
                return;
            }

            if (logicalNetworkConfig.GetLogicalNetworkById(HNVODLConstants.LOGICAL_NETWORK.LOGICALNETWORK_ID) != null) {
                // If exists, nothing to do.
                return;
            }

            ODLVSEMETW.EventWriteGetHNVLogicalNetworkNotFound(MethodBase.GetCurrentMethod().Name,
                string.Format("Create LogicalNetwork that Guid is {0}", HNVODLConstants.LOGICAL_NETWORK.LOGICALNETWORK_ID));

            // Create LogicalNetwork instance.
            var logicalNetwork = new LogicalNetwork() {
                AreLogicalNetworkDefinitionsIsolated =
                    HNVODLConstants.LOGICAL_NETWORK.ARE_LOGICALNETWORK_DEFINITIONS_ISOLATED,
                Description = HNVODLConstants.LOGICAL_NETWORK.DESCRIPTION,
                Id = HNVODLConstants.LOGICAL_NETWORK.LOGICALNETWORK_ID,
                LastModifiedTimeStamp = DateTime.Now,
                LogicalNetworkDefinitions = new LogicalNetworkDefinition[1],
                Name = string.Format(HNVODLConstants.LOGICAL_NETWORK.NAME, this.VtnHostName)
            };
            logicalNetwork.LogicalNetworkDefinitions[0] = this.CreateDefaultLogicalNetworkDefinition();

            // Add created logical network to the configuration.
            logicalNetworkConfig.LogicalNetworks.Add(logicalNetwork);
        }
        /// <summary>
        /// Verify whether the specified LogicalNetwork is HNV resource or not.
        /// </summary>
        /// <param name="logicalNetwork">LogicalNetwork instance.</param>
        /// <returns>True if HNV resource, else false.</returns>
        public bool IsHNVLogicalNetwork(LogicalNetwork logicalNetwork)
        {
            if (logicalNetwork == null) {
                return false;
            }

            LogicalNetworkDefinition tmpLogicalNetworkDefinition =
                logicalNetwork.LogicalNetworkDefinitions.FirstOrDefault(l => l.Id == HNVODLConstants.LOGICAL_NETWORK_DEFINITION.ID);
            if (tmpLogicalNetworkDefinition != null
                && tmpLogicalNetworkDefinition.ManagedByNetworkServiceId == VSEMODLConstants.SYSTEM_INFO_ID
                && logicalNetwork.AreLogicalNetworkDefinitionsIsolated == false) {
                return true;
            }
            ODLVSEMETW.EventWriteNotHNVLogicalNetwork(MethodBase.GetCurrentMethod().Name,
                string.Format("LogicalNetwork name is {0}", logicalNetwork.Name));

            return false;
        }
        /// <summary>
        /// Validate whether the specified LogicalNetwork is correct configuration or not.
        /// </summary>
        /// <param name="logicalNetwork">LogicalNetwork instance.</param>
        /// <returns>True if correct configuraton or not HNV resource, else false.</returns>
        public bool IsLogicalNetworkValid(LogicalNetwork logicalNetwork)
        {
            if (logicalNetwork == null) {
                return false;
            }

            // IsHNV check.
            if (this.IsHNVLogicalNetwork(logicalNetwork) == false) {
                // Not HNV resource.
                return true;
            }

            // Validate NetworkSites.
            bool ret;
            ret = this.IsLogicalNetworkDefinitionsValid(logicalNetwork);

            if (ret == false) {
                ODLVSEMETW.EventWriteValidateLogicalNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format("LogicalNetwork name is {0}", logicalNetwork.Name));
            }

            return ret;
        }
        /// <summary>
        /// Update the existing logical network.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="logicalNetwork">Updated logical network.</param>
        public void UpdateLogicalNetwork(TransactionManager txnMng, LogicalNetwork logicalNetwork)
        {
            var logicalNetworkConfig = new LogicalNetworkConfig(this.VtnHostName);
            txnMng.SetConfigManager(logicalNetworkConfig, TransactionManager.OpenMode.WriteMode);

            int target;
            target = logicalNetworkConfig.ReplaceLogicalNetwork(logicalNetwork);
            if (target == -1) {
                ODLVSEMETW.EventWriteGetHNVLogicalNetworkNotFound(MethodBase.GetCurrentMethod().Name,
                    string.Format("LogicalNetwork name is {0}", logicalNetwork.Name));
            }
        }
 /// <summary>
 /// Validate whether the specified LogicalNetwork.LogicalNetworkDefinitions are correct configuration or not.
 /// </summary>
 /// <param name="logicalNetwork">LogicalNetwork instance.</param>
 /// <returns>True if correct configuraton, else false.</returns>
 private bool IsLogicalNetworkDefinitionsValid(LogicalNetwork logicalNetwork)
 {
     bool ret = true;
     for (int i = 0; i < logicalNetwork.LogicalNetworkDefinitions.Length; i++) {
         LogicalNetworkDefinition tmpLogicalNetworkDefinition = logicalNetwork.LogicalNetworkDefinitions[i];
         if (tmpLogicalNetworkDefinition.Id == HNVODLConstants.LOGICAL_NETWORK_DEFINITION.ID) {
             continue;
         } else {
             // Invalid NetworkSite.
             string ErrorString =
                 string.Format(HNVODLConstants.ERROR_STRING.INVALID_NETWORKSITE, tmpLogicalNetworkDefinition.Name);
             List<string> msg = new List<string>();
             msg.Add(ErrorString);
             tmpLogicalNetworkDefinition.SynchronizationErrors = msg.ToArray();
             ret = false;
         }
     }
     return ret;
 }