Пример #1
0
        /// <summary>
        /// Retrieve the webapi version of VTNCoordinator and check whether it is suppored of not.
        /// </summary>
        /// <param name="minVesion">Minimum weapi version supported.</param>
        /// <returns>True if Webapi version of VTNCoordinator is suppoted, else false.</returns>
        public bool VerifyConnection(Version minVesion)
        {
            Controller odl = new Controller(this.ConnectionString, this.Credential);
            ODLVSEMETW.EventWriteVerifyConnection("Verifying connection.", string.Empty);
            string webapiVersionFound =
                odl.RequestWebApiVersion();
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from VTNCoordinator Library.", string.Empty);

            Version vtncoWebapiVersion = new Version(webapiVersionFound.Substring(1));
            return minVesion <= vtncoWebapiVersion;
        }
Пример #2
0
 /// <summary>
 /// Closes the connection.
 /// </summary>
 public void CloseConnection()
 {
     ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
     Controller odl_ctr = new Controller(this.ConnectionString, this.controllers, this.Credential);
     odl_ctr.Delete_ctr(Constants.CTR_NAME);
     odl_ctr.UpdateStartupConfiguration();
     this.ConnectionString = null;
     this.controllers = null;
     this.Credential = null;
     ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
 }
Пример #3
0
        /// <summary>
        /// Update the VSEM repository.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        public void UpdateConnection(TransactionManager txnMng)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"TransactionManager\":" + JavaScriptSerializer.Serialize(txnMng));
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name, json.ToString());
            if (txnMng == null) {
                throw new ArgumentException(
                    "txnMng' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

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

            VtnHostName = VtnHostName.Split('.', ':').First();
            var vseminformation = this.CreateVSEMInfo();

            // Make sure we can connect to the ODL
            if (!this.VerifyConnection(vseminformation.MinVTNCoVersion)) {
                ODLVSEMETW.EventWriteProcesOdlLibraryError(MethodBase.GetCurrentMethod().Name,
                    "WebAPI version is not supported.");
                throw new ArgumentException("WebAPI version is not supported.");
            }
            Controller odl_ctr = new Controller(this.ConnectionString, this.controllers, this.Credential);
            odl_ctr.Create_ctr(Constants.CTR_NAME);

            ODLVSEMETW.EventWriteCreateODLData(
                MethodBase.GetCurrentMethod().Name, "Creating VSEM repository.");

            VSEMConfig vsemConfig = new VSEMConfig();
            txnMng.SetConfigManager(vsemConfig, TransactionManager.OpenMode.WriteMode);

            // Update Configuration Data;
            vsemConfig.Info = vseminformation;
            vsemConfig.Controller = new VSEMController();
            vsemConfig.Controller.ControllerInfo = this.controllers;
            if (vsemConfig.NetworkServiceSystemInformation.Id.CompareTo(Guid.Empty) == 0) {
                vsemConfig.NetworkServiceSystemInformation = VSEMConnection.CreateSystemInfo();
            } else {
                VSEMODLConstants.SYSTEM_INFO_ID = vsemConfig.NetworkServiceSystemInformation.Id;
            }
            if (vsemConfig.SwitchExtensionInfo.Count == 0) {
                vsemConfig.SwitchExtensionInfo = VSEMConnection.CreateSwitchExtensionInfos();
            } else {
                VSEMODLConstants.SWITCH_EXTENSION_INFO_ID = vsemConfig.SwitchExtensionInfo[0].Id;
            }
            vsemConfig.SwitchExtensionInfo.ForEach((i) =>
                    VSEMConnection.AddSwitchFeatureToSwitchExtInfos(i, this.controllers));

            LogicalNetworkConfig logicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(logicalNetworkConfig, TransactionManager.OpenMode.WriteMode);
            if (logicalNetworkConfig.LogicalNetworks.Count == 0) {
                logicalNetworkConfig.LogicalNetworks =
                    this.CreateLogicalNetworks();
            }

            PortProfileConfig portProfileConfig = new PortProfileConfig();
            txnMng.SetConfigManager(portProfileConfig, TransactionManager.OpenMode.WriteMode);

            if (portProfileConfig.UplinkPortProfiles.Count == 0) {
                portProfileConfig.UplinkPortProfiles =
                    VSEMConnection.CreateUplinkPortProfiles();
            } else {
                VSEMODLConstants.UPLINK_PORT_PROFILE_ID = portProfileConfig.UplinkPortProfiles[0].Id;
            }

            if (portProfileConfig.VirtualPortProfiles.Count == 0) {
                portProfileConfig.VirtualPortProfiles =
                    VSEMConnection.CreateVirtualPortProfiles();
            }

            // Create HNV default resource.
            HNVLogicalNetworkManagement hnvMgmt = new HNVLogicalNetworkManagement(this.VtnHostName);
            hnvMgmt.CreateHNVLogicalNetwork(logicalNetworkConfig);
            hnvMgmt.AssociatePortProfileWithHNV(portProfileConfig);

            this.SaveVtncoInfo(txnMng, VtnHostName);

            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
        }
        /// <summary>
        /// Publish VM Network.
        /// </summary>
        /// <param name="txnMng">TransactionManager instance.</param>
        /// <param name="vMNetwork">VM Network.</param>
        /// <param name="operationType">Operation type performed on SCVMM.</param>
        /// <param name="connection">Connection object.</param>
        /// <returns>Boolean indicating whether network service refresh is needed..</returns>
        public bool PublishVMNetwork(TransactionManager txnMng,
            VMNetwork vMNetwork,
            NetworkEntityPublishType operationType,
            VSEMConnection connection)
        {
            bool needRefresh = false;
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"vMNetwork\":" + JavaScriptSerializer.Serialize(vMNetwork));
            json.Append(" \"operationType\":" + JavaScriptSerializer.Serialize(operationType));
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'transaction' is null or invalid.");
                throw new ArgumentException("The parameter 'transaction' is null or invalid.");
            }

            if (vMNetwork == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetwork' is null or invalid.");
                throw new ArgumentException("The parameter 'vMNetworkName' is null or invalid.");
            }
            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");
                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

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

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

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);

            var vmnetworkFound = vMNetworkConfig.VMNetwork.VmNetworks.FirstOrDefault(
                nw => nw.Id == vMNetwork.Id);

            var vmnetworkMappigInfoFound = vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.FirstOrDefault(
                        nw => nw.VMNetworkID == vMNetwork.Id);
            if (vmnetworkMappigInfoFound == null) {
                return needRefresh;
            }

            if (operationType != NetworkEntityPublishType.Delete) {
                vmnetworkMappigInfoFound.VMNetworkName = vMNetwork.Name;
                if (vmnetworkMappigInfoFound.VTNName.CompareTo(string.Empty) == 0) {
                    return needRefresh;
                }
                vmnetworkFound.OwnerName = vMNetwork.OwnerName;
                vmnetworkFound.RoutingDomainId = vMNetwork.RoutingDomainId;
                if (operationType == NetworkEntityPublishType.Create) {
                    foreach (var subnetinfo in vmnetworkMappigInfoFound.VMSubnetInfo) {
                        subnetinfo.VMSubnetName = subnetinfo.VBridgeName;
                        subnetinfo.VMSubnetVlanId = subnetinfo.VBridgeVlanId;
                    }
                    Controller odl = new Controller(this.ConnectionString, this.Credential);
                    List<Vtn> vtns = odl.ReadVTNObjects(vmnetworkMappigInfoFound.VTNName);
                    if (vtns.Count == 0) {
                        needRefresh = true;
                        vMNetworkConfig.VMNetwork.VmNetworks.Remove(vmnetworkFound);
                        vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Remove(vmnetworkMappigInfoFound);
                    } if (vtns.Count != 0) {
                        needRefresh = this.SyncVTN(vmnetworkFound.VMSubnets.First().LogicalNetworkDefinitionId,
                    vmnetworkFound,
                    vtns.First(),
                    vmnetworkMappigInfoFound,
                    txnMng,
                    VtnHostName);
                    }
                }
                vmnetworkMappigInfoFound.Description = string.Empty;
            } else {
                if (vmnetworkMappigInfoFound.VTNName.CompareTo(string.Empty) == 0) {
                    vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Remove(vmnetworkMappigInfoFound);
                    return needRefresh;
                }
                vmnetworkMappigInfoFound.VMNetworkName = string.Empty;
                vmnetworkMappigInfoFound.VMSubnetInfo.ForEach(subnet => { subnet.VMSubnetName = string.Empty; subnet.VMSubnetVlanId = 0; });
                vmnetworkMappigInfoFound.Description = "VM Network corresponding to this VTN is not created on SCVMM";
                vmnetworkFound.Name = vmnetworkMappigInfoFound.VTNName;
                vmnetworkFound.RoutingDomainId = null;
                vmnetworkFound.OwnerName = string.Empty;
            }

            string output = "\"VMNetwork\":" + JavaScriptSerializer.Serialize(vmnetworkFound);
            string outputMappingInfo = "\"VMNetworkInfo\":" + JavaScriptSerializer.Serialize(vmnetworkMappigInfoFound);
            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
                output);
            return needRefresh;
        }
        /// <summary>
        /// This method is responsible to synchronize the network configuration between ODL and SCVMM.
        /// </summary>
        /// <param name="txnMng">TransactionManager instance.</param>
        public void SynchronizeVTNObjects(TransactionManager txnMng)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                   json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'transaction' is null or invalid.");
                throw new ArgumentException("The parameter 'transaction' is null or invalid.");
            }
            Controller odl = new Controller(this.ConnectionString, this.Credential);
            List<Vtn> vtns = odl.ReadVTNObjects(string.Empty);

            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);

            string VtnHostName = this.ConnectionString;

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

            VtnHostName = VtnHostName.Split('.', ':').First();
            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            try {
                txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);
            } catch (Exception ex) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}\n{1}",
                    configFileIOErrorValidationMessage,
                    ex.Message));
                ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }
            var logicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            try {
                txnMng.SetConfigManager(logicalNetworkConfig, TransactionManager.OpenMode.ReadMode);
            } catch (Exception ex) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}\n{1}",
                    configFileIOErrorValidationMessage,
                    ex.Message));
                ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            } string logicalNetworkName = VSEMODLConstants.LOGICAL_NETWORK_NAME;
            logicalNetworkName += VtnHostName;
            var logicalNetwork = logicalNetworkConfig.LogicalNetworks.FirstOrDefault(logicalnw => logicalnw.Name.Equals(logicalNetworkName));
            if (logicalNetwork == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "Logical network '{0}' not found.",
                    logicalNetworkName));
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                     "Logical network definition '{0}' not found.",
                     logicalNetworkName));
            }
            Guid logicalNetworkId = logicalNetwork.Id;
            Guid logicalNetworkDefinitionId = logicalNetwork.LogicalNetworkDefinitions.First().Id;
            ////for creation.
            this.CompareVTNObjects(vtns, vMNetworkConfig, logicalNetworkId, logicalNetworkDefinitionId, txnMng, VtnHostName);
            ////for removal.
            this.CompareVMNetworkObjects(vtns, vMNetworkConfig);
            vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.LastModifiedTimeStamp =
                        DateTime.Now;
        }
        /// <summary>
        /// Create a new VM network with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="vMSubnetName">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkName">Name of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnets">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition
        /// to associate with.</param>
        /// <param name="connection">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMNetwork CreateVMNetwork(TransactionManager txnMng,
            string vMSubnetName,
            string vMNetworkName,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnets,
            Guid logicalNetworkDefinitionId,
            VSEMConnection connection,
            out string vtnName)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"ipSubnets\":" + JavaScriptSerializer.Serialize(ipSubnets));
            json.Append("\"maxNumberOfPorts\":\"" + maxNumberOfPorts + "\"");
            json.Append("\"vMNetworkName\":\"" + vMNetworkName + "\"");
            json.Append("\"vMSubnetName\":\"" + vMSubnetName + "\"");
            json.Append("\"logicalNetworkDefinitionId\":\"" + logicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'transaction' is null or invalid.");
                throw new ArgumentException("The parameter 'transaction' is null or invalid.");
            }

            if (string.IsNullOrEmpty(vMNetworkName)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkName' is null or invalid.");
                throw new ArgumentException("The parameter 'vMNetworkName' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }
            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");
                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

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

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

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);

            var LogicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(LogicalNetworkConfig, TransactionManager.OpenMode.ReadMode);
            if (LogicalNetworkConfig.LogicalNetworks.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var logicalNetName = VSEMODLConstants.LOGICAL_NETWORK_NAME;
            logicalNetName += VtnHostName;
            var fabricNwDef = LogicalNetworkConfig.LogicalNetworks.First(
                log => log.Name.Equals(logicalNetName)).LogicalNetworkDefinitions.FirstOrDefault(
                fabnw => fabnw.Id == logicalNetworkDefinitionId);
            if (fabricNwDef == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "Logical network definition '{0}' not found.",
                    logicalNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                     "Logical network definition '{0}' not found.",
                logicalNetworkDefinitionId.ToString("B")));
            }

            ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                "VSEMLogicalNetworkDefinition is retrieved by ID: {0}",
                logicalNetworkDefinitionId.ToString("B")),
                string.Empty);

            if (!fabricNwDef.SupportsVMNetworkProvisioning) {
                ODLVSEMETW.EventWriteSupportsVMNetworkProvisioningError(
                    "Logical network does not support VM network creation.",
                    string.Empty);
                throw new InvalidOperationException(
                    "Logical network does not support VM network creation.");
            }

            vtnName = this.CreateUniqueNameForVTN(vMNetworkName);

            Vtn vtn = new Vtn(this.ConnectionString, this.Credential);
            vtn.AddVtn(vtnName);

            ODLVSEMETW.EventWriteReturnODLLibrary(string.Format(CultureInfo.CurrentCulture,
                "VTN '{0}' is created",
                vtnName),
                string.Empty);

            VMNetwork vmNet = CreateVtnVmNetwork(vMNetworkName);
            vmNet.LogicalNetwork = fabricNwDef.LogicalNetworkId;
            if (vmNet == null) {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Network.");
                throw new InvalidOperationException("Failed to create VM Network.");
            }
            ODLVSEMETW.EventWriteSuccessVmNetwork(MethodBase.GetCurrentMethod().Name,
                    "VM Network Successfully Created.");

            // Create the VM Subnet
            vMNetworkConfig.VMNetwork.VmNetworks.Add(vmNet);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo == null) {
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo =
                    new List<VMNetworkInfo>();
            }

            vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Add(
                new VMNetworkInfo {
                    VMNetworkID = vmNet.Id,
                    VMNetworkName = vmNet.Name,
                    VTNName = vtnName,
                    VMSubnetInfo = new List<VMSubnetInfo>(),
                    CreatedFrom = "SCVMM",
                    VMNetworkOriginalName = vmNet.Name
                });

            var vsemvmnetworkDefinition = new VSEMVMSubnetManagement(
                this.ConnectionString, this.Credential);
            ODLVSEMETW.EventWriteCreateVMsubNetwork(MethodBase.GetCurrentMethod().Name,
                    "VM Sub Network creation process started.");
            string vbrName = string.Empty;
            VMSubnet vmNetworkDef =
                vsemvmnetworkDefinition.CreateVMNetworkDefinitionforVtn(
                txnMng,
                LogicalNetworkConfig,
                vMNetworkConfig,
                vMSubnetName,
                vmNet.Id,
                maxNumberOfPorts,
                ipSubnets,
                logicalNetworkDefinitionId,
                connection,
                out vtnName,
                out vbrName);

            Controller odl = new Controller(this.ConnectionString, this.Credential);
            odl.UpdateStartupConfiguration();
            string output = "\"vmNet\":" + JavaScriptSerializer.Serialize(vmNet);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", output);

            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
                output);
            return vmNet;
        }
        /// <summary>
        /// Create unique name for vtn.
        /// </summary>
        /// <param name="vmNetworkName">VmNetwork name.</param>
        /// <returns>Unique name of vtn.</returns>
        private string CreateUniqueNameForVTN(string vmNetworkName)
        {
            ODLVSEMETW.EventWriteCreateUniqueVTNName(MethodBase.GetCurrentMethod().Name,
                    "Creating unique name for VTN.");
            if (string.IsNullOrEmpty(vmNetworkName)) {
                ODLVSEMETW.EventWriteArgumentError(
                MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                MethodBase.GetCurrentMethod().Name,
                "The parameter 'vmNetworkName' is null or invalid.");
                throw new ArgumentException("The parameter 'vmNetworkName' is null or invalid.");
            }

            Controller Odl = new Controller(this.ConnectionString, this.Credential);
            List<string> existingVtns = Odl.GetVtnList();
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
            string name = CreateName(vmNetworkName);
            while (existingVtns.Contains(name)) {
                name = RecreateName(name);
            }
            return name;
        }
        /// <summary>
        /// Synchronize the VMSubnet.
        /// </summary>
        /// <param name="vmNetworkDefinitionId"> ID of the VMSubnet.</param>
        /// <param name="vMNetworkConfig">Instance of VMNetwor.config file.</param>
        private void SyncVMSubnet(Guid vmNetworkDefinitionId, VMNetworkConfig vMNetworkConfig)
        {
            string vtnName = string.Empty;
            string vbrName = string.Empty;
            VMNetworkInfo vmnetworkMappigInfoFound = null;
            foreach (var vmNet in
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo) {
                foreach (var vmSubNet in vmNet.VMSubnetInfo) {
                    if (vmSubNet.VMSubnetID == vmNetworkDefinitionId) {
                        vtnName = vmNet.VTNName;
                        vbrName = vmSubNet.VBridgeName;
                        vmnetworkMappigInfoFound = vmNet;
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(vtnName)) {
                    break;
                }
            }
            VSEMSynchronization vSEMSynchronization =
                new VSEMSynchronization(this.ConnectionString, this.Credential);
            Controller odl = new Controller(this.ConnectionString, this.Credential);
            int odlStatus = odl.CheckVbridgeStatus(vtnName, vbrName);

            if (odlStatus == -2) {
                VSEMSynchronization.RemoveVMNetworkSync(vMNetworkConfig, vmnetworkMappigInfoFound);
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                        "Corresponding VTN is not found on ODL.");
                throw new DataMisalignedException("Corresponding VTN is not found on ODL.\nRefresh the Odl configuration and then retry.");
            }
            if (odlStatus == -1) {
                VSEMSynchronization.RemoveVMSubnetSync(vMNetworkConfig, vmNetworkDefinitionId, null, null);
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                        "Corresponding vBridge is not found on ODL.");
                throw new DataMisalignedException("Corresponding vBridge is not found on ODL.\nRefresh the Odl configuration and then retry.");
            }
        }
        /// <summary>
        /// Remove the specified VM Subnet.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="id">ID of VM Subnet to remove.</param>
        /// <param name="connection">VSEM connection.</param>
        /// <param name="vbrName">Name of the vBridge.</param>
        /// <returns>Indicated the need to refresh the network service..</returns>
        public bool RemoveVmNetworkDefinition(TransactionManager txnMng,
            Guid id,
            VSEMConnection connection,
            out string vbrName)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append("\"id\":\"" + id + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");
                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }
            if (id == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'id' is null or invalid.");
                throw new ArgumentException("The parameter 'id' is null or invalid.");
            }
            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");
                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }
            string VtnHostName = this.ConnectionString;

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

            VtnHostName = VtnHostName.Split('.', ':').First();
            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            string vtnName = string.Empty;
            vbrName = string.Empty;
            Guid vmNetId = Guid.Empty;
            VMNetworkInfo vmnetworkMappigInfoFound = null;
            long vlanId = 0;
            foreach (var vmNet in
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo) {
                foreach (var vmSubNet in vmNet.VMSubnetInfo) {
                    if (vmSubNet.VMSubnetID == id) {
                        vtnName = vmNet.VTNName;
                        vbrName = vmSubNet.VBridgeName;
                        vmNetId = vmNet.VMNetworkID;
                        vlanId = vmSubNet.VBridgeVlanId;
                        vmnetworkMappigInfoFound = vmNet;
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(vtnName)) {
                    break;
                }
            }
            if (string.IsNullOrEmpty(vbrName)) {
                ODLVSEMETW.EventWriteGetVSEMVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMSubnet '{0}' not found.",
                    id.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VMSubnet '{0}' not found.",
                    id.ToString("B")));
            }
            VMNetwork network = null;
            foreach (var vmNet in
                 vMNetworkConfig.VMNetwork.VmNetworks) {
                if (vmNet.Id == vmNetId) {
                    network = vmNet;
                    break;
                }
            }
            if (network == null || !network.VMSubnets.Any(vms => vms.Id.CompareTo(id) == 0)) {
                ODLVSEMETW.EventWriteGetVSEMVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMSubnet '{0}' not found.",
                    id.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VMSubnet '{0}' not found.",
                    id.ToString("B")));
            }
            var logicalNetworkDefinitionId = vMNetworkConfig.VMNetwork.VmNetworks.FirstOrDefault(
                vmn => vmn.Id == vmNetId).VMSubnets.FirstOrDefault(
                subNetwork => subNetwork.Id == id).LogicalNetworkDefinitionId;

            VSEMSynchronization vSEMSynchronization =
                new VSEMSynchronization(this.ConnectionString, this.Credential);
            Controller odl = new Controller(this.ConnectionString, this.Credential);
            List<Vtn> vtns = odl.ReadVTNObjects(vtnName);
            if (vtns.Count == 0 && network.VMSubnets.Count() > 1) {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    "Corresponding VTN is not found on ODL.");
                throw new DataMisalignedException(
                    "Corresponding VTN is not found on ODL.\nRefresh the Odl configuration and then retry.");
            }
            string vbridgeName = vbrName;
            if (vtns[0].Vbridges.Any(vbr => vbr.Name.CompareTo(vbridgeName) != 0) && network.VMSubnets.Count() == 1) {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    "On synchronization, additional vBridge(s) are found in the VTN corresponding to this VM Network on ODL.\nSo, this VM Network cannot be removed and the operation has been abandoned.\nRefresh the Odl configuration and then retry.");
                throw new DataMisalignedException(
                    "On synchronization, additional vBridge(s) are found in the VTN corresponding to this VM Network on ODL.\nSo, this VM Network cannot be removed and the operation has been abandoned.\nRefresh the Odl configuration and then retry.");
            }
            Vbridge vbridge = vtns[0].Vbridges.FirstOrDefault(vbr => vbr.Name.CompareTo(vbridgeName) == 0);
            if (vbridge != null && vlanId != vbridge.VlanId) {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                        "VLAN ID of corresponding vBridge is modified on ODL.");
                throw new DataMisalignedException(
                    "VLAN ID of corresponding vBridge is modified on ODL.\nRefresh the Odl configuration and then retry.");
            }

            var vmsubnet = vmnetworkMappigInfoFound.VMSubnetInfo.Where(vms =>
                vms.VMSubnetID.CompareTo(id) == 0).First();
            if (vmsubnet.CreatedFrom.Contains("ODL") &&
                vbridge != null) {
                ODLVSEMETW.EventWriteGetVSEMVMNetworkError(
                   MethodBase.GetCurrentMethod().Name,
                   "Corresponding vBridge is created or modified on ODL");
                throw new DataMisalignedException("Corresponding vBridge is created or modified on ODL.\nRefresh the Odl configuration and then retry.");
            }
            if (vtns.Count != 0) {
                Vbridge vBridge = new Vbridge(this.ConnectionString, this.Credential);
                vBridge.RemoveVbridge(vtnName, vbrName);
                ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
            }

            // Checking if VM Network removal is required.
            network.VMSubnets = network.VMSubnets.Where(
                netDef => netDef.Id != id).ToArray();

            vmnetworkMappigInfoFound.VMSubnetInfo.RemoveAll(subNet => subNet.VMSubnetID == id);
            if (network.VMSubnets.Count() == 0) {
                VSEMVMNetworkManagement vmNetworkManagement =
                    new VSEMVMNetworkManagement(this.ConnectionString,
                        this.Credential);
                vmNetworkManagement.RemoveVmNetwork(vMNetworkConfig,
                    vmNetId);
            }

            odl.UpdateStartupConfiguration();
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);

            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
            return false;
        }
 /// <summary>
 /// Gets the list of vBridges for the specified VTN from ODL.
 /// </summary>
 /// <param name="vtnName">Name of the VTN.</param>
 /// <returns>List of vBridges.</returns>
 public List<string> GetVbridgesListforVtn(string vtnName)
 {
     Controller odl = new Controller(this.ConnectionString, this.Credential);
     ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
     List<string> existingVtns = odl.GetVbridgesListforVtn(vtnName);
     return existingVtns;
 }
        /// <summary>
        /// Create a new VM network with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="LogicalNetworkConfig">Config file of logical network.</param>
        /// <param name="vMNetworkConfig">Config file of vm network.</param>
        /// <param name="name">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkId">Id of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnet">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition
        /// to associate with.</param>
        /// <param name="conn">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <param name="vbrName">Vbridge name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMSubnet CreateVMNetworkDefinitionforVtn(
            TransactionManager txnMng,
            LogicalNetworkConfig LogicalNetworkConfig,
            VMNetworkConfig vMNetworkConfig,
            string name,
            Guid vMNetworkId,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnet,
            Guid logicalNetworkDefinitionId,
            VSEMConnection conn,
            out string vtnName,
            out string vbrName)
        {
            ODLVSEMETW.EventWriteCreateVMsubNetwork(MethodBase.GetCurrentMethod().Name,
                "Creating VM SubNetwork.");
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");
                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }
            if (LogicalNetworkConfig == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'LogicalNetworkConfig' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'LogicalNetworkConfig' is null or invalid.");
            }
            if (vMNetworkConfig == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkConfig' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'vMNetworkConfig' is null or invalid.");
            }
            if (string.IsNullOrEmpty(name)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");
                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }
            if (vMNetworkId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkId' is null or invalid.");
                throw new ArgumentException("The parameter 'vMNetworkId' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }
            if (conn == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'conn' is null or invalid.");
                throw new ArgumentException("The parameter 'conn' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

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

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

            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo == null) {
                ODLVSEMETW.EventWriteProcessLibraryError(MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
            }
            var vmNetInfo =
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Where(
                vmNw => vmNw.VMNetworkID == vMNetworkId).FirstOrDefault();
            if (vmNetInfo == null) {
                ODLVSEMETW.EventWriteProcessLibraryError(MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VM network {0} not found.",
                    vMNetworkId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
            }
            vtnName = vmNetInfo.VTNName;

            vbrName = this.CreateUniqueNameForVBridge(name, vmNetInfo.VTNName);

            VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
                VtnHostName,
                TransactionManager.OpenMode.ReadMode);
            string vlanIdRange = vLANIDMap.GetVlanId(vmNetInfo.VMNetworkOriginalName, name);
            if (string.IsNullOrEmpty(vlanIdRange)) {
                ODLVSEMETW.EventWriteFoundNoVlanError(MethodBase.GetCurrentMethod().Name,
                    "No VLAN ID found.");
                throw new ItemNotFoundException("No VLAN ID found.");
            }
            long vlanId = this.SelectVlanId(vlanIdRange,
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo);
            if (vlanId == 0) {
                ODLVSEMETW.EventWriteFoundNoUnusedVlanError(MethodBase.GetCurrentMethod().Name,
                    "No unused VLAN ID found.");
                throw new ItemNotFoundException("No unused VLAN ID found.");
            }

            VMSubnet vmNetworkDef = CreateVbrVmNetworkDefinition(
                vMNetworkId,
                maxNumberOfPorts,
                ipSubnet,
                name,
                logicalNetworkDefinitionId,
                vbrName,
                vlanId);

            if (vmNetworkDef == null) {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Subnet.");
                throw new InvalidOperationException("Failed to create VM Subnet.");
            }
            Vbridge vBridge = new Vbridge(this.ConnectionString, this.Credential);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
            Controller odl_ctr = new Controller(this.ConnectionString, this.Credential);
            if (odl_ctr.Get_status(Constants.CTR_NAME)) {
            vBridge.AddVbridge(vbrName, vmNetInfo.VTNName, vlanId);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
            } else {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VBR controller status is down.");
                throw new InvalidOperationException("Failed to create VBR.");
            }

            var vmNet = vMNetworkConfig.VMNetwork.VmNetworks.Where(nwk =>
                nwk.Id == vMNetworkId).FirstOrDefault();

            Array.Resize(ref vmNet.VMSubnets, vmNet.VMSubnets.Length + 1);
            vmNet.VMSubnets[vmNet.VMSubnets.Length - 1] = vmNetworkDef;
            vmNetInfo.VMSubnetInfo.Add(new VMSubnetInfo {
                VBridgeName = vbrName,
                VMSubnetVlanId = vlanId,
                VMSubnetID = vmNetworkDef.Id,
                VMSubnetName = vmNetworkDef.Name,
                CreatedFrom = "SCVMM",
                VBridgeVlanId = vlanId
            });

            return vmNetworkDef;
        }
        /// <summary>
        /// Create a new VM subnet with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="name">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkId">Id of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnets">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition to associate with.</param>
        /// <param name="connection">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <param name="vbrName">Vbridge name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMSubnet CreateVMNetworkDefinition(TransactionManager txnMng,
            string name,
            Guid vMNetworkId,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnets,
            Guid logicalNetworkDefinitionId,
            VSEMConnection connection,
            out string vtnName,
            out string vbrName)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"ipSubnets\":" + JavaScriptSerializer.Serialize(ipSubnets));
            json.Append("\"maxNumberOfPorts\":\"" + maxNumberOfPorts + "\"");
            json.Append("\"name\":\"" + name + "\"");
            json.Append("\"logicalNetworkDefinitionId\":\"" + logicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");

                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }

            if (string.IsNullOrEmpty(name)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");

                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }

            if (vMNetworkId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkId' is null or invalid.");

                throw new ArgumentException("The parameter 'vMNetworkId' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");

                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }

            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");

                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

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

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

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var vmNw = vMNetworkConfig.VMNetwork.VmNetworks.FirstOrDefault(
                nwk => nwk.Id == vMNetworkId);

            if (vmNw == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found. VTN corresponding to this VM network may have been deleted from ODL.\nRefer Network Object Mapping screen.",
                    vMNetworkId.ToString("B")));
            }

            var LogicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(LogicalNetworkConfig, TransactionManager.OpenMode.ReadMode);
            if (LogicalNetworkConfig.LogicalNetworks.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var logicalNwDef = LogicalNetworkConfig.LogicalNetworks.First().LogicalNetworkDefinitions.FirstOrDefault(
                fabnw => fabnw.Id == logicalNetworkDefinitionId);

            if (logicalNwDef == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "Logical network definition '{0}' not found.",
                    logicalNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                     "Logical network definition '{0}' not found.",
                logicalNetworkDefinitionId.ToString("B")));
            }

            string output = "\"logicalNwDef\":" + JavaScriptSerializer.Serialize(logicalNwDef);
            if (!logicalNwDef.SupportsVMNetworkProvisioning) {
                ODLVSEMETW.EventWriteSupportsVMNetworkProvisioningError(
                    "Logical does not support VM network creation.",
                    output);
                throw new InvalidOperationException(
                    "Logical does not support VM network creation.");
            }
            VMNetworkInfo vmnetworkInfo = vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.First(vmn => vmn.VMNetworkID.CompareTo(vmNw.Id) == 0);
            VSEMSynchronization vSEMSynchronization =
                new VSEMSynchronization(this.ConnectionString, this.Credential);
            Controller odl = new Controller(this.ConnectionString, this.Credential);
            List<Vtn> vtns = odl.ReadVTNObjects(vmnetworkInfo.VTNName);
            if (vtns.Count == 0) {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                        "Corresponding VTN is not found on ODL.");
                throw new DataMisalignedException("Corresponding VTN is not found on ODL.\nRefresh the Odl configuration and then retry.");
            }

            VMSubnet nw = this.CreateVMNetworkDefinitionforVtn(txnMng,
                LogicalNetworkConfig,
                vMNetworkConfig,
                name,
                vMNetworkId,
                maxNumberOfPorts,
                ipSubnets,
                logicalNetworkDefinitionId,
                connection,
                out vtnName,
                out vbrName);

            if (nw == null) {
                ODLVSEMETW.EventWriteProcessFailedVMSubNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Subnet.");
                throw new InvalidOperationException("Failed to create VM Subnet.");
            }

            odl = new Controller(this.ConnectionString, this.Credential);
            odl.UpdateStartupConfiguration();
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);

            string outputLib = "\"nw\":" + JavaScriptSerializer.Serialize(nw);
            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, outputLib);
            return nw;
        }