/// <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);
 }
        /// <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>
        /// 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 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;
        }