/// <summary>
        /// Checks whether the change is VLAN ID is consistent or not.
        /// </summary>
        /// <param name="vmnetworkInfo">Corresponding VM network info.</param>
        /// <param name="txnMng">Transaction manager instance.</param>
        /// <param name="VtnHostName">Host name of the VTNCoordinator.</param>
        /// <param name="vmsubnetInfo">Corresponding VM subnet info.</param>
        /// <returns>Empty id the modification is consistent.</returns>
        private static string CheckVlanRange(VMNetworkInfo vmnetworkInfo, TransactionManager txnMng, string VtnHostName, VMSubnetInfo vmsubnetInfo)
        {
            string vlanIdRange = string.Empty;

            if (vmsubnetInfo.CreatedFrom.CompareTo("ODL") == 0)
            {
                return(vlanIdRange);
            }
            vmsubnetInfo.CreatedFrom = "ODLModified";
            VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
                                                VtnHostName,
                                                TransactionManager.OpenMode.ReadMode);

            vlanIdRange = vLANIDMap.GetVlanId(vmnetworkInfo.VMNetworkOriginalName, vmsubnetInfo.VMSubnetName);
            if (string.IsNullOrEmpty(vlanIdRange))
            {
                return(vlanIdRange);
            }
            bool isinRange = CheckVlanId(vlanIdRange, vmsubnetInfo.VBridgeVlanId);

            if (isinRange)
            {
                return(string.Empty);
            }
            else
            {
                return(vlanIdRange);
            }
        }
 /// <summary>
 /// This method is responsible to dump the VlanId map information.
 /// </summary>
 protected override void DoODLVSEMCmdlet()
 {
     StringBuilder json = new StringBuilder("\"VMNetworkName\":\"" + this.VMNetworkName + "\"");
     json.Append("\"VMSubnetworkName\":\"" + this.VMSubnetworkName + "\"");
     json.Append("\"MatchType\":\"" + this.MatchType + "\"");
     json.Append("\"VTNcoHostName\":\"" + this.VTNCoHostName + "\"");
     ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
         "Removing VlanId map information.",
         json.ToString());
     TransactionManager txnMng = new TransactionManager();
     txnMng.StartTransaction();
     var ope = TransactionManager.Operation.None;
     try {
         VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
             this.VTNCoHostName,
             TransactionManager.OpenMode.WriteMode);
         vLANIDMap.DeregisterVlanId(this.VMNetworkName,
             this.VMSubnetworkName,
             this.MatchType);
         ODLVSEMETW.EventWriteReturnLibrary("VlanId map information is un-registered.", string.Empty);
         ope = TransactionManager.Operation.Commit;
     } catch (Exception ex) {
         Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
         ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
         ope = TransactionManager.Operation.Rollback;
         throw exception;
     } finally {
         txnMng.EndTransaction(ope);
         var JavaScriptSerializer = new JavaScriptSerializer();
         JavaScriptSerializer.MaxJsonLength = int.MaxValue;
         ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
     }
 }
 /// <summary>
 /// Checks whether the change is VLAN ID is consistent or not.
 /// </summary>
 /// <param name="vmnetworkInfo">Corresponding VM network info.</param>
 /// <param name="txnMng">Transaction manager instance.</param>
 /// <param name="VtnHostName">Host name of the VTNCoordinator.</param>
 /// <param name="vmsubnetInfo">Corresponding VM subnet info.</param>
 /// <returns>Empty id the modification is consistent.</returns>
 private static string CheckVlanRange(VMNetworkInfo vmnetworkInfo, TransactionManager txnMng, string VtnHostName, VMSubnetInfo vmsubnetInfo)
 {
     string vlanIdRange = string.Empty;
     if (vmsubnetInfo.CreatedFrom.CompareTo("ODL") == 0) {
         return vlanIdRange;
     }
     vmsubnetInfo.CreatedFrom = "ODLModified";
     VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
            VtnHostName,
            TransactionManager.OpenMode.ReadMode);
     vlanIdRange = vLANIDMap.GetVlanId(vmnetworkInfo.VMNetworkOriginalName, vmsubnetInfo.VMSubnetName);
     if (string.IsNullOrEmpty(vlanIdRange)) {
         return vlanIdRange;
     }
     bool isinRange = CheckVlanId(vlanIdRange, vmsubnetInfo.VBridgeVlanId);
     if (isinRange) {
         return string.Empty;
     } else {
         return vlanIdRange;
     }
 }
        /// <summary>
        /// This method is responsible to add specified vlan entry into the local variable.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            StringBuilder json = new StringBuilder("\"VMNetworkName\":\"" + this.VMNetworkName + "\"");
            json.Append("\"VMSubnetworkName\":\"" + this.VMSubnetworkName + "\"");
            json.Append("\"VlanIdList\":\"" + this.VlanIdList + "\"");
            json.Append("\"VtnHostName\":\"" + this.VtnCoHostName + "\"");
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                "Registering VlanId map information.",
                json.ToString());
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            VSEMVLANIDMapping vSEMVLANIDMapping = null;
            try {
                if (string.IsNullOrWhiteSpace(this.VMNetworkName)) {
                    this.VMNetworkName = "*";
                }

                if (string.IsNullOrWhiteSpace(this.VMSubnetworkName)) {
                    this.VMSubnetworkName = "*";
                }

                VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
                    this.VtnCoHostName,
                    TransactionManager.OpenMode.WriteMode);
                vSEMVLANIDMapping = vLANIDMap.RegisterVlanId(this.VMNetworkName,
                    this.VMSubnetworkName,
                    this.VlanIdList);
                ODLVSEMETW.EventWriteReturnLibrary("VlanId map information is registered.", string.Empty);
                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : VlanId map information registration is failed. \n" + ex.Message);
                ope = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(ope);
                var JavaScriptSerializer = new JavaScriptSerializer();
                JavaScriptSerializer.MaxJsonLength = int.MaxValue;
                string output = "\"vSEMVLANIDMapping\":" + JavaScriptSerializer.Serialize(vSEMVLANIDMapping);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
            }

            // Return the VSEMVLANIDMapping object
            this.WriteObject(vSEMVLANIDMapping);
        }
        /// <summary>
        /// This method is responsible to retrieve the VlanId map information.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            StringBuilder json = new StringBuilder("\"VMNetworkName\":\"" + this.VMNetworkName + "\"");
            json.Append("\"VMSubnetworkName\":\"" + this.VMSubnetworkName + "\"");
            json.Append("\"VtncoHostName\":\"" + this.VTNCoHostName + "\"");
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                "Retrieving VlanId map information.",
                json.ToString());
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            List<VSEMVLANIDMapping> vSEMVLANIDMapping = new List<VSEMVLANIDMapping>();
            try {
                VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
                    this.VTNCoHostName,
                    TransactionManager.OpenMode.ReadMode);

                vSEMVLANIDMapping.AddRange(vLANIDMap.SelectVlanIdWildCardMatch(
                    this.VMNetworkName,
                    this.VMSubnetworkName));

                ODLVSEMETW.EventWriteReturnLibrary("VlanId map information is retrieved.", string.Empty);
                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                ope = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(ope);

                var JavaScriptSerializer = new JavaScriptSerializer();
                JavaScriptSerializer.MaxJsonLength = int.MaxValue;
                string output = "\"vSEMVLANIDMapping\":" + JavaScriptSerializer.Serialize(vSEMVLANIDMapping);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
            }
            if (vSEMVLANIDMapping == null || vSEMVLANIDMapping.Count == 0) {
                this.WriteWarning("Vlan-mapping not found.");
            } else {
                this.WriteObject(vSEMVLANIDMapping);
            }
        }
        /// <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;
        }