/// <summary>
 /// This method is responsible to add specified vlan entry into the local variable.
 /// </summary>
 protected override void DoODLVSEMCmdlet()
 {
     var JavaScriptSerializer = new JavaScriptSerializer();
     JavaScriptSerializer.MaxJsonLength = int.MaxValue;
     StringBuilder json = new StringBuilder("\"VtnHostName\":" + JavaScriptSerializer.Serialize(this.VtnHostName));
     ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
         "Retrieving VM network maping info.",
         json.ToString());
     TransactionManager txnMng = new TransactionManager();
     txnMng.StartTransaction();
     var operation = TransactionManager.Operation.None;
     VMNetworkMappingInfo vMNetworkMappingInfo = null;
     try {
         vMNetworkMappingInfo = VSEMConfiguration.GetVSEMVMNetworkMappingInfo(txnMng, this.VtnHostName);
         ODLVSEMETW.EventWriteReturnLibrary("VM network mapping information is retrieved.", string.Empty);
         if (vMNetworkMappingInfo == null) {
             ODLVSEMETW.EventWriteProcessCmdletWarning(this.CmdletName,
             "VM network mapping information not found.");
             this.WriteWarning("VM network mapping information not found.");
         } else {
             this.WriteObject(this.ToXML(vMNetworkMappingInfo), true);
         }
     } catch (Exception ex) {
         Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
         ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
         operation = TransactionManager.Operation.Rollback;
         throw exception;
     } finally {
         txnMng.EndTransaction(operation);
         string output = "\"vMNetworkMappingInfo\":" + JavaScriptSerializer.Serialize(vMNetworkMappingInfo);
         ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
     }
 }
        /// <summary>
        /// Verify whether the specified VMNetwork is HNV resource or not.
        /// </summary>
        /// <param name="vmnetwork">VMNetwork instance.</param>
        /// <returns>True if HNV resource, else false.</returns>
        public bool IsHNVVMNetwork(VMNetwork vmnetwork)
        {
            if (vmnetwork == null) {
                return false;
            }

            // Create txn and read configuration.
            var txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var logicalNetworkConfig = new LogicalNetworkConfig(this.VtnHostName);
            txnMng.SetConfigManager(logicalNetworkConfig, TransactionManager.OpenMode.ReadMode);

            bool ret;

            // Get LogicalNetowork that Guid equals vmnetwork.LogicalNetwork.
            LogicalNetwork logicalnetwork = logicalNetworkConfig.GetLogicalNetworkById(vmnetwork.LogicalNetwork);
            if (logicalnetwork == null) {
                ret = false;
                goto txnEnd;
            }

            var hnvLogicalNetworkManagement = new HNVLogicalNetworkManagement(this.VtnHostName);
            ret = hnvLogicalNetworkManagement.IsHNVLogicalNetwork(logicalnetwork);

            if (ret == false) {
                ODLVSEMETW.EventWriteNotHNVVMNetwork(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format("VMNetwork name is {0}", vmnetwork.Name));
            }
            txnEnd:
            txnMng.EndTransaction(TransactionManager.Operation.None);
            return ret;
        }
 /// <summary>
 /// This method is responsible for extracting the list of VSEMVmNetwork
 /// from the VSEM repository for the corresponding connection.
 /// </summary>
 /// <param name="txnMng">Transaction manager.</param>
 /// <param name="VtnHostName">Host name of the VTNCoordinator.</param>
 /// <returns>List of VSEMVmNetwork instances attached with the connection.</returns>
 public static VMNetworkMappingInfo GetVSEMVMNetworkMappingInfo(TransactionManager txnMng, string VtnHostName)
 {
     var JavaScriptSerializer = new JavaScriptSerializer();
     JavaScriptSerializer.MaxJsonLength = int.MaxValue;
     StringBuilder json = new StringBuilder("\"TransactionManager\":" + JavaScriptSerializer.Serialize(txnMng));
     ODLVSEMETW.EventWriteStartLibrary(
             MethodBase.GetCurrentMethod().Name,
             json.ToString());
     ODLVSEMETW.EventWriteExtractVMNetworkInfolist(
         "Extracting list of VMNetwork Info.",
         string.Empty);
     if (string.IsNullOrWhiteSpace(VtnHostName)) {
         VSEMConfig vsemConfig = new VSEMConfig();
         try {
             txnMng.SetConfigManager(vsemConfig, TransactionManager.OpenMode.ReadMode);
         } catch (Exception ex) {
             ODLVSEMETW.EventWriteConfigManagerFileIOError(
                 MethodBase.GetCurrentMethod().Name,
                 string.Format(CultureInfo.CurrentCulture,
                 "VSEM.config {0}\n",
                 configFileIOErrorValidationMessage) +
                 ex.Message);
             ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
             throw new InvalidOperationException(
                 string.Format(CultureInfo.CurrentCulture,
                 "Either the NetworkService is not added in SCVMM or VSEM.config {0}",
                 configFileIOErrorValidationMessage));
         }
         VtnHostName = vsemConfig.Info.ServerName;
     }
     if (string.IsNullOrWhiteSpace(VtnHostName)) {
         throw new ArgumentException(
                 "Parameter 'VTNCoordinatorHostName' is null or invalid.");
     }
     var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
     try {
         txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.ReadMode);
         var ret = vMNetworkConfig.VMNetwork.VMNetworkMappingInformation;
         string output = "\"VMNetwork\":" + JavaScriptSerializer.Serialize(ret);
         ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
             output);
         return ret;
     } catch (System.IO.FileNotFoundException) {
         // Ignore if the file is not yet created and return empty list.
         return new VMNetworkMappingInfo();
     } catch (Exception ex) {
         ODLVSEMETW.EventWriteConfigManagerFileIOError(
             MethodBase.GetCurrentMethod().Name,
             string.Format(CultureInfo.CurrentCulture,
             "VMNetwork.config {0}\n{1}",
             configFileIOErrorValidationMessage,
             ex.Message));
         throw new InvalidOperationException(
             string.Format(CultureInfo.CurrentCulture,
             "VMNetwork.config {0}",
             configFileIOErrorValidationMessage));
     }
 }
 /// <summary>
 /// Initializes a new instance of the VSEMSynchronization class.
 /// </summary>
 /// <param name="txnMng">Transaction Manager.</param>
 public VSEMSynchronization(TransactionManager txnMng)
 {
     var JavaScriptSerializer = new JavaScriptSerializer();
     JavaScriptSerializer.MaxJsonLength = int.MaxValue;
     StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
     ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
            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.");
     }
     var vSEMConfig = new VSEMConfig();
     try {
         txnMng.SetConfigManager(vSEMConfig, TransactionManager.OpenMode.ReadMode);
     } catch (Exception ex) {
         ODLVSEMETW.EventWriteConfigManagerFileIOError(
             MethodBase.GetCurrentMethod().Name,
             string.Format(CultureInfo.CurrentCulture,
             "VSEM.config {0}\n",
             configFileIOErrorValidationMessage) +
             ex.Message);
         ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
         throw new InvalidOperationException(
             string.Format(CultureInfo.CurrentCulture,
             "Either the NetworkService is not added in SCVMM or VSEM.config {0}",
             configFileIOErrorValidationMessage));
     }
     try {
         var odlInformation = new OdlInformation(vSEMConfig.Info.ServerName);
         txnMng.SetConfigManager(odlInformation, TransactionManager.OpenMode.ReadMode);
         this.ConnectionString = odlInformation.GetConnectionString();
         this.Credential = odlInformation.GetCredentials();
     } catch (Exception ex) {
         ODLVSEMETW.EventWriteConfigManagerFileIOError(
             MethodBase.GetCurrentMethod().Name,
             string.Format(CultureInfo.CurrentCulture,
             "ODLInformation.config {0}\n",
             configFileIOErrorValidationMessage) +
             ex.Message);
         ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
         throw new InvalidOperationException(
             string.Format(CultureInfo.CurrentCulture,
             "ODLInformation.config {0}",
             configFileIOErrorValidationMessage));
     }
 }
        /// <summary>
        /// This method is responsible to add specified vlan entry into the local variable.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                "Synchronizing SCVMM and ODL.",
                string.Empty);
            VSEMSynchronization vSEMSynchronization = null;
            if (string.IsNullOrEmpty(this.SCVMSubnets)) {
                TransactionManager txnMng = new TransactionManager();
                txnMng.StartTransaction();
                var operation = TransactionManager.Operation.None;
                try {
                    vSEMSynchronization = new VSEMSynchronization(txnMng);

                    vSEMSynchronization.SynchronizeVTNObjects(txnMng);
                    operation = TransactionManager.Operation.Commit;
                } catch (Exception ex) {
                    Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                    ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : synchronization is failed. \n" + ex.Message);
                    operation = TransactionManager.Operation.Rollback;
                    ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
                    throw exception;
                } finally {
                    txnMng.EndTransaction(operation);
                }
            } else {
                TransactionManager txnMng = new TransactionManager();
                txnMng.StartTransaction();
                var operation = TransactionManager.Operation.Commit;
                try {
                    vSEMSynchronization = new VSEMSynchronization(txnMng);
                    vSEMSynchronization.StatusAfterRefreshNetworkService(txnMng, this.SCVMSubnets);
                } catch (Exception ex) {
                    operation = TransactionManager.Operation.Rollback;
                    if (ex.GetType() != typeof(NSPluginSynchronizationException)) {
                        ODLVSEMETW.EventWriteFailedCmdlet("NetworkService could not be refreshed in SCVMM. " + ex.Message,
                           string.Empty);

                        throw new NSPluginSynchronizationException("NetworkService could not be refreshed in SCVMM. " + ex.Message);
                    } else {
                        throw;
                    }
                } finally {
                    txnMng.EndTransaction(operation);
                    ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
                }
            }
        }
 /// <summary>
 /// This constructor is responsible for instantiating the vlanMapInfo.
 /// </summary>
 /// <param name="txnMng">Transaction manager object.</param>
 /// <param name="VtnHostName">Parent Folder name.</param>
 /// <param name="mode">Write or Read mode in which file to be opened.</param>
 public VLANIDMap(TransactionManager txnMng,
     string VtnHostName,
     TransactionManager.OpenMode mode)
 {
     var JavaScriptSerializer = new JavaScriptSerializer();
     JavaScriptSerializer.MaxJsonLength = int.MaxValue;
     StringBuilder json = new StringBuilder("\"vMNetworkName\":\"" + VtnHostName + "\"");
     json.Append(" \"TransactionManager\":" + JavaScriptSerializer.Serialize(txnMng));
     json.Append(" \"OpenMode\":\"" + mode + "\"");
     ODLVSEMETW.EventWriteStartLibrary(
         MethodBase.GetCurrentMethod().Name,
         json.ToString());
     if (txnMng == null) {
         throw new ArgumentException(
             "Parameter 'txnMng' is null or invalid.");
     }
     if (string.IsNullOrWhiteSpace(VtnHostName)) {
         VSEMConfig vsemConfig = new VSEMConfig();
         txnMng.SetConfigManager(vsemConfig, TransactionManager.OpenMode.ReadMode);
         VtnHostName = vsemConfig.Info.ServerName;
     }
     if (string.IsNullOrWhiteSpace(VtnHostName)) {
         throw new ArgumentException(
                 "Parameter 'VTNCoordinatorHostName' is null or invalid.");
     }
     try {
         VLANIDMappingConfig vLANIDMappingConfig = new VLANIDMappingConfig(VtnHostName);
         txnMng.SetConfigManager(vLANIDMappingConfig, mode);
         this.vlanMapInfo = vLANIDMappingConfig.VLANIDMapping;
     } catch (System.IO.IOException) {
         ODLVSEMETW.EventWriteConfigManagerFileIOError(MethodBase.GetCurrentMethod().Name,
             configFileIOErrorValidationMessage);
         throw new InvalidOperationException(
             configFileIOErrorValidationMessage);
     }
 }
        /// <summary>
        /// This function is responsible to remove the information about the
        /// vm network(s) for the connection.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            bool needRefresh = false;
            VSEMVMSubnetManagement vSEMVmNetworkDefinitionManagement = null;
            try {
                var JavaScriptSerializer = new JavaScriptSerializer();
                JavaScriptSerializer.MaxJsonLength = int.MaxValue;
                StringBuilder json = new StringBuilder("\"VMSubnetId\":\"" + this.VMSubnetId + "\"");
                ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                    "Removing VMSubnet.",
                    json.ToString());
                string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
                vSEMVmNetworkDefinitionManagement =
                    new VSEMVMSubnetManagement(connectionString,
                this.conn.Credential);
                needRefresh = vSEMVmNetworkDefinitionManagement.RemoveVmNetworkDefinition(
                    txnMng,
                    this.VMSubnetId,
                    this.conn,
                    out this.name);
                ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                "VM Subnet with ID: {0} is removed",
                this.VMSubnetId.ToString("B")),
                string.Empty);

                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                ope = TransactionManager.Operation.Rollback;
                if (!string.IsNullOrEmpty(this.name)
                    && string.Compare(ex.GetType().ToString(), "System.Net.WebException", StringComparison.Ordinal) == 0) {
                    ODLVSEMETW.EventWriteFailedCmdlet(string.Format(CultureInfo.CurrentCulture,
                        "Due to some problem in connection with ODL, VSEM VM Subnet '{0}' removal process is terminated in the middle of the request. vBridge may have been deleted from ODL, Please check. Please retry and delete VM Subnet if inconsistency is created.",
                    this.name),
                    string.Empty);
                    Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(
                        new System.Net.WebException(string.Format(CultureInfo.CurrentCulture,
                            "Due to some problem in connection with ODL, VSEM VM Subnet '{0}' removal process is terminated in the middle of the request. vBridge may have been deleted from ODL, Please check. Please retry and delete VM Subnet if inconsistency is created.",
                            this.name),
                            ex));
                    ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                    ope = TransactionManager.Operation.Rollback;
                    throw exception;
                } else {
                    ODLVSEMETW.EventWriteFailedCmdlet(
                        "VSEM VM Subnet removal is failed.",
                        string.Empty);
                    Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                    ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + exception.Message);
                    ope = TransactionManager.Operation.Rollback;
                    throw exception;
                }
            } finally {
                txnMng.EndTransaction(ope);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, 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 function is responsible for creating a VM Network
        /// with one VM Subnet on the VSEM.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder(" \"IPSubnets\":" + JavaScriptSerializer.Serialize(this.IPSubnets));
            json.Append("\"MaxNumberOfPorts\":\"" + this.MaxNumberOfPorts + "\"");
            json.Append("\"VMSubnetName\":\"" + this.VMSubnetName + "\"");
            json.Append("\"VMNetworkName\":\"" + this.VMNetworkName + "\"");
            json.Append("\"LogicalNetworkDefinitionId\":\"" + this.LogicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                   "VM Network creation process started.",
                   json.ToString());
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            VMNetwork nw = null;
            string vtnName = string.Empty;
            string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
            VSEMVMNetworkManagement vSEMVmNetworkManagement =
                new VSEMVMNetworkManagement(connectionString, this.conn.Credential);
            try {
                nw = vSEMVmNetworkManagement.CreateVMNetwork(txnMng,
                    this.VMSubnetName,
                    this.VMNetworkName,
                    this.MaxNumberOfPorts,
                    this.IPSubnets,
                    this.LogicalNetworkDefinitionId,
                    this.conn,
                    out vtnName);
                ODLVSEMETW.EventWriteReturnLibrary("VM network is created.",
                    string.Empty);

                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                Exception userException = ex;
                ODLVSEMETW.EventWriteFailedCmdlet(
                    "VM network creation is failed. ODL changes rollback is started.",
                    string.Empty);
                ope = TransactionManager.Operation.Rollback;
                try {
                    if (!string.IsNullOrEmpty(vtnName)) {
                        vSEMVmNetworkManagement.RemoveVmNetwork(vtnName);
                        ODLVSEMETW.EventWriteFailedCmdlet(
                            "VM network creation is failed. ODL changes are successfully rolled back.",
                            string.Empty);
                    }
                } catch (Exception except) {
                    ODLVSEMETW.EventWriteFailedCmdlet(
                        string.Format(CultureInfo.CurrentCulture,
                        "Due to some problem in connection with ODL, VSEM VM Network creation process is terminated in the middle of the request. VTN '{0}' may have been created on ODL, Please check. Please delete the VTN from ODL to maintain the consistency between ODL and SCVMM.\n{1}",
                        vtnName,
                        except.Message),
                        string.Empty);
                    userException =
                        new System.Net.WebException(string.Format(CultureInfo.CurrentCulture,
                            "Due to some problem in connection with ODL, VSEM VM Network creation process is terminated in the middle of the request. VTN '{0}' may have been created on ODL, Please check. Please delete the VTN from ODL to maintain the consistency between ODL and SCVMM.",
                            vtnName),
                            ex);
                }

                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(userException);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                ope = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(ope);

                string output = "\"VM Network\":" + JavaScriptSerializer.Serialize(nw);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
                this.WriteObject(nw);
            }
        }
        /// <summary>
        /// This method is responsible for extracting the VSEMVirtualPortProfile
        /// from the VSEM repository for the corresponding connection for the specified id.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="id">Id of the VSEMVirtualPortProfile.</param>
        /// <returns>VSEMVirtualPortProfile instance attached with the connection.</returns>
        public VSEMVirtualPortProfile GetVSEMVirtualPortProfileById(
            TransactionManager txnMng,
            Guid id)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"TransactionManager\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"id\":" + id.ToString("B"));
            ODLVSEMETW.EventWriteStartLibrary(
                    MethodBase.GetCurrentMethod().Name,
                    json.ToString());
            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.");
            }

            ODLVSEMETW.EventWriteExtractVirtualPortProfile(
                "Extracting VirtualPortProfile Info.", string.Empty);
            var portProfileConfig = new PortProfileConfig();
            try {
                txnMng.SetConfigManager(portProfileConfig, TransactionManager.OpenMode.ReadMode);
                var ret = portProfileConfig.VirtualPortProfiles.FirstOrDefault(
                    port => port.Id == id);
                string output = "\"VSEMVirtualPortProfile\":" + JavaScriptSerializer.Serialize(ret);
                ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, output);
                return ret;
            } catch (Exception ex) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "PortProfile.config {0}\n{1}",
                    configFileIOErrorValidationMessage,
                    ex.Message));
                ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, string.Empty);
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "PortProfile.config {0}",
                    configFileIOErrorValidationMessage));
            }
        }
        /// <summary>
        /// This method is responsible for extracting the VSEMVmNetwork
        /// from the VSEM repository for the corresponding connection for the specified id.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="id">Id of the VSEMVmNetwork.</param>
        /// <returns>VSEMVmNetwork instance attached with the connection.</returns>
        public VMNetwork GetVSEMVMNetworkById(TransactionManager txnMng, Guid id)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"TransactionManager\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"id\":" + id.ToString("B"));
            ODLVSEMETW.EventWriteStartLibrary(
                    MethodBase.GetCurrentMethod().Name,
                    json.ToString());
            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.");
            }

            ODLVSEMETW.EventWriteExtractVMNetworkInfo(
                "Extracting VMNetwork Info.",
            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.ReadMode);

                var ret = vMNetworkConfig.VMNetwork.VmNetworks.FirstOrDefault(
                    nw => nw.Id == id);
                string output = "\"VMNetwork\":" + JavaScriptSerializer.Serialize(ret);
                ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
                    output);
                return ret;
            } catch (System.IO.FileNotFoundException) {
                // Ignore if the file is not yet created and return empty list.
                return new VMNetwork();
            } 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));
            }
        }
        /// <summary>
        /// Remove completely the entities removed on SCVMM after refresh network service.
        /// </summary>
        /// <param name="scvmsubnets">Collection of VMSubnets on SCVMM.</param>
        /// <param name="txnMng">Transaction manager instance.</param>
        private void HandleVMSubnetsDependencies(List<string> scvmsubnets, TransactionManager txnMng)
        {
            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));
            }
            List<string> vsemvmsubnets = new List<string>();
            var vmnetworkInfo = vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo;
            vmnetworkInfo.ForEach(vmn => vmn.VMSubnetInfo.ForEach(vms => {
                if (vms.VBridgeName.CompareTo(string.Empty) == 0) {
                    vsemvmsubnets.Add(vms.VMSubnetID.ToString());
                }
            }));

            List<string> vmsubnetsDeleted = vsemvmsubnets.Except(scvmsubnets).ToList();
            vmnetworkInfo.ForEach(vmn => vmn.VMSubnetInfo.RemoveAll(vms => vmsubnetsDeleted.Contains(vms.VMSubnetID.ToString())));
            vmnetworkInfo.RemoveAll(vmn => vmn.VMSubnetInfo.Count == 0);
            vmnetworkInfo.ForEach(vmn => {
                vmn.VMSubnetInfo.ForEach(vms => {
                    if (vms.VBridgeName.CompareTo(string.Empty) == 0) {
                        vms.Description = "VM Subnet could not be deleted on SCVMM due to dependent resources.\nEither one or more VM Subnets associated with the corresponding VM Network have dependent resources such as VM templates, virtual network adapters etc. Or corresponding VM Network has dependent resources such as VM templates, virtual network adapters etc.";
                    }
                });
                if (vmn.VTNName.CompareTo(string.Empty) == 0) {
                    vmn.Description = "VM Network could not be deleted on SCVMM due to dependent resources.\nIt has dependent resources such as VM templates, virtual network adapters etc.";
                }
            });
        }
 /// <summary>
 /// This method is responsible for extracting the VSEMSystemInfo
 /// from the VSEM repository for the corresponding connection.
 /// </summary>
 /// <param name="txnMng">Transaction manager.</param>
 /// <returns>VSEMSystemInfo instance attached with the connection.</returns>
 public NetworkServiceSystemInformation GetVSEMSystemInfo(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());
     ODLVSEMETW.EventWriteExtractsystemInfo("Extracting System Info.", string.Empty);
     var vsemConfig = new VSEMConfig();
     try {
         txnMng.SetConfigManager(vsemConfig, TransactionManager.OpenMode.ReadMode);
     } catch (Exception ex) {
         ODLVSEMETW.EventWriteConfigManagerFileIOError(
             MethodBase.GetCurrentMethod().Name,
             string.Format(CultureInfo.CurrentCulture,
             "VSEM.config {0}\n{1}",
             configFileIOErrorValidationMessage,
             ex.Message));
         throw new InvalidOperationException(
             string.Format(CultureInfo.CurrentCulture,
             "VSEM.config {0}",
             configFileIOErrorValidationMessage));
     }
     string output = "\"NetworkServiceSystemInformation\":" + JavaScriptSerializer.Serialize(vsemConfig.NetworkServiceSystemInformation);
     ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, output);
     return vsemConfig.NetworkServiceSystemInformation;
 }
 /// <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 function is responsible to synchronize the network configuration between ODL and SCVMM.
        /// </summary>
        /// <param name="vtns">List of VTNs on ODL.</param>
        /// <param name="vMNetworkConfig">VMNetwork.config file instance.</param>
        /// <param name="logicalNetworkId">Logical network ID.</param>
        /// <param name="logicalNetworkDefinitionId">Logical network definition ID.</param>
        /// <param name="txnMng">Transaction manager instance.</param>
        /// <param name="VtnHostName">Host name of the VTNCoordinator.</param>
        private void CompareVTNObjects(List<Vtn> vtns, VMNetworkConfig vMNetworkConfig, Guid logicalNetworkId, Guid? logicalNetworkDefinitionId, TransactionManager txnMng, string VtnHostName)
        {
            var vmnetworks = vMNetworkConfig.VMNetwork;
            foreach (Vtn vtn in vtns) {
                var vmnetworkInfo = vmnetworks.VMNetworkMappingInformation.VMNetworkInfo.FirstOrDefault(vmnet => vmnet.VTNName.Equals(vtn.Name));
                if (vmnetworkInfo != null) {
                    VMNetwork vmnetwork = vmnetworks.VmNetworks.FirstOrDefault(vmn => vmn.Id == vmnetworkInfo.VMNetworkID);
                    this.SyncVTN(logicalNetworkDefinitionId, vmnetwork, vtn, vmnetworkInfo, txnMng, VtnHostName);
                } else {
                    VMNetwork vMNetwork = VSEMVMNetworkManagement.CreateVtnVmNetwork(vtn.Name);
                    vMNetwork.LogicalNetwork = logicalNetworkId;

                    vMNetworkConfig.VMNetwork.VmNetworks.Add(vMNetwork);
                    if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo == null) {
                        vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo =
                            new List<VMNetworkInfo>();
                    }
                    var vmnetInfo = new VMNetworkInfo {
                        VMNetworkID = vMNetwork.Id,
                        VMNetworkName = string.Empty,
                        VTNName = vtn.Name,
                        VMSubnetInfo = new List<VMSubnetInfo>(),
                        CreatedFrom = "ODL",
                        Description = "VM Network corresponding to this VTN is not created on SCVMM",
                        VMNetworkOriginalName = vMNetwork.Name
                    };
                    vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Add(
                        vmnetInfo);
                    foreach (Vbridge vbr in vtn.Vbridges) {
                        this.AddVMSubnet(vmnetInfo, vbr, vMNetwork, logicalNetworkDefinitionId);
                    }
                    ////--------VTN is added on ODL
                }
            }
        }
 /// <summary>
 /// Compare the VTN.
 /// </summary>
 /// <param name="logicalNetworkDefinitionId">Logfical network definition ID.</param>
 /// <param name="vmnetwork">Corresponding VM network.</param>
 /// <param name="vtn">VTN to compare.</param>
 /// <param name="vmnetworkInfo">Corresponding VM network info.</param>
 /// <param name="txnMng">Transaction manager instance.</param>
 /// <param name="VtnHostName">Host name of the VTNCoordinator.</param>
 /// <returns>Indicateds the need to refresh the network service.</returns>
 public bool SyncVTN(Guid? logicalNetworkDefinitionId, VMNetwork vmnetwork, Vtn vtn, VMNetworkInfo vmnetworkInfo, TransactionManager txnMng, string VtnHostName)
 {
     bool needRefresh = false;
     foreach (Vbridge vbr in vtn.Vbridges) {
         var vmsubnetInfo = vmnetworkInfo.VMSubnetInfo.FirstOrDefault(vmsubnet => vmsubnet.VBridgeName.Equals(vbr.Name));
         if (vmsubnetInfo != null) {
             if (vmsubnetInfo.VBridgeVlanId != vbr.VlanId && !string.IsNullOrEmpty(vmsubnetInfo.VMSubnetName)) {
                 string vlanRange = CheckVlanRange(vmnetworkInfo, txnMng, VtnHostName, vmsubnetInfo);
                 if (vlanRange.CompareTo(string.Empty) == 0) {
                     vmsubnetInfo.Description = string.Format("VLAN ID of this VM Subnet is changed from {0} to {1} on ODL. VM attached to this VM Subnet prior to this change (i.e, with VLAN ID {0}), will not be operable now.", vmsubnetInfo.VMSubnetVlanId, vbr.VlanId);
                     vmsubnetInfo.VMSubnetVlanId = vbr.VlanId;
                     var vmsubnet = vmnetwork.VMSubnets.FirstOrDefault(subnet => subnet.Id.Equals(vmsubnetInfo.VMSubnetID));
                     vmsubnet.SegmentId.PrimarySegmentIdentifier = Convert.ToUInt32(vbr.VlanId);
                     needRefresh = true;
                 } else {
                     vmsubnetInfo.Description = string.Format("VLAN ID of this VM Subnet is changed from {0} to {1} on ODL. But {1} does not lie in the specified range '{2}'. VM attached to this VM Subnet will not be operable now.", vmsubnetInfo.VMSubnetVlanId, vbr.VlanId, vlanRange);
                 }
             }
             vmsubnetInfo.VBridgeVlanId = vbr.VlanId;
         } else {
             this.AddVMSubnet(vmnetworkInfo, vbr, vmnetwork, logicalNetworkDefinitionId);
             needRefresh = true;
         }
     }
     foreach (var subnetInfo in vmnetworkInfo.VMSubnetInfo) {
         Vbridge vbr = vtn.Vbridges.FirstOrDefault(odlItem => odlItem.Name.CompareTo(subnetInfo.VBridgeName) == 0);
         if (vbr == null) {
             RemoveVMSubnetSync(null, subnetInfo.VMSubnetID, vmnetwork, vmnetworkInfo);
             needRefresh = true;
         }
     }
     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>
 /// Completes the sync operation for the removed removed entities.
 /// </summary>
 /// <param name="txnMng">Transaction Manager instance.</param>
 /// <param name="SCVMSubnets">Names of VMSubnets present in SCVMM.</param>
 public void StatusAfterRefreshNetworkService(TransactionManager txnMng, string SCVMSubnets)
 {
     this.HandleVMSubnetsDependencies(SCVMSubnets.Split(',').ToList(), txnMng);
 }
 /// <summary>
 /// Saves the VTNCordinator information.
 /// </summary>
 /// <param name="txnMng">Transaction Manager.</param>
 /// <param name="VtnHostName">Host name of the VTNCoordinator.</param>
 private void SaveVtncoInfo(TransactionManager txnMng, string VtnHostName)
 {
     OdlInformation odlInfo = new OdlInformation(VtnHostName);
     txnMng.SetConfigManager(odlInfo, TransactionManager.OpenMode.WriteMode);
     odlInfo.SetCredentials(this.Credential, this.ConnectionString);
 }
        /// <summary>
        /// This method is responsible to remove static Ip address pool.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            VSEMIPAddressPoolManagement vSEMIPAddressPoolManagement = null;
            try {
                StringBuilder json = new StringBuilder("\"IPAddressPoolId\":\"" + this.IPAddressPoolId + "\"");
                ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                    "Removing IP Address Pool.",
                    json.ToString());
                string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
                vSEMIPAddressPoolManagement =
                    new VSEMIPAddressPoolManagement(connectionString,
                this.conn.Credential);
                if (!vSEMIPAddressPoolManagement.RemoveIpAddressPool(
                                   txnMng,
                                   this.IPAddressPoolId,
                                   this.conn)) {
                    ODLVSEMETW.EventWriteRemoveIPPoolWarning(this.CmdletName,
                    string.Format(CultureInfo.CurrentCulture,
                    "IP Address Pool '{0}' not found.",
                    this.IPAddressPoolId.ToString("B")));

                    // if IP address pool was not found in Remove-Odl.VSEMRemoveIpAddressPool,
                    // ignore it
                }

                ODLVSEMETW.EventWriteReturnLibrary("VSEMIpAddressPool is removed.",
                    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);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
            }
        }
        /// <summary>
        /// This method is responsible for extracting the list of VSEMLogicalNetworkDefinition
        /// from the VSEM repository for the corresponding connection.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <returns>List of VSEMLogicalNetworkDefinition instances
        /// attached with the connection.</returns>
        public List<LogicalNetwork> GetVSEMLogicalNetwork(
            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());
            ODLVSEMETW.EventWriteExtractFabricNetworkDefinitionlist(
                "Extracting list of Logical Network Info.",
                string.Empty);
            string VtnHostName = this.ConnectionString;

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

            VtnHostName = VtnHostName.Split('.', ':').First();
            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));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }
            string output = "\"LogicalNetwork\":" + JavaScriptSerializer.Serialize(logicalNetworkConfig.LogicalNetworks);
            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, output);
            return logicalNetworkConfig.LogicalNetworks;
        }
 /// <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>
 /// This method is responsible for extracting the list of VSEMVirtualPortProfile
 /// from the VSEM repository for the corresponding connection.
 /// </summary>
 /// <param name="txnMng">Transaction manager.</param>
 /// <returns>List of VSEMVirtualPortProfile instances
 /// attached with the connection.</returns>
 public List<VSEMVirtualPortProfile> GetVSEMVirtualPortProfile(
     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());
     ODLVSEMETW.EventWriteExtractVirtualPortProfilelist(
         "Extracting list of VirtualPortProfile Info.", string.Empty);
     var portProfileConfig = new PortProfileConfig();
     try {
         txnMng.SetConfigManager(portProfileConfig, TransactionManager.OpenMode.ReadMode);
     } catch (Exception ex) {
         ODLVSEMETW.EventWriteConfigManagerFileIOError(
             MethodBase.GetCurrentMethod().Name,
             string.Format(CultureInfo.CurrentCulture,
             "PortProfile.config {0}\n{1}",
             configFileIOErrorValidationMessage,
             ex.Message));
         throw new InvalidOperationException(
             string.Format(CultureInfo.CurrentCulture,
             "PortProfile.config {0}",
             configFileIOErrorValidationMessage));
     }
     string output = "\"VSEMVirtualPortProfile\":" + JavaScriptSerializer.Serialize(portProfileConfig.VirtualPortProfiles);
     ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, output);
     return portProfileConfig.VirtualPortProfiles;
 }
        /// <summary>
        /// Initialize of ConfigManager.
        /// </summary>
        /// <param name="mode">Open mode of config file.</param>
        public void Initialize(TransactionManager.OpenMode mode)
        {
            ConfigManagerBase config = null;

            if (mode == TransactionManager.OpenMode.WriteMode) {
                FileInfo info = new FileInfo(this.Path);
                if (info.Directory.Exists == false) {
                    info.Directory.Create();
                }
            }

            // Open the config file.
            // (Retry max RETRY_COUNT times at RETRY_INTERVAL msec intervals)
            for (var cnt = 1; cnt <= RETRY_COUNT; cnt++) {
                try {
                    if (mode == TransactionManager.OpenMode.WriteMode) {
                        // Open the config file by WriteMode.
                        this.FileStreamInfo = new FileStream(this.Path,
                            FileMode.OpenOrCreate,
                            FileAccess.ReadWrite,
                            FileShare.None);
                    } else if (mode == TransactionManager.OpenMode.ReadMode) {
                        // Open the config file by ReadMode.
                        this.FileStreamInfo = new FileStream(this.Path,
                            FileMode.Open,
                            FileAccess.Read,
                            FileShare.Read);
                    }

                    ODLVSEMETW.EventWriteConfigManagerFileOpen(this.Path, (uint)mode);
                    break;
                } catch (Exception e) {
                    // If the config file is locked, retry the open.
                    if (e.HResult != unchecked((int)FILE_LOCK_FAILED_CODE) || cnt == RETRY_COUNT) {
                        ODLVSEMETW.EventWriteConfigManagerFileIOError(MethodBase.GetCurrentMethod().Name, e.Message);
                        throw;
                    }
                    Thread.Sleep(RETRY_INTERVAL);
                }
            }

            try {
                // If the config file is not empty, get the config info.
                if (this.FileStreamInfo.Length != 0) {
                    var dcs = new DataContractSerializer(this.GetType());
                    config = (ConfigManagerBase)dcs.ReadObject(this.FileStreamInfo);
                }

                this.SetEntity(config);
            } catch (Exception e) {
                // The config file closed because failed to get the config info.
                ODLVSEMETW.EventWriteConfigManagerFileIOError(MethodBase.GetCurrentMethod().Name, e.Message);
                this.FileStreamInfo.Close();
                throw;
            }
        }
        /// <summary>
        /// This method is responsible for extracting the list of VSEMVmNetwork
        /// from the VSEM repository for the corresponding connection.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <returns>List of VSEMVmNetwork instances attached with the connection.</returns>
        public List<VMNetwork> GetVSEMVMNetwork(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());
            ODLVSEMETW.EventWriteExtractVMNetworkInfolist(
                "Extracting list of VMNetwork Info.",
                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.ReadMode);
                var ret = vMNetworkConfig.VMNetwork.VmNetworks;
                string output = "\"VMNetwork\":" + JavaScriptSerializer.Serialize(ret);
                ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
                    output);
                return ret;
            } catch (System.IO.FileNotFoundException) {
                // Ignore if the file is not yet created and return empty list.
                return new List<VMNetwork>();
            } catch (Exception ex) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}\n{1}",
                    configFileIOErrorValidationMessage,
                    ex.Message));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }
        }
        /// <summary>
        /// This function is responsible for updating the IP address pool.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder(" \"NetworkGatewayInfo\":" + JavaScriptSerializer.Serialize(this.NetworkGatewayInfo));
            json.Append("\"Name\":\"" + this.Name + "\"");
            json.Append("\"Description\":\"" + this.Description + "\"");
            json.Append("\"IPAddressSubnet\":\"" + this.IPAddressSubnet + "\"");
            json.Append("\"AddressRangeStart\":\"" + this.AddressRangeStart + "\"");
            json.Append("\"AddressRangeEnd\":\"" + this.AddressRangeEnd + "\"");
            json.Append("\"IPAddressPoolId\":\"" + this.IPAddressPoolId + "\"");
            ODLVSEMETW.EventWriteDoCmdlet(MethodBase.GetCurrentMethod().Name,
                    "Updating IP Address Pool.",
                    string.Empty);
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var ope = TransactionManager.Operation.None;
            VSEMIPAddressPoolManagement vSEMIPAddressPoolManagement = null;
            try {
                string connectionString =
                this.conn.ConnectionString.Split(',').FirstOrDefault();
                vSEMIPAddressPoolManagement =
                    new VSEMIPAddressPoolManagement(connectionString,
                this.conn.Credential);
                IPAddressPool pool = vSEMIPAddressPoolManagement.UpdateIpAddressPool(txnMng,
                    this.Name,
                    this.Description,
                    this.IPAddressSubnet,
                    this.AddressRangeStart,
                    this.AddressRangeEnd,
                    this.NetworkGatewayInfo,
                    this.conn,
                    this.IPAddressPoolId);
                ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                    "VSEM IP address pool with ID: {0} is updated",
                    this.IPAddressPoolId.ToString("B")),
                    string.Empty);
                string output = "\"pool\":" + JavaScriptSerializer.Serialize(pool);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
                this.WriteObject(pool);

                ope = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                ope = TransactionManager.Operation.Rollback;
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
                throw exception;
            } finally {
                txnMng.EndTransaction(ope);
            }
        }
        /// <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>
        /// This function is responsible to retrieve the SystemInfo for the connection.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                "Retrieving system information.",
                string.Empty);
            NetworkServiceSystemInformation info = null;
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var operation = TransactionManager.Operation.None;
            try {
                info = this.conn.GetVSEMSystemInfo(txnMng);
                ODLVSEMETW.EventWriteReturnLibrary("System information is retrieved.", string.Empty);

                if (info == null) {
                    ODLVSEMETW.EventWriteProcessCmdletWarning(this.CmdletName,
                        "System information not found.");
                    this.WriteWarning("System information not found.");
                } else {
                    this.WriteObject(info);
                }
            } catch (Exception ex) {
                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                operation = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(operation);
            string output = "\"NetworkServiceSystemInformation\":" + JavaScriptSerializer.Serialize(info);
            ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
            }
        }
        /// <summary>
        /// This function is responsible to retrieve the information about the uplink port
        /// profile(s) for the connection.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder(" \"ID\":" + JavaScriptSerializer.Serialize(this.ID));
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                "Retrieving uplink port profile(s).",
                json.ToString());

            List<VSEMUplinkPortProfile> profiles = null;
            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var operation = TransactionManager.Operation.None;
            try {
                if (this.ID != Guid.Empty) {
                    profiles = new List<VSEMUplinkPortProfile>();
                    profiles.Add(this.conn.GetVSEMUplinkPortProfileById(txnMng, this.ID));
                    ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                        "Uplink port profile is retrieved by ID:{0}",
                        this.ID.ToString("B")),
                        string.Empty);

                    if (profiles[0] == null) {
                        ODLVSEMETW.EventWriteProcessCmdletWarning(this.CmdletName,
                        string.Format(CultureInfo.CurrentCulture,
                        "ID '{0}' not found.",
                        this.ID.ToString("B")));
                        this.WriteWarning(string.Format(CultureInfo.CurrentCulture,
                            "ID '{0}' not found.",
                            this.ID.ToString("B")));
                    } else {
                        this.WriteObject(profiles);
                    }
                } else {
                    profiles = this.conn.GetVSEMUplinkPortProfile(txnMng);
                    ODLVSEMETW.EventWriteReturnLibrary(
                        "Uplink port profile(s) retrieved.",
                        string.Empty);
                    if (profiles == null) {
                        ODLVSEMETW.EventWriteProcessCmdletWarning(this.CmdletName,
                        "Uplink profile(s) not found.");
                        this.WriteWarning("Uplink profile(s) not found.");
                    } else {
                        this.WriteObject(profiles, true);
                    }
                }
            } catch (Exception ex) {
                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                operation = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(operation);
                string output = "\"VSEMUplinkPortProfile\":" + JavaScriptSerializer.Serialize(profiles);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, output);
            }
        }
        /// <summary>
        /// This function is responsible for creating a connection object for this VSEM provider.
        /// </summary>
        protected override void DoODLVSEMCmdlet()
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"ConnectionString\":" + JavaScriptSerializer.Serialize(this.ConnectionParams.ConnectionString));
            ODLVSEMETW.EventWriteDoCmdlet(this.CmdletName,
                "Connecting to VSEM.",
                json.ToString());

            this.ValidateConnectionString();
            string controllers = this.ValidateControllers();
            string connectionString =
                this.ConnectionParams.ConnectionString.Split(',').FirstOrDefault();

            TransactionManager txnMng = new TransactionManager();
            txnMng.StartTransaction();
            var operation = TransactionManager.Operation.None;
            VSEMConnection conn = new VSEMConnection(connectionString,
                this.ConnectionParams.Credential,
                controllers);
            try {
                conn.UpdateConnection(txnMng);
                ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                    "Connected to {0} as user '{1}'.",
                    this.ConnectionParams.ConnectionString,
                    this.ConnectionParams.Credential.UserName),
                    string.Empty);

                operation = TransactionManager.Operation.Commit;
            } catch (Exception ex) {
                Exception exception = VSEMODLExceptionUtil.ConvertExceptionToVSEMException(ex);
                ODLVSEMETW.EventWriteFailedCmdlet(this.CmdletName, exception.GetType() + " : " + ex.Message);
                operation = TransactionManager.Operation.Rollback;
                throw exception;
            } finally {
                txnMng.EndTransaction(operation);
                ODLVSEMETW.EventWriteEndCmdlet(this.CmdletName, string.Empty);
                this.WriteObject(conn);
            }
        }