Exemplo n.º 1
0
        public async Task <IActionResult> Edit([FromServices] IHostingEnvironment env, ValueMaps model)
        {
            ValueMaps updated = new ValueMaps();

            if (ModelState.IsValid)
            {
                var auth = await HttpContext.AuthenticateAsync();

                string currentUser = "";
                string currentip   = ContextIP.GetUserIp(this.HttpContext);
                if (auth.Succeeded)
                {
                    currentUser = auth.Principal.Identity.Name;
                }
                updated = await valuemapsRepository.GetByIdAsync(model.Id);

                updated.SystemId          = model.SystemId;
                updated.Threshold         = model.Threshold;
                updated.ValuationFunction = model.ValuationFunction;
                updated.Uid           = currentUser;
                updated.TransdateTime = DateTime.Now;
                var mapping = systemRepository.FindById(model.SystemId);
                updated.System = mapping;


                await valuemapsRepository.UpdateAsync(updated);
            }
            else
            {
                return(BadRequest("Something is wrong,please retry"));
            }
            //if (!note.Password.Equals(password))

            return(View("Details", updated));
        }
 public static T GetOriginal <T>(this ValueMaps input, byte[] byteArray) where T : class
 {
     using (var memoryStream = new MemoryStream(byteArray))
     {
         var obj = ProtoBuf.Serializer.Deserialize <T>(memoryStream);
         return(obj);
     }
 }
Exemplo n.º 3
0
        public static IDictionary <String, IDictionary <String, ValueList> > GetMappedValueListsWithPath(this GraphMap graphMap, ValueListMaps valueListMaps, String templateId, int templateIndex, String parentClassId, int parentClassIndex, IDictionary <String, IDictionary <String, ValueList> > valueList = null)
        {
            if (valueList == null)
            {
                valueList = new Dictionary <String, IDictionary <String, ValueList> >();
            }

            var classTemplateMap = graphMap.GetClassTemplateMap(parentClassId, parentClassIndex);



            if (classTemplateMap != null)
            {
                var template = classTemplateMap.templateMaps.SingleOrDefault(x => (x.id == templateId && x.index == templateIndex));
                if (template != null)
                {
                    foreach (var role in template.roleMaps.Where(x => !String.IsNullOrWhiteSpace(x.propertyName)))
                    {
                        if (role.type == RoleType.ObjectProperty)
                        {
                            string path = (string.IsNullOrEmpty(classTemplateMap.classMap.path) ? "" : classTemplateMap.classMap.path) + "/" + classTemplateMap.classMap.id.ToString() + "/" + template.id.ToString() + "/" + role.id.ToString();
                            Dictionary <String, ValueList> valListDict = new Dictionary <String, ValueList>();
                            ValueMaps       valueMaps = GetValueListMap(valueListMaps, role.valueListName);
                            ValueList       valList   = new ValueList();
                            ValueCollection valCol    = new ValueCollection();
                            valList.name = role.valueListName;
                            foreach (var item in valueMaps)
                            {
                                ValueItem valItem = new ValueItem();
                                valItem.label = item.label;
                                valItem.value = item.internalValue;
                                valItem.uri   = item.uri;
                                valCol.Add(valItem);
                            }
                            valList.values = valCol;
                            valListDict.Add(role.propertyName, valList);
                            valueList.Add(path, valListDict);
                        }
                    }
                    foreach (var role in template.roleMaps.Where(x => x.classMap != null))
                    {
                        var classTemplate = graphMap.GetClassTemplateMap(role.classMap.id, role.classMap.index);
                        foreach (var tmpl in classTemplate.templateMaps)
                        {
                            if (tmpl != null)
                            {
                                graphMap.GetMappedValueListsWithPath(valueListMaps, tmpl.id, tmpl.index, role.classMap.id, role.classMap.index, valueList);
                            }
                        }
                    }
                }
            }
            return(valueList);
        }
        private void CompareValueMappings(Guid sessionUniqueId, ValueMaps newValueMaps, ValueMaps currValueMaps)
        {
            if (newValueMaps.ValueMap.Count != currValueMaps.ValueMap.Count)
            {
                SetImpactForSessionChange(sessionUniqueId);
                return;
            }

            bool mappingsFound = true;

            foreach (var valueMap in newValueMaps.ValueMap)
            {
                var mapQuery = currValueMaps.ValueMap.Where(vm =>
                                                            vm.name == valueMap.name && vm.Value.Count == valueMap.Value.Count);
                if (mapQuery.Count() == 0)
                {
                    mappingsFound = false;
                    break;
                }

                Debug.Assert(mapQuery.Count() == 1, "mapQuery.Count() != 1");
                var currMap = mapQuery.First();
                foreach (var newValue in valueMap.Value)
                {
                    var valueQuery = currMap.Value.Where(v =>
                                                         v.LeftValue == newValue.LeftValue && v.RightValue == newValue.RightValue &&
                                                         v.When.ConditionalSrcFieldName == newValue.When.ConditionalSrcFieldName &&
                                                         v.When.ConditionalSrcFieldValue == newValue.When.ConditionalSrcFieldValue);

                    if (valueQuery.Count() == 0)
                    {
                        mappingsFound = false;
                        break;
                    }
                }

                if (!mappingsFound)
                {
                    break;
                }
            }

            if (!mappingsFound)
            {
                SetImpactForSessionChange(sessionUniqueId);
            }
        }
 public static byte[] SetBinary <T>(this ValueMaps input) where T : class, new()
 {
     byte[] byteArray = null;
     try
     {
         using (var memoryStream = new MemoryStream())
         {
             ProtoBuf.Serializer.Serialize(memoryStream, input);
             byteArray = memoryStream.ToArray();
             return(byteArray);
         }
     }
     catch (Exception)
     {
         return(byteArray);
     }
 }
        public async Task AddAsync(ValueMaps vm)
        {
            IDbContextTransaction tx = null;

            try
            {
                using (tx = await context.Database.BeginTransactionAsync())
                {
                    context.ValueMaps.Add(vm);
                    await context.SaveChangesAsync();

                    tx.Commit();
                }
            }
            catch (DbUpdateException ex)
            {
                tx.Rollback();
            }
        }
Exemplo n.º 7
0
 public ValueListMap()
 {
     valueMaps = new ValueMaps();
 }
Exemplo n.º 8
0
        public async Task <IActionResult> Add([FromServices] IHostingEnvironment env, ValueMapsModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var auth = await HttpContext.AuthenticateAsync();

            string currentUser = "";
            string currentip   = ContextIP.GetUserIp(this.HttpContext);

            if (auth.Succeeded)
            {
                currentUser = auth.Principal.Identity.Name;
            }


            string    filename = string.Empty;
            ValueMaps tempin   = new ValueMaps
            {
                SystemId          = model.System,
                ValuationFunction = model.ValuationFunction,
                TransdateTime     = DateTime.Now,
                Threshold         = model.Threshold,
                Uid = currentUser
            };
            await valuemapsRepository.AddAsync(tempin);

            //redis
            await _redisService.SetAsync("First", tempin.ToString());



            StringBuilder sb = new StringBuilder();

            sb.Append("<table class='table' style='border: solid; color: silver'>"
                      + "<thead style='border: solid; color: red'>" + "< tr>< th > User </ th >< th > Datatime </ th ></ tr ></thead>" +
                      "<tbody style='border: solid; color: goldenrod'>"
                      + "<tr>< td >" + currentUser + " </ td >< td >" + DateTime.Now + " </ td ></ tr >< tr > "

                      + "</table>");
            sb.AppendLine(tempin.SetJSONString());
            //byte[] tempssin = tempin.SetBinary<ValueMaps>();
            //AddRedisData(tempssin);

            //pubish redis message
            //using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
            //{
            //    ISubscriber sub = redis.GetSubscriber();
            //  var rel=  sub.Publish("Addmessages", tempin.SetJSONString());
            //}


            //var busConfig = new RawRabbitConfiguration
            //rabbitmq
            //= new RabbitMqOptions
            //{
            //    Username = "******",
            //    Password = "******",
            //    Port = 5672,
            //    VirtualHost = "/",
            //    Hostnames = { "localhost" }

            //};
            //var busClient = BusClientFactory.CreateDefault(rabbitmq);
            busClient = BusClientFactory.CreateDefault(new RabbitMqOptions());
            //using (var busClient = BusClientFactory.CreateDefault(new RabbitMqOptions()))
            //{
            await busClient.PublishAsync <string>(tempin.SetJSONString());

            //}


            //await  emailSender.SendEmailAsync(currentUser, "Added one record!", sb.ToString());
            //await  valuemapsRepository.PublishAsync(tempin);
            return(RedirectToAction("Index"));
        }
Exemplo n.º 9
0
        private EnvelopeType _export(Session xenSession, string targetPath, string ovfname, string vmUuid)
        {
            EnvelopeType ovfEnv;

            try
            {
                auditLog.DebugFormat("Export: {0}, {1}", ovfname, targetPath);

                #region GET VM Reference
                XenRef <VM> vmRef = null;

                try
                {
                    vmRef = VM.get_by_uuid(xenSession, vmUuid);
                }
                catch
                {
                    log.WarnFormat("VM not found as uuid: {0}, trying as name-label", vmUuid);
                    vmRef = null;
                }
                if (vmRef == null)
                {
                    try
                    {
                        List <XenRef <VM> > vmRefs = VM.get_by_name_label(xenSession, vmUuid);
                        vmRef = vmRefs[0];
                        traceLog.DebugFormat("{0} VM(s) found by label {1}", vmRefs.Count, vmUuid);
                        if (vmRefs.Count > 1)
                        {
                            log.WarnFormat("Only exporting FIRST VM with name {0}", vmUuid);
                        }
                    }
                    catch
                    {
                        log.ErrorFormat(Messages.ERROR_VM_NOT_FOUND, vmUuid);
                        throw;
                    }
                }
                #endregion

                VM vm = VM.get_record(xenSession, vmRef);

                if (vm.power_state != vm_power_state.Halted && vm.power_state != vm_power_state.Suspended)
                {
                    var message = string.Format(Messages.ERROR_VM_NOT_HALTED, vm.Name());
                    OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ExportProgress, "Export", message));
                    log.Info(message);
                    throw new Exception(message);
                }

                #region CREATE ENVELOPE / ADD VIRTUAL SYSTEM
                ovfEnv = OVF.CreateEnvelope(ovfname);
                string vsId  = OVF.AddVirtualSystem(ovfEnv, vm.name_label);
                string vhsId = OVF.AddVirtualHardwareSection(ovfEnv, vsId);
                #endregion

                #region TRY TO ID OS
                XenRef <VM_guest_metrics> vmgmRef = VM.get_guest_metrics(xenSession, vmRef);
                if (!vmgmRef.opaque_ref.ToUpper().Contains("NULL"))
                {
                    VM_guest_metrics vmgm = VM_guest_metrics.get_record(xenSession, vmgmRef);
                    //VM_metrics vmm = VM_metrics.get_record(xenSession, VM.get_metrics(xenSession, vmRef));
                    if (vmgm.os_version != null && vmgm.os_version.Count > 0)
                    {
                        foreach (string key in vmgm.os_version.Keys)
                        {
                            if (key.ToLower().Equals("name"))
                            {
                                ushort osid = ValueMaps.OperatingSystem(vmgm.os_version[key]);
                                if (osid == 0xFFFF)
                                {
                                    osid = 1;
                                }                                 // change to OTHER since search failed.
                                string version = OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_INFO");
                                if (vmgm.os_version.ContainsKey("major") &&
                                    vmgm.os_version.ContainsKey("minor"))
                                {
                                    version = string.Format(OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_VERSION"), vmgm.os_version["major"], vmgm.os_version["minor"]);
                                }
                                string osname = (vmgm.os_version[key].Split(new [] { '|' }))[0];
                                OVF.UpdateOperatingSystemSection(ovfEnv, vsId, osname, version, osid);
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region ADD VSSD
                // IS PV'd? for VirtualSystemType identification.
                string typeformat = @"{0}-{1}-{2}";
                string vmtype     = string.Format(typeformat, "hvm", "3.0", "unknown");
                if (vm.HVM_boot_policy != null && vm.HVM_boot_policy == Properties.Settings.Default.xenBootOptions)
                {
                    if (!string.IsNullOrEmpty(vm.domarch))
                    {
                        vmtype = string.Format(typeformat, vm.domarch, "3.0", "unknown");
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(vm.domarch))
                    {
                        vmtype = string.Format(typeformat, "xen", "3.0", vm.domarch);
                    }
                    else
                    {
                        vmtype = string.Format(typeformat, "xen", "3.0", "unknown");
                    }
                }
                OVF.AddVirtualSystemSettingData(ovfEnv, vsId, vhsId, vm.name_label, OVF.GetContentMessage("VSSD_CAPTION"), vm.name_description, Guid.NewGuid().ToString(), vmtype);
                #endregion

                #region ADD CPUS
                OVF.SetCPUs(ovfEnv, vsId, (ulong)vm.VCPUs_max);
                #endregion

                #region ADD MEMORY
                OVF.SetMemory(ovfEnv, vsId, (ulong)(vm.memory_dynamic_max / MB), "MB");
                #endregion

                #region ADD NETWORKS
                List <XenRef <VIF> > vifs = VM.get_VIFs(xenSession, vmRef);
                foreach (XenRef <VIF> vifref in vifs)
                {
                    VIF vif = VIF.get_record(xenSession, vifref);
                    XenRef <Network> netRef = vif.network;
                    Network          net    = Network.get_record(xenSession, netRef);

                    // Why is the following call reference using name_label where other references use uuid?
                    OVF.AddNetwork(ovfEnv, vsId, net.uuid, net.name_label, net.name_description, vif.MAC);
                }
                #endregion

                #region SET STARTUP OPTIONS
                OVF.AddStartupSection(ovfEnv, true, vsId, vm.order, vm.start_delay, vm.shutdown_delay);
                #endregion

                #region GET AND EXPORT DISKS using iSCSI
                List <XenRef <VBD> > vbdlist = VM.get_VBDs(xenSession, vmRef);
                _vdiRefs.Clear();

                int diskIndex = 0;

                foreach (XenRef <VBD> vbdref in vbdlist)
                {
                    VBD vbd = VBD.get_record(xenSession, vbdref);

                    if (vbd.type == vbd_type.CD)
                    {
                        string rasdid = OVF.AddCDROM(ovfEnv, vsId, vbd.uuid, OVF.GetContentMessage("RASD_16_CAPTION"), OVF.GetContentMessage("RASD_16_DESCRIPTION"));
                        OVF.SetTargetDeviceInRASD(ovfEnv, vsId, rasdid, vbd.userdevice);
                    }
                    else
                    {
                        try
                        {
                            XenRef <VDI> vdi = VBD.get_VDI(xenSession, vbdref);
                            if (vdi != null && !string.IsNullOrEmpty(vdi.opaque_ref) && !(vdi.opaque_ref.ToLower().Contains("null")))
                            {
                                _vdiRefs.Add(vdi);
                                VDI    lVdi = VDI.get_record(xenSession, vdi);
                                string destinationFilename = Path.Combine(targetPath, string.Format(@"{0}.vhd", lVdi.uuid));
                                string diskid = Guid.NewGuid().ToString();

                                string diskName = lVdi.name_label;

                                if (diskName == null)
                                {
                                    diskName = string.Format("{0} {1}", OVF.GetContentMessage("RASD_19_CAPTION"), diskIndex);
                                }

                                OVF.AddDisk(ovfEnv, vsId, diskid, Path.GetFileName(destinationFilename), vbd.bootable, diskName, lVdi.name_description, (ulong)lVdi.physical_utilisation, (ulong)lVdi.virtual_size);
                                OVF.SetTargetDeviceInRASD(ovfEnv, vsId, diskid, vbd.userdevice);

                                diskIndex++;
                            }
                        }
                        catch (Exception ex)
                        {
                            log.InfoFormat("Export: VBD Skipped: {0}: {1}", vbdref, ex.Message);
                        }
                    }
                }
                #endregion

                if (!MetaDataOnly)
                {
                    _copydisks(ovfEnv, ovfname, targetPath);
                }

                #region ADD XEN SPECIFICS
                if (vm.HVM_boot_params != null)
                {
                    Dictionary <string, string> _params = vm.HVM_boot_params;
                    foreach (string key in _params.Keys)
                    {
                        if (key.ToLower().Equals("order"))
                        {
                            OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_params", _params[key], OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                        }
                    }
                }
                if (!string.IsNullOrEmpty(vm.HVM_boot_policy))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_policy", vm.HVM_boot_policy, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_2"));
                }
                if (vm.HVM_shadow_multiplier != 1.0)
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_shadow_multiplier", Convert.ToString(vm.HVM_shadow_multiplier), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (vm.platform != null)
                {
                    Dictionary <string, string> platform = vm.platform;
                    StringBuilder sb = new StringBuilder();
                    foreach (string key in platform.Keys)
                    {
                        sb.AppendFormat(@"{0}={1};", key, platform[key]);
                    }
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "platform", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3"));
                }
                if (!string.IsNullOrEmpty(vm.PV_args))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_args", vm.PV_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_bootloader))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader", vm.PV_bootloader, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_bootloader_args))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader_args", vm.PV_bootloader_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_kernel))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_kernel", vm.PV_kernel, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_legacy_args))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_legacy_args", vm.PV_legacy_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_ramdisk))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_ramdisk", vm.PV_ramdisk, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }

                if (vm.hardware_platform_version >= 0)
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "hardware_platform_version", vm.hardware_platform_version.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }

                if (vm.HasSriovRecommendation())
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "allow_network_sriov", bool.TrueString.ToLowerInvariant(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (vm.has_vendor_device)
                {
                    //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "VM_has_vendor_device", vm.has_vendor_device.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }

                if (vm.VGPUs.Count != 0)
                {
                    VGPU vgpu = VGPU.get_record(xenSession, vm.VGPUs[0]);

                    if (vgpu != null)
                    {
                        var vgpuGroup = GPU_group.get_record(xenSession, vgpu.GPU_group);
                        var vgpuType  = VGPU_type.get_record(xenSession, vgpu.type);

                        var sb = new StringBuilder();
                        sb.AppendFormat("GPU_types={{{0}}};",
                                        vgpuGroup.GPU_types == null || vgpuGroup.GPU_types.Length < 1
                                            ? ""
                                            : string.Join(";", vgpuGroup.GPU_types));
                        sb.AppendFormat("VGPU_type_vendor_name={0};", vgpuType.vendor_name ?? "");
                        sb.AppendFormat("VGPU_type_model_name={0};", vgpuType.model_name ?? "");
                        OVF.AddOtherSystemSettingData(ovfEnv, vsId, "vgpu", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_4"));
                    }
                }

                string pvsSiteUuid = string.Empty;
                var    allProxies  = xenSession.Connection.Cache.PVS_proxies;

                foreach (var p in allProxies.Where(p => p != null && p.VIF != null))
                {
                    var vif = xenSession.Connection.Resolve(p.VIF);
                    if (vif != null)
                    {
                        var vmFromVif = xenSession.Connection.Resolve(vif.VM);
                        if (vmFromVif != null && vmFromVif.uuid == vm.uuid)
                        {
                            var pvsSite = xenSession.Connection.Resolve(p.site);
                            if (pvsSite != null)
                            {
                                pvsSiteUuid = pvsSite.uuid;
                            }

                            break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(pvsSiteUuid))
                {
                    var sb = new StringBuilder();
                    sb.AppendFormat("PVS_SITE={{{0}}};", string.Format("uuid={0}", pvsSiteUuid));

                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "pvssite", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_5"));
                }
                #endregion

                OVF.FinalizeEnvelope(ovfEnv);
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException)
                {
                    throw;
                }
                log.Error(Messages.ERROR_EXPORT_FAILED);
                throw new Exception(Messages.ERROR_EXPORT_FAILED, ex);
            }
            return(ovfEnv);
        }
        //public async Task PublishAsync(ValueMaps vm)
        //{

        //    using (var trans = context.Database.BeginTransaction())
        //    {
        //        //指定发送的消息标题(供订阅)和内容
        //        await _publisher.PublishAsync("xxx.services.account.check", vm);
        //        // 你的业务代码。
        //        trans.Commit();
        //    }
        //    //return Ok();
        //}

        //public async Task PublishBatchAsync(List<ValueMaps> vm)
        //{
        //    using (var trans = context.Database.BeginTransaction())
        //    {
        //        //指定发送的消息标题(供订阅)和内容
        //        await _publisher.PublishAsync("xxx.services.account.check", vm);
        //        // 你的业务代码。
        //        trans.Commit();
        //    }
        //}
        //public interface ISubscriberService
        //{
        //    Task CheckReceivedMessage(ValueMaps VM);
        //}



        public Task UpdateAsync(ValueMaps vm)
        {
            context.Entry(vm).State = EntityState.Modified;
            return(context.SaveChangesAsync());
        }
Exemplo n.º 11
0
        private EnvelopeType Export(string targetDir, VM vm, Action <float> updatePercentage)
        {
            if (vm.power_state != vm_power_state.Halted && vm.power_state != vm_power_state.Suspended)
            {
                log.Error($"Cannot export VM {vm.Name()} ({vm.opaque_ref}); it is neither halted nor suspended.");
                throw new Exception(string.Format(Messages.ERROR_VM_NOT_HALTED, vm.Name()));
            }

            log.Info($"Exporting metadata for {vm.name_label}...");

            #region CREATE ENVELOPE / ADD VIRTUAL SYSTEM
            EnvelopeType ovfEnv = OVF.CreateEnvelope(m_applianceFileName);
            string       vsId   = OVF.AddVirtualSystem(ovfEnv, vm.name_label);
            string       vhsId  = OVF.AddVirtualHardwareSection(ovfEnv, vsId);
            #endregion

            #region TRY TO ID OS

            VM_guest_metrics vmgm = Connection.Resolve(vm.guest_metrics);

            if (vmgm?.os_version != null && vmgm.os_version.TryGetValue("name", out string osName))
            {
                ushort osId = ValueMaps.OperatingSystem(osName);
                if (osId == 0xFFFF)
                {
                    osId = 1; // change to OTHER since search failed.
                }
                string version = OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_INFO");

                if (vmgm.os_version.TryGetValue("major", out string major) &&
                    vmgm.os_version.TryGetValue("minor", out string minor))
                {
                    version = string.Format(OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_VERSION"), major, minor);
                }

                string[] osNameParts = osName.Split('|');
                if (osNameParts.Length > 0)
                {
                    OVF.UpdateOperatingSystemSection(ovfEnv, vsId, osNameParts[0], version, osId);
                }
            }

            #endregion

            #region ADD VirtualSystemType identification
            var pv     = vm.IsHVM() ? "hvm" : "xen";
            var arch   = string.IsNullOrEmpty(vm.domarch) ? "unknown" : vm.domarch;
            var vmType = string.Format("{0}-3.0-{1}", pv, arch);

            OVF.AddVirtualSystemSettingData(ovfEnv, vsId, vhsId, vm.name_label, OVF.GetContentMessage("VSSD_CAPTION"), vm.name_description, Guid.NewGuid().ToString(), vmType);
            #endregion

            #region ADD CPUS
            OVF.SetCPUs(ovfEnv, vsId, (ulong)vm.VCPUs_max);
            #endregion

            #region ADD MEMORY
            OVF.SetMemory(ovfEnv, vsId, (ulong)(vm.memory_dynamic_max / Util.BINARY_MEGA), "MB");
            #endregion

            #region ADD NETWORKS

            foreach (XenRef <VIF> vifRef in vm.VIFs)
            {
                VIF vif = Connection.Resolve(vifRef);
                if (vif == null)
                {
                    continue;
                }

                XenAPI.Network net = Connection.Resolve(vif.network);
                if (net == null)
                {
                    continue;
                }

                OVF.AddNetwork(ovfEnv, vsId, net.uuid, net.name_label, net.name_description, vif.MAC);
            }

            #endregion

            #region SET STARTUP OPTIONS
            OVF.AddStartupSection(ovfEnv, true, vsId, vm.order, vm.start_delay, vm.shutdown_delay);
            #endregion

            #region EXPORT DISKS

            int diskIndex = 0;
            var vbdRefs   = vm.VBDs;

            for (int i = 0; i < vbdRefs.Count; i++)
            {
                int          curVbd = i;
                XenRef <VBD> vbdRef = vbdRefs[i];

                VBD vbd = Connection.Resolve(vbdRef);
                if (vbd == null)
                {
                    continue;
                }

                if (vbd.type == vbd_type.CD)
                {
                    string rasdid = OVF.AddCDROM(ovfEnv, vsId, vbd.uuid, OVF.GetContentMessage("RASD_16_CAPTION"), OVF.GetContentMessage("RASD_16_DESCRIPTION"));
                    OVF.SetTargetDeviceInRASD(ovfEnv, vsId, rasdid, vbd.userdevice);
                    continue;
                }

                VDI vdi = Connection.Resolve(vbd.VDI);
                if (vdi == null)
                {
                    continue;
                }

                try
                {
                    var diskFilename = $"{vdi.uuid}.vhd";
                    var diskPath     = Path.Combine(targetDir, diskFilename);

                    if (File.Exists(diskPath))
                    {
                        var oldFileName = diskFilename;
                        diskFilename = $"{vdi.uuid}_{Thread.CurrentThread.ManagedThreadId}.vhd";
                        diskPath     = Path.Combine(targetDir, diskFilename);
                        log.InfoFormat("VHD Name collision, renamed {0} to {1}", oldFileName, diskFilename);
                    }

                    string diskName = vdi.name_label;
                    if (string.IsNullOrEmpty(diskName))
                    {
                        diskName = $"{OVF.GetContentMessage("RASD_19_CAPTION")} {diskIndex}";
                    }

                    if (!MetaDataOnly)
                    {
                        log.Info($"Exporting disk {diskName} to {diskFilename} for {vm.name_label}...");

                        var taskRef = Task.create(Connection.Session, "export_raw_vdi_task",
                                                  $"Exporting VDI {vdi.uuid} to {diskFilename}");

                        HTTP_actions.get_export_raw_vdi(b =>
                        {
                            Description = string.Format(Messages.EXPORTING_VDI, diskName, diskFilename,
                                                        Util.DiskSizeString(b, 2, "F2"), Util.DiskSizeString(vdi.virtual_size));
                            updatePercentage((curVbd + (float)b / vdi.virtual_size) / vbdRefs.Count);
                        },
                                                        () => Cancelling, XenAdminConfigManager.Provider.GetProxyTimeout(true),
                                                        Connection.Hostname, XenAdminConfigManager.Provider.GetProxyFromSettings(Connection),
                                                        diskPath, taskRef, Connection.Session.opaque_ref, vdi.uuid, "vhd");

                        if (m_shouldVerify)
                        {
                            Description = string.Format(Messages.EXPORTING_VDI_VERIFICATION, diskFilename);

                            using (var stream = new FileStream(diskPath, FileMode.Open, FileAccess.Read))
                                using (var sw = new StringWriter())
                                {
                                    var vhdChecker = new FileChecker(stream);
                                    var result     = vhdChecker.Check(sw, ReportLevels.All);
                                    log.InfoFormat("Verifying disk {0}:\n{1}", diskFilename, sw.ToString().Replace("\0", ""));
                                    if (!result)
                                    {
                                        throw new Exception(string.Format(Messages.EXPORTING_VDI_VERIFICATION_FAILURE, diskFilename));
                                    }
                                }
                        }
                    }

                    string diskId = Guid.NewGuid().ToString();

                    OVF.AddDisk(ovfEnv, vsId, diskId, diskFilename, vbd.bootable, diskName,
                                vdi.name_description, (ulong)vdi.physical_utilisation, (ulong)vdi.virtual_size);
                    OVF.SetTargetDeviceInRASD(ovfEnv, vsId, diskId, vbd.userdevice);

                    diskIndex++;
                }
                catch (HTTP.CancelledException)
                {
                    throw new CancelledException();
                }
            }

            #endregion

            #region ADD XEN SPECIFICS

            var _params = vm.HVM_boot_params;
            if (_params != null && _params.Count > 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_params", string.Join(";", _params.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_6"));
            }

            if (!string.IsNullOrEmpty(vm.HVM_boot_policy))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_policy", vm.HVM_boot_policy, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_2"));
            }

            if (vm.HVM_shadow_multiplier != 1.0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_shadow_multiplier", Convert.ToString(vm.HVM_shadow_multiplier), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            var platform = vm.platform;
            if (platform != null && platform.Count > 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "platform", string.Join(";", platform.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3"));
            }

            var nvram = vm.NVRAM;
            if (nvram != null && nvram.Count > 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "NVRAM", string.Join(";", nvram.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_7"));
            }

            if (!string.IsNullOrEmpty(vm.PV_args))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_args", vm.PV_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.PV_bootloader))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader", vm.PV_bootloader, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.PV_bootloader_args))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader_args", vm.PV_bootloader_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.PV_kernel))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_kernel", vm.PV_kernel, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.PV_legacy_args))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_legacy_args", vm.PV_legacy_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.PV_ramdisk))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_ramdisk", vm.PV_ramdisk, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (vm.hardware_platform_version >= 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "hardware_platform_version", vm.hardware_platform_version.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.recommendations))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "recommendations", vm.recommendations.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (vm.has_vendor_device)
            {
                //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "VM_has_vendor_device", vm.has_vendor_device.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            foreach (XenRef <VGPU> gpuRef in vm.VGPUs)
            {
                VGPU vgpu = Connection.Resolve(gpuRef);

                if (vgpu != null)
                {
                    var vgpuGroup = Connection.Resolve(vgpu.GPU_group);
                    var vgpuType  = Connection.Resolve(vgpu.type);

                    var sb = new StringBuilder();
                    sb.AppendFormat("GPU_types={{{0}}};",
                                    vgpuGroup?.GPU_types == null || vgpuGroup.GPU_types.Length < 1
                            ? ""
                            : string.Join(";", vgpuGroup.GPU_types));
                    sb.AppendFormat("VGPU_type_vendor_name={0};", vgpuType?.vendor_name ?? "");
                    sb.AppendFormat("VGPU_type_model_name={0};", vgpuType?.model_name ?? "");
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "vgpu", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_4"), true);
                }
            }

            string pvsSiteUuid = string.Empty;
            var    allProxies  = Connection.Cache.PVS_proxies;

            foreach (var p in allProxies.Where(p => p != null && p.VIF != null))
            {
                var vif = Connection.Resolve(p.VIF);
                if (vif != null)
                {
                    var vmFromVif = Connection.Resolve(vif.VM);
                    if (vmFromVif != null && vmFromVif.uuid == vm.uuid)
                    {
                        var pvsSite = Connection.Resolve(p.site);
                        if (pvsSite != null)
                        {
                            pvsSiteUuid = pvsSite.uuid;
                        }

                        break;
                    }
                }
            }

            if (!string.IsNullOrEmpty(pvsSiteUuid))
            {
                var sb = new StringBuilder();
                sb.AppendFormat("PVS_SITE={{{0}}};", string.Format("uuid={0}", pvsSiteUuid));

                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "pvssite", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_5"));
            }

            #endregion

            OVF.FinalizeEnvelope(ovfEnv);
            return(ovfEnv);
        }
 public static string SetJSONString(this ValueMaps input)
 {
     return(JsonConvert.SerializeObject(input));
 }