Example #1
0
        protected override void OnSizeChanged(EventArgs e)
        {
            VirtualDevice device = Device;

            if (device != null)
            {
                float xScale = 1;
                float yScale = 1;
                float ppd    = OffscreenGraphics.PixelsPerDip;

                CefRect viewportRect = device.ViewportRect;
                viewportRect.Scale(OffscreenGraphics.PixelsPerDip);
                Rectangle clientRect = this.ClientRectangle;
                if (viewportRect.Height > clientRect.Height)
                {
                    yScale = Math.Max(clientRect.Height - 6.0f, 1.0f) / viewportRect.Height;
                }

                if (viewportRect.Width > clientRect.Width)
                {
                    xScale = Math.Max(clientRect.Width - 6.0f, 1.0f) / viewportRect.Width;
                }

                device.Scale = Math.Min(xScale, yScale);

                CefRect bounds = device.GetBounds(ppd);
                device.X = (int)(((clientRect.Width - bounds.Width) >> 1) / ppd);
                device.Y = (int)(((clientRect.Height - bounds.Height) >> 1) / ppd);

                CefInvalidate();
            }

            base.OnSizeChanged(e);
        }
Example #2
0
 public ActionResult Edit(VirtualDevice collection)
 {
     ReturnMessage RM = new ReturnMessage(false);
     if (ModelState.IsValid)
     {
         try
         {
             if (!CheckRepeat(collection))
             {
                 RM.IsSuccess = false;
                 RM.Message = "已有相同记录存在!";
             }
             else
             {
                 RM.IsSuccess = _bll.Update(collection);
             }
         }
         catch (Exception ex)
         {
             RM.Message = ex.Message;
         }
     }
     else
     {
         RM.IsSuccess = false;
         RM.Message = "数据格式不正确";
     }
     return Json(RM);
 }
Example #3
0
        /// <summary>
        /// Enable or disable device simulation.
        /// </summary>
        /// <param name="device">The simulated device or null.</param>
        public void SimulateDevice(VirtualDevice device)
        {
            if (IsHandleCreated)
            {
                VerifyAccess();
            }

            if (Device == device)
            {
                return;
            }

            OffscreenGraphics offscreenGraphics = this.OffscreenGraphics;

            if (offscreenGraphics != null)
            {
                offscreenGraphics.Device = device;
            }

            if (IsHandleCreated)
            {
                if (!WindowlessRenderingEnabled)
                {
                    throw new InvalidOperationException();
                }
                OnSizeChanged(EventArgs.Empty);
            }
            else
            {
                Device = device;
            }
        }
        public ActionResult Edit(VirtualDevice collection)
        {
            var rm = new ReturnMessage(false);

            if (ModelState.IsValid)
            {
                try
                {
                    if (!CheckRepeat(collection))
                    {
                        rm.IsSuccess = false;
                        rm.Message   = "已有相同记录存在!";
                    }
                    else
                    {
                        collection.ModifyOn = DateTime.Now;
                        collection.ModifyBy = CurrentHelper.CurrentUser.User.UserName;
                        rm.IsSuccess        = _bll.Update(collection);
                    }
                }
                catch (Exception ex)
                {
                    rm.Message = ex.Message;
                }
            }
            else
            {
                rm.IsSuccess = false;
                rm.Message   = "数据格式不正确";
            }
            return(Json(rm));
        }
Example #5
0
        /// <summary>
        /// This method retrieves the typical week used by the TOU schedule.
        /// </summary>
        //  Revision History
        //  MM/DD/YY Who Version Issue# Description
        //  -------- --- ------- ------ ---------------------------------------------
        //  10/01/08 jrf 9.50           Created.
        //
        private void RetrieveANSITypicalWeek()
        {
            short  sDisplayProgress = 0;
            short  sResponse        = DEVICE_SERVER_SUCCESS;
            object objValue         = null;

            //Get the typical week
            sResponse = VirtualDevice.GetValue(TOU_SEASON_1_DAY_TYPE_MAP, ref objValue, sDisplayProgress);

            if (DEVICE_SERVER_SUCCESS == sResponse && null != objValue)
            {
                //extract the daytype for each day of the typical week.
                int iTypicalWeek = (int)objValue;
                int iSunday      = SUNDAY_MASK & iTypicalWeek;
                int iMonday      = (MONDAY_MASK & iTypicalWeek) >> 2;
                int iTuesday     = (TUESDAY_MASK & iTypicalWeek) >> 4;
                int iWednesday   = (WEDNESDAY_MASK & iTypicalWeek) >> 6;
                int iThursday    = (THURSDAY_MASK & iTypicalWeek) >> 8;
                int iFriday      = (FRIDAY_MASK & iTypicalWeek) >> 10;
                int iSaturday    = (SATURDAY_MASK & iTypicalWeek) >> 12;

                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.SUNDAY]    = m_TOUSchedule.NormalDays[iSunday];
                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.MONDAY]    = m_TOUSchedule.NormalDays[iMonday];
                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.TUESDAY]   = m_TOUSchedule.NormalDays[iTuesday];
                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.WEDNESDAY] = m_TOUSchedule.NormalDays[iWednesday];
                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.THURSDAY]  = m_TOUSchedule.NormalDays[iThursday];
                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.FRIDAY]    = m_TOUSchedule.NormalDays[iFriday];
                m_TOUSchedule.TypicalWeek[(int)eTypicalDay.SATURDAY]  = m_TOUSchedule.NormalDays[iSaturday];
            }
        }
Example #6
0
        public unsafe void Render(Graphics g, Rectangle r)
        {
            lock (_syncRoot)
            {
                if (ViewPixels != null)
                {
                    float ppd = OffscreenGraphics.PixelsPerDip;

                    int           offsetX  = 0;
                    int           offsetY  = 0;
                    VirtualDevice viewport = this.Device;
                    if (viewport != null)
                    {
                        offsetX = viewport.X;
                        offsetY = viewport.Y;
                    }

                    DrawPixels(ViewPixels, g, r, (int)(offsetX * ppd), (int)(offsetY * ppd));

                    PixelBuffer pixelBuffer = PopupPixels;
                    if (pixelBuffer == null)
                    {
                        return;
                    }

                    DrawPixels(pixelBuffer, g, r, (int)(_popupBounds.X + offsetX * ppd), (int)(_popupBounds.Y + offsetY * ppd));
                }
            }
        }
Example #7
0
        public unsafe void Render(SKCanvas canvas, Rectangle r)
        {
            lock (_syncRoot)
            {
                if (ViewPixels != null)
                {
                    float ppd = OffscreenGraphics.PixelsPerDip;

                    int           offsetX  = 0;
                    int           offsetY  = 0;
                    VirtualDevice viewport = this.Device;
                    if (viewport != null)
                    {
                        offsetX = viewport.X;
                        offsetY = viewport.Y;
                    }
                    using (var skpaint = new SKPaint())
                    {
                        skpaint.BlendMode = SKBlendMode.Multiply;
                        DrawPixels(ViewPixels, canvas, skpaint, r, (int)(offsetX * ppd), (int)(offsetY * ppd));
                    }
                    PixelBuffer pixelBuffer = PopupPixels;
                    if (pixelBuffer == null)
                    {
                        return;
                    }

                    DrawPixels(pixelBuffer, canvas, null, r, (int)(_popupBounds.X + offsetX * ppd), (int)(_popupBounds.Y + offsetY * ppd));
                }
            }
        }
Example #8
0
        protected virtual unsafe CefRect GetCefRootBounds()
        {
            VirtualDevice device = Device;

            if (device == null)
            {
                const int GA_ROOT = 2;

                RECT   windowBounds;
                IntPtr hwnd = NativeMethods.GetAncestor(OffscreenGraphics.WidgetHandle, GA_ROOT);
                if ((NativeMethods.DwmIsCompositionEnabled() && NativeMethods.DwmGetWindowAttribute(hwnd, DWMWINDOWATTRIBUTE.ExtendedFrameBounds, &windowBounds, sizeof(RECT)) == 0) ||
                    NativeMethods.GetWindowRect(hwnd, out windowBounds))
                {
                    float ppd = OffscreenGraphics.PixelsPerDip;
                    if (ppd == 1.0f)
                    {
                        return(windowBounds.ToCefRect());
                    }
                    return(new CefRect(
                               (int)(windowBounds.Left / ppd),
                               (int)(windowBounds.Top / ppd),
                               (int)((windowBounds.Right - windowBounds.Left) / ppd),
                               (int)((windowBounds.Bottom - windowBounds.Top) / ppd)
                               ));
                }
                return(OffscreenGraphics.GetBounds());
            }
            else
            {
                return(device.GetRootBounds());
            }
        }
Example #9
0
 public VirtualClient(string host, int port, bool heartbeatSwitch, int interval, VirtualDevice device)
 {
     Host            = host;
     Port            = port;
     HeartbeatSwitch = heartbeatSwitch;
     Interval        = interval;
     Device          = device;
 }
Example #10
0
        private VirtualDeviceConfigSpec getCDDeviceConfigSpec()
        {
            String ops = cb.get_option("operation");
            VirtualDeviceConfigSpec  cdSpec = new VirtualDeviceConfigSpec();
            VirtualMachineConfigInfo vmConfigInfo
                = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty(
                      _virtualMachine, "config");

            if (ops.Equals("add"))
            {
                cdSpec.operation          = VirtualDeviceConfigSpecOperation.add;
                cdSpec.operationSpecified = true;
                VirtualCdrom cdrom = new VirtualCdrom();

                VirtualCdromIsoBackingInfo cdDeviceBacking
                    = new  VirtualCdromIsoBackingInfo();
                DatastoreSummary dsum = getDataStoreSummary();
                cdDeviceBacking.datastore = dsum.datastore;
                cdDeviceBacking.fileName  = "[" + dsum.name + "] " + cb.get_option("value") + ".iso";

                VirtualDevice vd = getIDEController();
                cdrom.backing                = cdDeviceBacking;
                cdrom.controllerKey          = vd.key;
                cdrom.controllerKeySpecified = true;
                cdrom.unitNumber             = -1;
                cdrom.unitNumberSpecified    = true;
                cdrom.key = -100;

                cdSpec.device = cdrom;

                return(cdSpec);
            }
            else
            {
                VirtualCdrom     cdRemove = null;
                VirtualDevice [] test     = vmConfigInfo.hardware.device;
                cdSpec.operation          = VirtualDeviceConfigSpecOperation.remove;
                cdSpec.operationSpecified = true;
                for (int k = 0; k < test.Length; k++)
                {
                    if (test[k].deviceInfo.label.Equals(
                            cb.get_option("value")))
                    {
                        cdRemove = (VirtualCdrom)test[k];
                    }
                }
                if (cdRemove != null)
                {
                    cdSpec.device = cdRemove;
                }
                else
                {
                    Console.WriteLine("No device available " + cb.get_option("value"));
                    return(null);
                }
            }
            return(cdSpec);
        }
Example #11
0
 private bool CheckRepeat(VirtualDevice model)
 {
     var query = Query.And(Query.EQ("PublicIP", model.PublicIP),
         Query.EQ("IntranetIP", model.IntranetIP),
         Query.EQ("MachineName", model.MachineName));
     var modelDb = _bll.Get(query);
     if (modelDb==null) return true;
     return model.Rid == modelDb.Rid;
 }
Example #12
0
        protected virtual bool GetCefScreenInfo(ref CefScreenInfo screenInfo)
        {
            VirtualDevice device = Device;

            if (device == null)
            {
                return(false);
            }
            screenInfo = device.ScreenInfo;
            return(true);
        }
Example #13
0
        public string GetActiveAudioDeviceName()
        {
            VirtualDevice device = _registry.ActiveDevice;

            if (!_isUsbDeviceSupported && device.IsUsbDevice())
            {
                device = _registry.DefaultDevice;
            }

            return(device.Name);
        }
Example #14
0
        public uint GetActiveChannelCount()
        {
            VirtualDevice device = _registry.ActiveDevice;

            if (!_isUsbDeviceSupported && device.IsUsbDevice())
            {
                device = _registry.DefaultDevice;
            }

            return(device.ChannelCount);
        }
Example #15
0
        private void UpdateOffscreenViewLocation()
        {
            if (OffscreenGraphics is null)
            {
                return;
            }

            VirtualDevice device = this.Device;

            if (device is null)
            {
                Point screenPoint = PointToScreen(default);
Example #16
0
        protected virtual CefPoint PointToViewport(CefPoint point)
        {
            float         scale    = OffscreenGraphics.PixelsPerDip;
            VirtualDevice viewport = Device;

            if (viewport != null)
            {
                scale = scale * viewport.Scale;
            }
            CefRect viewportRect = GetViewportRect();

            return(new CefPoint((int)((point.X - viewportRect.X) / scale), (int)((point.Y - viewportRect.Y) / scale)));
        }
Example #17
0
        private VirtualDevice getIDEController()
        {
            VirtualDevice ideCtlr = null;

            VirtualDevice [] defaultDevices = getDefaultDevices();
            for (int di = 0; di < defaultDevices.Length; di++)
            {
                if (defaultDevices[di].GetType().Name.Equals("VirtualIDEController"))
                {
                    ideCtlr = defaultDevices[di];
                    break;
                }
            }
            return(ideCtlr);
        }
Example #18
0
        protected virtual bool CefPointToScreen(ref CefPoint point)
        {
            VirtualDevice device = Device;

            if (device == null)
            {
                point.Scale(OffscreenGraphics.PixelsPerDip);
                NativeMethods.MapWindowPoints(OffscreenGraphics.WidgetHandle, IntPtr.Zero, ref point, 1);
                return(true);
            }
            else
            {
                return(device.PointToScreen(ref point));
            }
        }
Example #19
0
        protected CefRect GetViewportRect()
        {
            CefRect       viewportRect;
            VirtualDevice device = Device;

            if (device == null)
            {
                viewportRect = new CefRect(0, 0, this.Width, this.Height);
                viewportRect.Scale(OffscreenGraphics.PixelsPerDip);
                return(viewportRect);
            }
            else
            {
                return(device.GetBounds(OffscreenGraphics.PixelsPerDip));
            }
        }
        public ActionResult Create(VirtualDevice collection, string isContinue = "0")
        {
            var rm = new ReturnMessage(false);

            if (ModelState.IsValid)
            {
                try
                {
                    if (!string.IsNullOrEmpty(collection.ModelNum))
                    {
                        if (!CheckRepeat(collection))
                        {
                            rm.IsSuccess = false;
                            rm.Message   = "已有相同记录存在!";
                        }
                        else
                        {
                            collection.CreateOn = DateTime.Now;
                            collection.CreateBy = CurrentHelper.CurrentUser.User.UserName;
                            var res = _bll.Add(collection);
                            rm.IsSuccess = res;
                            if (rm.IsSuccess)
                            {
                                //OperateLogHelper.Create(collection);
                                rm.IsContinue = isContinue == "1";
                            }
                        }
                    }
                    else
                    {
                        rm.IsSuccess = false;
                        rm.Message   = "型号不能为空!";
                    }
                }
                catch (Exception ex)
                {
                    rm.Message = ex.Message;
                }
            }
            else
            {
                rm.IsSuccess = false;
                rm.Message   = "数据格式不正确";
            }
            return(Json(rm));
        }
    private static void Main(string[] args)
    {
        VirtualDevice dev = new VirtualDevice();

        dev.LogCallback = new LogCallback(LogCallback);
        dev.Start("Device name", true);
        Console.WriteLine("Got device name: {0}", dev.DeviceName);
        Console.WriteLine("Got device hwaddr: {0}", BitConverter.ToString(dev.HWAddress));
        dev.HWAddress = new byte[] { 0x00, 0x01, 0x23, 0x45, 0x67, 0x89 };
        dev.MTU       = 1280;
        dev.SetAddress(IPAddress.Parse("192.168.10.1"), 16);
        dev.Enabled = true;

        while (true)
        {
            Thread.Sleep(1000);
        }
    }
Example #22
0
        public ActionResult Create(VirtualDevice collection, string IsContinue = "0")
        {
            ReturnMessage RM = new ReturnMessage(false);
            if (ModelState.IsValid)
            {
                try
                {
                    if (!string.IsNullOrEmpty(collection.ModelNum))
                    {
                        if (!CheckRepeat(collection))
                        {
                            RM.IsSuccess = false;
                            RM.Message = "已有相同记录存在!";
                        }
                        else
                        {
                            bool res = _bll.Add(collection);
                            RM.IsSuccess = res;
                            if (RM.IsSuccess)
                            {
                                OperateLogHelper.Create(collection);
                                RM.IsContinue = IsContinue == "1";
                            }
                        }
                    }
                    else
                    {
                        RM.IsSuccess = false;
                        RM.Message = "型号不能为空!";
                    }

                }
                catch (Exception ex)
                {
                    RM.Message = ex.Message;
                }
            }
            else
            {
                RM.IsSuccess = false;
                RM.Message = "数据格式不正确";
            }
            return Json(RM);
        }
Example #23
0
        // private static VirtualDeviceConfigSpec GetIDEController(int key)
        // {
        //     VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec();
        //     devicespec.device = new VirtualIDEController();
        //     devicespec.device.key = key;
        //     devicespec.operation = VirtualDeviceConfigSpecOperation.add;
        //     devicespec.operationSpecified = true;
        //     return devicespec;
        // }

        private static VirtualDeviceConfigSpec GetSCSIController(ref int key, string type)
        {
            VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec();
            VirtualDevice           device     = null;

            // DISK CONTROLLER
            if (type.ToLower().EndsWith("sas"))
            {
                VirtualLsiLogicSASController sas = new VirtualLsiLogicSASController();
                sas.busNumber = 0;
                sas.sharedBus = VirtualSCSISharing.noSharing;
                sas.key       = key--;
                device        = sas;
            }

            if (type.ToLower() == "lsilogic")
            {
                VirtualLsiLogicController controller = new VirtualLsiLogicController();
                controller.busNumber = 0;
                controller.sharedBus = VirtualSCSISharing.noSharing;
                controller.key       = key--;
                device = controller;
            }

            if (type.ToLower() == "buslogic")
            {
                VirtualBusLogicController bus = new VirtualBusLogicController();
                bus.busNumber     = 0;
                bus.sharedBus     = VirtualSCSISharing.noSharing;
                bus.controllerKey = key--;
                device            = bus;
            }

            devicespec.device             = device;
            devicespec.operation          = VirtualDeviceConfigSpecOperation.add;
            devicespec.operationSpecified = true;

            return(devicespec);
        }
Example #24
0
        private async void connect_Click(object sender, EventArgs e)
        {
            var onlineStatus = online.Checked;

            if (onlineStatus)
            {
                _client.Disconnect();
                return;
            }
            var mac      = deviceNo.Text;
            var ip       = this.ip.Text;
            var port     = Convert.ToInt32(this.port.Text);
            var device   = new VirtualDevice(mac, showSend, showRecv, onlineChange);
            var hbSwitch = heartbeat.Checked;
            var interval = 30;

            if (!String.IsNullOrEmpty(heartBeatInterval.Text))
            {
                interval = Convert.ToInt32(heartBeatInterval.Text);
            }
            _client = new VirtualClient(ip, port, hbSwitch, interval, device);
            await _client.Start();
        }
Example #25
0
        /// <summary>
        /// This method reverse engineers the active custom schedule from the given
        /// MIF file.
        /// </summary>
        /// <returns>The reverse engineered custom schedule.</returns>
        //  Revision History
        //  MM/DD/YY Who Version Issue# Description
        //  -------- --- ------- ------ ---------------------------------------------
        //  10/08/08 jrf 9.50           Created.
        //
        private void ReverseEngineerCustomSchedule()
        {
            object objValue         = null;
            short  sResponse        = DEVICE_SERVER_SUCCESS;
            short  sDisplayProgress = 0;

            DateTime[]     adtBillingDates;
            DateCollection colBillingDates = new DateCollection();

            if (false == m_bHasHHFBeenRead)
            {
                sResponse = (short)OpenHHF();
            }

            if (DEVICE_SERVER_SUCCESS == sResponse)
            {
                //Get the array of billing dates
                sResponse = VirtualDevice.GetValue(BILLING_SCHEDULE_ITEMS, ref objValue, sDisplayProgress);
            }

            if (DEVICE_SERVER_SUCCESS == sResponse && null != objValue)
            {
                adtBillingDates = (DateTime[])Convert.ChangeType(objValue, typeof(DateTime[]), CultureInfo.InvariantCulture);

                //Populate a date collection
                foreach (DateTime dtDate in adtBillingDates)
                {
                    colBillingDates.Add(dtDate);
                }

                //Add dates to the new schedule
                m_CustomSchedule = new CCustomSchedule();

                m_CustomSchedule.AddDates(colBillingDates);
            }
        }
Example #26
0
 /// <summary>
 /// Create a new <see cref="VirtualDeviceSession"/> instance.
 /// </summary>
 /// <param name="virtualDevice">The <see cref="VirtualDevice"/> associated to this session.</param>
 public VirtualDeviceSession(VirtualDevice virtualDevice)
 {
     Device = virtualDevice;
 }
Example #27
0
        public VirtualMachineConfigSpec createVmConfigSpec(String vmName,

                                                           String datastoreName,

                                                           int diskSizeMB,

                                                           ManagedObjectReference computeResMor,

                                                           ManagedObjectReference hostMor)

        {
            ConfigTarget configTarget = getConfigTargetForHost(computeResMor, hostMor);

            VirtualDevice[] defaultDevices = getDefaultDevices(computeResMor, hostMor);

            VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();



            String networkName = null;

            if (configTarget.network != null)

            {
                for (int i = 0; i < configTarget.network.Length; i++)

                {
                    VirtualMachineNetworkInfo netInfo = configTarget.network[i];

                    NetworkSummary netSummary = netInfo.network;

                    if (netSummary.accessible)

                    {
                        networkName = netSummary.name;

                        break;
                    }
                }
            }

            ManagedObjectReference datastoreRef = null;

            if (datastoreName != null)

            {
                Boolean flag = false;

                for (int i = 0; i < configTarget.datastore.Length; i++)

                {
                    VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i];

                    DatastoreSummary dsSummary = vdsInfo.datastore;

                    if (dsSummary.name.Equals(datastoreName))

                    {
                        flag = true;

                        if (dsSummary.accessible)

                        {
                            datastoreName = dsSummary.name;

                            datastoreRef = dsSummary.datastore;
                        }

                        else

                        {
                            throw new Exception("Specified Datastore is not accessible");
                        }

                        break;
                    }
                }

                if (!flag)

                {
                    throw new Exception("Specified Datastore is not Found");
                }
            }

            else

            {
                Boolean flag = false;

                for (int i = 0; i < configTarget.datastore.Length; i++)

                {
                    VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i];

                    DatastoreSummary dsSummary = vdsInfo.datastore;

                    if (dsSummary.accessible)

                    {
                        datastoreName = dsSummary.name;

                        datastoreRef = dsSummary.datastore;

                        flag = true;

                        break;
                    }
                }

                if (!flag)

                {
                    throw new Exception("No Datastore found on host");
                }
            }

            String datastoreVolume = getVolumeName(datastoreName);

            VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();

            vmfi.vmPathName = datastoreVolume;

            configSpec.files = vmfi;

            // Add a scsi controller

            int diskCtlrKey = 1;

            VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec();

            scsiCtrlSpec.operation = VirtualDeviceConfigSpecOperation.add;

            scsiCtrlSpec.operationSpecified = true;

            VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController();

            scsiCtrl.busNumber = 0;

            scsiCtrlSpec.device = scsiCtrl;

            scsiCtrl.key = diskCtlrKey;

            scsiCtrl.sharedBus = VirtualSCSISharing.noSharing;

            String ctlrType = scsiCtrl.GetType().Name;



            // Find the IDE controller

            VirtualDevice ideCtlr = null;

            for (int di = 0; di < defaultDevices.Length; di++)

            {
                if (defaultDevices[di].GetType().Name.Equals("VirtualIDEController"))

                {
                    ideCtlr = defaultDevices[di];

                    break;
                }
            }



            // Add a floppy

            VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec();

            floppySpec.operation = VirtualDeviceConfigSpecOperation.add;

            floppySpec.operationSpecified = true;

            VirtualFloppy floppy = new VirtualFloppy();

            VirtualFloppyDeviceBackingInfo flpBacking = new VirtualFloppyDeviceBackingInfo();

            flpBacking.deviceName = "/dev/fd0";

            floppy.backing = flpBacking;

            floppy.key = 3;

            floppySpec.device = floppy;



            // Add a cdrom based on a physical device

            VirtualDeviceConfigSpec cdSpec = null;



            if (ideCtlr != null)

            {
                cdSpec = new VirtualDeviceConfigSpec();

                cdSpec.operation = VirtualDeviceConfigSpecOperation.add;

                cdSpec.operationSpecified = true;

                VirtualCdrom cdrom = new VirtualCdrom();

                VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo();

                cdDeviceBacking.datastore = datastoreRef;

                cdDeviceBacking.fileName = datastoreVolume + "testcd.iso";

                cdrom.backing = cdDeviceBacking;

                cdrom.key = 20;

                cdrom.controllerKey = ideCtlr.key;

                cdrom.controllerKeySpecified = true;

                cdrom.unitNumberSpecified = true;

                cdrom.unitNumber = 0;

                cdSpec.device = cdrom;
            }



            // Create a new disk - file based - for the vm

            VirtualDeviceConfigSpec diskSpec = null;

            diskSpec = createVirtualDisk(datastoreName, diskCtlrKey, datastoreRef, diskSizeMB);



            // Add a NIC. the network Name must be set as the device name to create the NIC.

            VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();

            if (networkName != null)

            {
                nicSpec.operation = VirtualDeviceConfigSpecOperation.add;

                nicSpec.operationSpecified = true;

                VirtualEthernetCard nic = new VirtualPCNet32();

                VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();

                nicBacking.deviceName = networkName;

                nic.addressType = "generated";

                nic.backing = nicBacking;

                nic.key = 4;

                nicSpec.device = nic;
            }



            var deviceConfigSpec = new List <VirtualDeviceConfigSpec>();

            deviceConfigSpec.Add(scsiCtrlSpec);

            deviceConfigSpec.Add(floppySpec);

            deviceConfigSpec.Add(diskSpec);

            deviceConfigSpec.Add(nicSpec);



            if (ideCtlr != null)

            {
                deviceConfigSpec.Add(cdSpec);
            }



            configSpec.deviceChange = deviceConfigSpec.ToArray();

            return(configSpec);
        }
        public ActionResult GetVirtualDeviceList(int page = 1, int rows = 20, VirtualDevice search = null, string sidx = null, string sord = "asc")
        {
            if (string.IsNullOrEmpty(sidx))
            {
                sidx = "MachineName";
            }
            var pager = new PageInfo
            {
                PageSize         = rows,
                CurrentPageIndex = page > 0 ? page : 1
            };

            List <IMongoQuery> queryList = null;

            if (search != null)
            {
                queryList = new List <IMongoQuery>();
                if (!string.IsNullOrWhiteSpace(search.MachineName))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.MachineName,
                                                                 new BsonRegularExpression(new Regex(search.MachineName, RegexOptions.IgnoreCase))));
                }
                if (!string.IsNullOrWhiteSpace(search.ModelNum))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.ModelNum,
                                                                 new BsonRegularExpression(new Regex(search.ModelNum, RegexOptions.IgnoreCase))));
                }
                if (search.HostDevice.HasValue)
                {
                    queryList.Add(Query <VirtualDevice> .EQ(t => t.HostDevice, search.HostDevice));
                }
                if (!string.IsNullOrWhiteSpace(search.PublicIP))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.PublicIP, search.PublicIP));
                }
                if (!string.IsNullOrWhiteSpace(search.IntranetIP))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.IntranetIP, search.IntranetIP));
                }
                if (!string.IsNullOrWhiteSpace(search.DomainIP))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.DomainIP, search.DomainIP));
                }
                if (!string.IsNullOrWhiteSpace(search.Cpu))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.Cpu,
                                                                 new BsonRegularExpression(new Regex(search.Cpu, RegexOptions.IgnoreCase))));
                }
                if (!string.IsNullOrWhiteSpace(search.Memory))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.Memory,
                                                                 new BsonRegularExpression(new Regex(search.Memory, RegexOptions.IgnoreCase))));
                }
                if (!string.IsNullOrWhiteSpace(search.Storage))
                {
                    queryList.Add(Query <VirtualDevice> .Matches(t => t.Storage,
                                                                 new BsonRegularExpression(new Regex(search.Storage, RegexOptions.IgnoreCase))));
                }
                if (search.Date.HasValue)
                {
                    queryList.Add(Query <VirtualDevice> .EQ(t => t.Date, search.Date));
                }
                if (search.StartDate.HasValue)
                {
                    queryList.Add(Query <VirtualDevice> .EQ(t => t.StartDate, search.StartDate));
                }
            }
            var where = queryList != null && queryList.Any() ? Query.And(queryList) : null;

            long totalCount;
            var  rm = new JqGridData
            {
                page    = pager.CurrentPageIndex,
                rows    = _bll.GetList(out totalCount, page, rows, where, sidx, sord),
                total   = (int)(totalCount % pager.PageSize == 0 ? totalCount / pager.PageSize : totalCount / pager.PageSize + 1),
                records = (int)totalCount
            };

            return(Json(rm, JsonRequestBehavior.AllowGet));
        }
Example #29
0
        public unsafe CefRect Draw(CefPaintEventArgs e)
        {
            float         ppd    = OffscreenGraphics.PixelsPerDip;
            VirtualDevice device = this.Device;

            CefRect[] dirtyRects = e.DirtyRects;
            if (dirtyRects.Length == 0)
            {
                return(new CefRect());
            }

            CefRect r           = dirtyRects[0];
            CefRect invalidRect = new CefRect(r.X, r.Y, r.Width, r.Height);

            for (int i = 1; i < dirtyRects.Length; i++)
            {
                invalidRect.Union(dirtyRects[i]);
            }

            if (device != null)
            {
                invalidRect.Scale(device.Scale * ppd / device.DevicePixelRatio);
            }

            if (e.PaintElementType == CefPaintElementType.Popup)
            {
                invalidRect.Offset(_popupBounds.X, _popupBounds.Y);
            }

            if (invalidRect.IsNullSize)
            {
                return(new CefRect());
            }

            lock (_syncRoot)
            {
                int width  = e.Width;
                int height = e.Height;

                if (device != null)
                {
                    if (e.PaintElementType == CefPaintElementType.View)
                    {
                        width  = (int)(_bounds.Width * device.Scale * ppd);
                        height = (int)(_bounds.Height * device.Scale * ppd);
                    }
                    else if (e.PaintElementType == CefPaintElementType.Popup)
                    {
                        width  = (int)(e.Width / device.DevicePixelRatio * device.Scale * ppd);
                        height = (int)(e.Height / device.DevicePixelRatio * device.Scale * ppd);
                    }
                }

                PixelBuffer pixelBuffer;
                if (e.PaintElementType == CefPaintElementType.View)
                {
                    if (ViewPixels == null || ViewPixels.Width != width || ViewPixels.Height != height)
                    {
                        if (ViewPixels != null)
                        {
                            ViewPixels.Dispose();
                        }

                        ViewPixels = new PixelBuffer(width, height);
                    }
                    pixelBuffer = ViewPixels;
                }
                else if (e.PaintElementType == CefPaintElementType.Popup)
                {
                    if (PopupPixels == null || PopupPixels.Width != width || PopupPixels.Height != height)
                    {
                        if (PopupPixels != null)
                        {
                            PopupPixels.Dispose();
                        }
                        PopupPixels = new PixelBuffer(width, height);
                    }
                    pixelBuffer = PopupPixels;
                }
                else
                {
                    return(new CefRect());
                }

                if (e.Width == pixelBuffer.Width && e.Height == pixelBuffer.Height)
                {
                    long bufferSize = pixelBuffer.Source.ByteCount;
                    Buffer.MemoryCopy(e.Buffer.ToPointer(), pixelBuffer.Source.GetPixels().ToPointer(), bufferSize, bufferSize);
                }
                else
                {
                    using (var canvas = new SKCanvas(pixelBuffer.Source))
                        using (var paint = new SKPaint())
                        {
                            canvas.Clear();
                            paint.FilterQuality = SKFilterQuality.Medium;
                            using (var source = new SKBitmap())
                            {
                                source.InstallPixels(new SKImageInfo(e.Width, e.Height, SKColorType.Bgra8888, SKAlphaType.Opaque), e.Buffer);
                                canvas.DrawBitmap(source, new SKRect(0, 0, pixelBuffer.Width, pixelBuffer.Height), paint);
                            }
                            canvas.Flush();
                        }
                }
            }

            invalidRect.Inflate(2, 2);
            return(invalidRect);
        }
Example #30
0
        protected void cmdProvision_Click(object sender, EventArgs e)
        {
            //
            // Ready to provision
            //
            //
            // Populate the moRef objects with actual values
            //
            Globals.mySourceVM = new ManagedObjectReference(cboSourceVms.SelectedItem.Value);
            Globals.myCustomization = new ManagedObjectReference(cboCustomizations.SelectedItem.Value);
            Globals.myCluster = new ManagedObjectReference(cboClusters.SelectedItem.Value);
            Globals.myDatastore = new ManagedObjectReference(cboDatastores.SelectedItem.Value);
            Globals.myPortGroup = new ManagedObjectReference(cboPortGroups.SelectedItem.Value);
            //
            // The idea of using the page to do more than one VM failed rather miserably
            // I'll remove this code as I migrate to using moRefs for everything.
            //
            char[] splitChar;
            string targetVM = txtTargetVm.Text;
            Results_Panel.Visible = false;
            string targetIP = txtIpAddress.Text;
            //
            // Need a random number to pick a random virtual host to place the new vm on
            //
            Random rand = new Random();
            //
            // Validate user entries
            //
            //
            // Do we have a value for the target vm?
            //
            if (targetVM == null || targetVM == "")
            {
                txtErrors.Text = "Please enter a name for the virtual machine.";
                Error_Panel.Visible = true;
                return;
            }
            //
            // Make sure that we don't create a machine with a longer name than what netbios supports
            //
            if (targetVM.Length > 15)
            {
                txtErrors.Text = "Please enter a NetBIOS name shorter than 15 characters for the virtual machine.";
                Error_Panel.Visible = true;
                return;
            }
            //
            // http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2009820
            //
            if (targetVM.Contains("_"))
            {
                txtErrors.Text = "Underscore characters not supported for cloning.";
                Error_Panel.Visible = true;
                return;
            }
            //
            // Has a valid IP address been entered?
            //
            IPAddress theIp;
            bool ipResult = IPAddress.TryParse(targetIP, out theIp);
            if (ipResult != true)
            {
                txtErrors.Text = "Please enter a valid IP Address.";
                Error_Panel.Visible = true;
                return;
            }
            //
            // This does some basic checking on a subnet
            //
            IPAddress theMask;
            bool mskResult = IPAddress.TryParse(txtSubnet.Text, out theMask);
            if (mskResult != true)
            {
                txtErrors.Text = "Please enter a valid Subnet Mask.";
                Error_Panel.Visible = true;
                return;
            }
            //
            // Has a valid IP been entered for the gateway?
            //
            IPAddress theGateway;
            bool gwResult = IPAddress.TryParse(txtGateway.Text, out theGateway);
            if (gwResult != true)
            {
                txtErrors.Text = "Please entera valid IP Address for the default gateway.";
                Error_Panel.Visible = true;
                return;
            }
            //
            // Does a vm by this name already exist?
            //
            VimClient vimClient = functions.ConnectServer(Globals.sViServer, Globals.sUsername, Globals.sPassword);
            NameValueCollection filter = new NameValueCollection();
            filter.Add("name", targetVM);
            VirtualMachine chkVirtualMachine = functions.GetEntity<VirtualMachine>(vimClient, null, filter, null);
            filter.Remove("name");
            if (chkVirtualMachine != null)
            {
                vimClient.Disconnect();
                txtErrors.Text = "virtual machine " + targetVM + " already exists";
                Error_Panel.Visible = true;
                return;
            }
            //
            // Need to parse the value of the dropdown
            //
            splitChar = new char[] { '.' };
            string[] specType = cboCustomizations.SelectedValue.Split(splitChar);
            //
            // Connect to selected datacenter
            //
            ClusterComputeResource itmCluster = functions.GetObject<ClusterComputeResource>(vimClient, Globals.myCluster, null);
            filter.Add("hostFolder", itmCluster.Parent.Value);
            Datacenter itmDatacenter = functions.GetEntity<Datacenter>(vimClient, null, filter, null);
            filter.Remove("hostFolder");
            //
            // Get a list of hosts in the selected cluster
            //
            ManagedObjectReference[] lstHosts = itmCluster.Host;
            //
            // Randomly pick host
            //

            HostSystem selectedHost = functions.GetObject<HostSystem>(vimClient, lstHosts[rand.Next(0, lstHosts.Count())], null);
            txtResults.Text = "Host : " + selectedHost.Name + "\r\n";
            //
            // Connect to selected vm to clone
            //
            filter.Add("name", cboSourceVms.SelectedItem.Text);
            VirtualMachine itmVirtualMachine = functions.GetEntity<VirtualMachine>(vimClient, null, filter, null);
            filter.Remove("name");
            //
            // Make sure the spec file type matches the guest os
            //
            //
            // The commented code could be used to poweron a vm, check it's guestfamily and then turn it off.
            //
            //string GuestFamily = null;
            //if (itmVirtualMachine.Runtime.PowerState == VirtualMachinePowerState.poweredOff)
            //{
            //    //
            //    // We can power on the vm to get the guestfamily property
            //    //
            //    itmVirtualMachine.PowerOnVM(null);
            //    //
            //    // Set the GuestFamily var
            //    //
            //    while (itmVirtualMachine.Guest.GuestFamily == null)
            //    {
            //        //
            //        // Need to grab the current guest status from the vm
            //        //
            //        itmVirtualMachine.Reload();
            //        GuestFamily = itmVirtualMachine.Guest.GuestFamily;
            //    }
            //    //
            //    // Turn the VM back off
            //    //
            //    itmVirtualMachine.PowerOffVM();
            //}
            //
            // Added this test to accomodate cloning templates to vm's, per Ryan Lawrence.
            //
            if (!(chkTemplate.Checked))
            {
                if (itmVirtualMachine.Guest.GuestFamily != null)
                {
                    string GuestFamily = itmVirtualMachine.Guest.GuestFamily.ToLower();
                    string TargetType = specType[specType.GetUpperBound(0)].ToLower();
                    if (GuestFamily.Contains(TargetType) == false)
                    {
                        vimClient.Disconnect();
                        txtErrors.Text = "You specified a " + specType[specType.GetUpperBound(0)] + " spec file to clone a " + itmVirtualMachine.Guest.GuestFamily + " virtual machine.";
                        Error_Panel.Visible = true;
                        return;
                    }
                }
                else
                {
                    //
                    // Sometimes the GuestFamily property isn't populated
                    //
                    vimClient.Disconnect();
                    txtErrors.Text = "The virtual machine " + itmVirtualMachine.Name.ToString() + " has no GuestFamily property populated, please power on this VM and verify that it's a supported Guest Os.";
                    Error_Panel.Visible = true;
                    return;
                }
            }
            txtResults.Text += "Source : " + itmVirtualMachine.Name + "\r\n";
            //
            // Connect to the selected datastore
            //
            filter.Add("name", cboDatastores.SelectedItem.Text);
            Datastore itmDatastore = functions.GetEntity<Datastore>(vimClient, null, filter, null);
            filter.Remove("name");
            txtResults.Text += "Datastore : " + itmDatastore.Name + "\r\n";
            //
            // Connect to portgroup
            //
            filter.Add("name", cboPortGroups.SelectedItem.Text);
            DistributedVirtualPortgroup itmDvPortGroup = functions.GetEntity<DistributedVirtualPortgroup>(vimClient, null, filter, null);
            filter.Remove("name");
            txtResults.Text += "Portgroup : " + itmDvPortGroup.Name + "\r\n";
            //
            // Connect to the customizationspec
            //
            CustomizationSpecManager specManager = functions.GetObject<CustomizationSpecManager>(vimClient, vimClient.ServiceContent.CustomizationSpecManager, null);
            CustomizationSpecItem itmCustomizationSpecItem = specManager.GetCustomizationSpec(cboCustomizations.SelectedItem.Text);
            txtResults.Text += "Spec : " + cboCustomizations.SelectedItem.Text + "\r\n";
            //
            // Create a new VirtualMachineCloneSpec
            //
            VirtualMachineCloneSpec mySpec = new VirtualMachineCloneSpec();
            mySpec.Location = new VirtualMachineRelocateSpec();
            mySpec.Location.Datastore = itmDatastore.MoRef;
            mySpec.Location.Host = selectedHost.MoRef;
            //
            // Get resource pool for selected cluster
            //
            filter.Add("parent", itmCluster.Parent.ToString());
            ResourcePool itmResPool = functions.GetObject<ResourcePool>(vimClient, itmCluster.ResourcePool, null);
            filter.Remove("parent");
            //
            // Assign resource pool to specitem
            //
            mySpec.Location.Pool = itmResPool.MoRef;
            //
            // Add selected CloneSpec customizations to this CloneSpec
            //
            mySpec.Customization = itmCustomizationSpecItem.Spec;
            //
            // Handle hostname for either windows or linux
            //
            if (specType[specType.GetUpperBound(0)] == "Windows")
            {
                //
                // Create a windows sysprep object
                //
                CustomizationSysprep winIdent = (CustomizationSysprep)itmCustomizationSpecItem.Spec.Identity;
                CustomizationFixedName hostname = new CustomizationFixedName();
                hostname.Name = targetVM;
                winIdent.UserData.ComputerName = hostname;
                //
                // Store identity in this CloneSpec
                //
                mySpec.Customization.Identity = winIdent;
            }
            if (specType[specType.GetUpperBound(0)] == "Linux")
            {
                //
                // Create a Linux "sysprep" object
                //
                CustomizationLinuxPrep linIdent = (CustomizationLinuxPrep)itmCustomizationSpecItem.Spec.Identity;
                CustomizationFixedName hostname = new CustomizationFixedName();
                hostname.Name = targetVM;
                linIdent.HostName = hostname;
                //
                // Uncomment the line below to add a suffix to linux vm's
                //
                // linIdent.Domain = WebConfigurationManager.AppSettings["dnsSuffix"].ToString();
                //
                // Store identity in this CloneSpec
                //
                mySpec.Customization.Identity = linIdent;
            }
            //
            // Create a new ConfigSpec
            //
            mySpec.Config = new VirtualMachineConfigSpec();
            //
            // Set number of CPU's
            //
            int numCpus = new int();
            numCpus = Convert.ToInt16(cboCpus.SelectedValue);
            mySpec.Config.NumCPUs = numCpus;
            txtResults.Text += "CPU : " + numCpus + "\r\n";
            //
            // Set amount of RAM
            //
            long memoryMb = new long();
            memoryMb = (long)(Convert.ToInt16(cboRam.SelectedValue) * 1024);
            mySpec.Config.MemoryMB = memoryMb;
            txtResults.Text += "Ram : " + memoryMb + "\r\n";
            //
            // Only handle the first network card
            //
            mySpec.Customization.NicSettingMap = new CustomizationAdapterMapping[1];
            mySpec.Customization.NicSettingMap[0] = new CustomizationAdapterMapping();
            //
            // Read in the DNS from web.config and assign
            //
            string[] ipDns = new string[1];
            ipDns[0] = txtDnsServer.Text;
            mySpec.Customization.GlobalIPSettings = new CustomizationGlobalIPSettings();
            mySpec.Customization.GlobalIPSettings.DnsServerList = ipDns;
            txtResults.Text += "DNS : " + ipDns[0] + "\r\n";
            //
            // Create a new networkDevice
            //
            VirtualDevice networkDevice = new VirtualDevice();
            foreach (VirtualDevice vDevice in itmVirtualMachine.Config.Hardware.Device)
            {
                //
                // get nic on vm
                //
                if (vDevice.DeviceInfo.Label.Contains("Network"))
                {
                    networkDevice = vDevice;
                }
            }
            //
            // Create a DeviceSpec
            //
            VirtualDeviceConfigSpec[] devSpec = new VirtualDeviceConfigSpec[0];
            mySpec.Config.DeviceChange = new VirtualDeviceConfigSpec[1];
            mySpec.Config.DeviceChange[0] = new VirtualDeviceConfigSpec();
            mySpec.Config.DeviceChange[0].Operation = VirtualDeviceConfigSpecOperation.edit;
            mySpec.Config.DeviceChange[0].Device = networkDevice;
            //
            // Define network settings for the new vm
            //
            //
            // Assign IP Address
            //
            CustomizationFixedIp ipAddress = new CustomizationFixedIp();
            ipAddress.IpAddress = targetIP;
            mySpec.Customization.NicSettingMap[0].Adapter = new CustomizationIPSettings();
            txtResults.Text += "IP : " + targetIP + "\r\n";
            //
            // Assign subnet mask
            //
            mySpec.Customization.NicSettingMap[0].Adapter.Ip = ipAddress;
            mySpec.Customization.NicSettingMap[0].Adapter.SubnetMask = txtSubnet.Text;
            txtResults.Text += "Subnet : " + txtSubnet.Text + "\r\n";
            //
            // Assign default gateway
            //
            string[] ipGateway = new string[1];
            ipGateway[0] = txtGateway.Text;
            mySpec.Customization.NicSettingMap[0].Adapter.Gateway = ipGateway;
            txtResults.Text += "Gateway : " + txtGateway.Text + "\r\n";
            //
            // Create network backing information
            //
            VirtualEthernetCardDistributedVirtualPortBackingInfo nicBack = new VirtualEthernetCardDistributedVirtualPortBackingInfo();
            nicBack.Port = new DistributedVirtualSwitchPortConnection();
            //
            // Connect to the virtual switch
            //
            VmwareDistributedVirtualSwitch dvSwitch = functions.GetObject<VmwareDistributedVirtualSwitch>(vimClient, itmDvPortGroup.Config.DistributedVirtualSwitch, null);
            //
            // Assign the proper switch port
            //
            nicBack.Port.SwitchUuid = dvSwitch.Uuid;
            //
            // Connect the network card to proper port group
            //
            nicBack.Port.PortgroupKey = itmDvPortGroup.MoRef.Value;
            mySpec.Config.DeviceChange[0].Device.Backing = nicBack;
            //
            // Enable the network card at bootup
            //
            mySpec.Config.DeviceChange[0].Device.Connectable = new VirtualDeviceConnectInfo();
            mySpec.Config.DeviceChange[0].Device.Connectable.StartConnected = true;
            mySpec.Config.DeviceChange[0].Device.Connectable.AllowGuestControl = true;
            mySpec.Config.DeviceChange[0].Device.Connectable.Connected = true;
            //
            // Get the vmfolder from the datacenter
            //
            //
            // Perform the clone
            //
            txtWorking.Text = "Currently cloning " + targetVM + " please wait.";
            Working_Panel.Visible = true;
            Globals.myTask = itmVirtualMachine.CloneVM_Task(itmDatacenter.VmFolder, targetVM, mySpec);
            Task cloneVmTask = new Task(vimClient, Globals.myTask);
            //
            // The following will make the browser appear to hang, I need to hide this panel, and show a working panel
            //
            Globals.myClone = (ManagedObjectReference)vimClient.WaitForTask(cloneVmTask.MoRef);
            ////
            //// Connect to the VM in order to set the custom fields
            //// Custom Fields are only available when connecting to Vsphere, and not to an individual esxi host
            ////
            //filter.Add("name", targetVM);
            //VirtualMachine clonedVM = functions.GetEntity<VirtualMachine>(vimClient, null, filter, null);
            //filter.Remove("name");
            ////
            //// We need to get a list of the Custom Fields from vsphere, that information is stored in ServiceContent.CustomFieldsManager
            ////
            //CustomFieldsManager fieldManager = functions.GetObject<CustomFieldsManager>(vimClient, vimClient.ServiceContent.CustomFieldsManager, null);
            ////
            //// One or more custom field names could be stored in the web.config and processed in some fashion
            ////
            //foreach (CustomFieldDef thisField in fieldManager.Field)
            //{
            //    //
            //    // These fields exist in my test environment, you will need to use your own inside the quotes
            //    //
            //    if (thisField.Name.Equals("CreatedBy"))
            //    {
            //        fieldManager.SetField(clonedVM.MoRef, thisField.Key, txtUsername.Text);
            //    }
            //    if (thisField.Name.Equals("CreatedOn"))
            //    {
            //        fieldManager.SetField(clonedVM.MoRef, thisField.Key, System.DateTime.Now.ToString());
            //    }
            //}
            vimClient.Disconnect();
            //
            // Hide the vm controls and show the result box
            //
            Working_Panel.Visible = false;
            Vm_Panel.Visible = false;
            Results_Panel.Visible = true;
        }
Example #31
0
        private void RunFuzzedTest(bool useSubgroupConstruction, string hashFunction, int numberOfAttributes, bool supportDevice, int numberOfTokens, int[] dArray, int[] cArray, int pseudonymIndex)
        {
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters(numberOfAttributes);

            isp.GroupConstruction = useSubgroupConstruction ? GroupType.Subgroup : GroupType.ECC;
            isp.UidP = GetRandomBytes(MaxByteArrayLength);
            isp.UidH = hashFunction;
            //isp.E = IssuerSetupParameters.GetDefaultEValues(numberOfAttributes);  // extension by Fablei -> do not change MaxNumberOfAttributes
            isp.S = GetRandomBytes(MaxByteArrayLength);
            IssuerKeyAndParameters ikap = isp.Generate(supportDevice);
            IssuerParameters       ip   = ikap.IssuerParameters;

            ip.Verify();

            IDevice      device = null;
            GroupElement hd     = null;

            if (supportDevice)
            {
                device = new VirtualDevice(ip);
                hd     = device.GetDevicePublicKey();
            }

            // Issuance
            byte[][] attributes = new byte[numberOfAttributes][];
            for (int index = 0; index < numberOfAttributes; index++)
            {
                attributes[index] = GetRandomBytes(MaxByteArrayLength);
            }
            byte[] tokenInformation  = GetRandomBytes(MaxByteArrayLength);
            byte[] proverInformation = GetRandomBytes(MaxByteArrayLength);

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numberOfTokens;
            ipp.TokenInformation = tokenInformation;
            ipp.DevicePublicKey  = hd;
            Issuer issuer = ipp.CreateIssuer();

            string msg1 = ip.Serialize(issuer.GenerateFirstMessage());

            ProverProtocolParameters ppp = new ProverProtocolParameters(ip);

            ppp.Attributes        = attributes;
            ppp.NumberOfTokens    = numberOfTokens;
            ppp.TokenInformation  = tokenInformation;
            ppp.ProverInformation = proverInformation;
            ppp.DevicePublicKey   = hd;
            Prover prover = ppp.CreateProver();
            string msg2   = ip.Serialize(prover.GenerateSecondMessage(ip.Deserialize <FirstIssuanceMessage>(msg1)));
            string msg3   = ip.Serialize(issuer.GenerateThirdMessage(ip.Deserialize <SecondIssuanceMessage>(msg2)));

            // issue token
            UProveKeyAndToken[] upkt = prover.GenerateTokens(ip.Deserialize <ThirdIssuanceMessage>(msg3));

            // Presentation
            byte[] message       = GetRandomBytes(MaxByteArrayLength);
            byte[] deviceMessage = null;
            IDevicePresentationContext deviceContext = null;

            if (supportDevice)
            {
                deviceMessage = GetRandomBytes(MaxByteArrayLength);
                deviceContext = device.GetPresentationContext();
            }
            int tokenIndex = random.Next(upkt.Length);

            // generate the presentation proof
            PresentationProof proof = PresentationProof.Generate(ip, dArray, message, deviceMessage, deviceContext, upkt[tokenIndex], attributes);

            // verify the presentation proof
            proof.Verify(ip, dArray, message, deviceMessage, upkt[tokenIndex].Token);
        }
Example #32
0
 protected void cmdProvision_Click(object sender, EventArgs e)
 {
     //
     // Ready to provision
     //
     //
     // Need a random number to pick a random virtual host to place the new vm on
     //
     Random rand = new Random();
     //
     // Validate user entries
     //
     //
     // Do we have a value for the target vm?
     //
     if (txtTargetVm.Text == null || txtTargetVm.Text == "")
     {
         txtErrors.Text = "Please enter a name for the virtual machine.";
         Error_Panel.Visible = true;
         return;
     }
     //
     // Has a valid IP address been entered?
     //
     IPAddress theIp;
     bool ipResult = IPAddress.TryParse(txtIpAddress.Text, out theIp);
     if (ipResult != true)
     {
         txtErrors.Text = "Please enter a valid IP Address.";
         Error_Panel.Visible = true;
         return;
     }
     //
     // This does some basic checking on a subnet
     //
     IPAddress theMask;
     bool mskResult = IPAddress.TryParse(txtSubnet.Text, out theMask);
     if (mskResult != true)
     {
         txtErrors.Text = "Please enter a valid Subnet Mask.";
         Error_Panel.Visible = true;
         return;
     }
     //
     // Has a valid IP been entered for the gateway?
     //
     IPAddress theGateway;
     bool gwResult = IPAddress.TryParse(txtGateway.Text, out theGateway);
     if (gwResult != true)
     {
         txtErrors.Text = "Please entera valid IP Address for the default gateway.";
         Error_Panel.Visible = true;
         return;
     }
     //
     // Does a vm by this name already exist?
     //
     VimClient vimClient = ConnectServer(Globals.sViServer, Globals.sUsername, Globals.sPassword);
     List<VirtualMachine> chkVirtualMachines = GetVirtualMachines(vimClient, null, txtTargetVm.Text);
     if (chkVirtualMachines != null)
     {
         vimClient.Disconnect();
         txtErrors.Text = "virtual machine " + txtTargetVm.Text + " already exists";
         Error_Panel.Visible = true;
         return;
     }
     //
     // Need to parse the value of the dropdown
     //
     char[] splitChar = { '.' };
     string[] specType = cboCustomizations.SelectedValue.Split(splitChar);
     //
     // Connect to selected datacenter
     //
     List<ClusterComputeResource> lstClusters = GetClusters(vimClient, cboClusters.SelectedItem.Text);
     List<Datacenter> lstDatacenters = GetDcFromCluster(vimClient, lstClusters[0].Parent.Value);
     Datacenter itmDatacenter = lstDatacenters[0];
     //
     // Get a list of hosts in the selected cluster
     //
     List<HostSystem> lstHosts = GetHosts(vimClient, cboClusters.SelectedValue);
     //
     // Randomly pick host
     //
     HostSystem selectedHost = lstHosts[rand.Next(0, lstHosts.Count)];
     txtResults.Text = "Host : " + selectedHost.Name + "\r\n";
     //
     // Connect to selected vm to clone
     //
     List<VirtualMachine> lstVirtualMachines = GetVirtualMachines(vimClient, null, cboSourceVms.SelectedItem.Text);
     VirtualMachine itmVirtualMachine = lstVirtualMachines[0];
     //
     // Make sure the spec file type matches the guest os
     //
     //
     // The commented code could be used to poweron a vm, check it's guestfamily and then turn it off.
     //
     //string GuestFamily = null;
     //if (itmVirtualMachine.Runtime.PowerState == VirtualMachinePowerState.poweredOff)
     //{
     //    //
     //    // We can power on the vm to get the guestfamily property
     //    //
     //    itmVirtualMachine.PowerOnVM(null);
     //    //
     //    // Set the GuestFamily var
     //    //
     //    while (itmVirtualMachine.Guest.GuestFamily == null)
     //    {
     //        //
     //        // Need to grab the current guest status from the vm
     //        //
     //        itmVirtualMachine.Reload();
     //        GuestFamily = itmVirtualMachine.Guest.GuestFamily;
     //    }
     //    //
     //    // Turn the VM back off
     //    //
     //    itmVirtualMachine.PowerOffVM();
     //}
     //
     // Added this test to accomodate cloning templates to vm's, per Ryan Lawrence.
     //
     if (!(chkTemplate.Checked))
     {
         if (itmVirtualMachine.Guest.GuestFamily != null)
         {
             if ((itmVirtualMachine.Guest.GuestFamily).Contains(specType[specType.GetUpperBound(0)]) == false)
             {
                 vimClient.Disconnect();
                 txtErrors.Text = "You specified a " + specType[specType.GetUpperBound(0)] + " spec file to clone a " + itmVirtualMachine.Guest.GuestFamily + " virtual machine.";
                 Error_Panel.Visible = true;
                 return;
             }
         }
         else
         {
             //
             // Sometimes the GuestFamily property isn't populated
             //
             vimClient.Disconnect();
             txtErrors.Text = "The virtual machine " + itmVirtualMachine.Name.ToString() + " has no GuestFamily property populated, please power on this VM and verify that it's a supported Guest Os.";
             Error_Panel.Visible = true;
             return;
         }
     }
     txtResults.Text += "Source : " + itmVirtualMachine.Name + "\r\n";
     //
     // Connect to the selected datastore
     //
     List<Datastore> lstDatastores = GetDataStore(vimClient, null, cboDatastores.SelectedItem.Text);
     Datastore itmDatastore = lstDatastores[0];
     txtResults.Text += "Datastore : " + itmDatastore.Name + "\r\n";
     //
     // Connect to portgroup
     //
     List<DistributedVirtualPortgroup> lstDvPortGroups = GetDVPortGroups(vimClient, itmDatacenter, cboPortGroups.SelectedItem.Text);
     DistributedVirtualPortgroup itmDvPortGroup = lstDvPortGroups[0];
     txtResults.Text += "Portgroup : " + itmDvPortGroup.Name + "\r\n";
     //
     // Connect to the customizationspec
     //
     CustomizationSpecItem itmSpecItem = GetCustomizationSpecItem(vimClient, cboCustomizations.SelectedItem.Text);
     txtResults.Text += "Spec : " + cboCustomizations.SelectedItem.Text + "\r\n";
     //
     // Create a new VirtualMachineCloneSpec
     //
     VirtualMachineCloneSpec mySpec = new VirtualMachineCloneSpec();
     mySpec.Location = new VirtualMachineRelocateSpec();
     mySpec.Location.Datastore = itmDatastore.MoRef;
     mySpec.Location.Host = selectedHost.MoRef;
     //
     // Get resource pool for selected cluster
     //
     List<ResourcePool> lstResPools = GetResPools(vimClient, cboClusters.SelectedValue);
     ResourcePool itmResPool = lstResPools[0];
     //
     // Assign resource pool to specitem
     //
     mySpec.Location.Pool = itmResPool.MoRef;
     //
     // Add selected CloneSpec customizations to this CloneSpec
     //
     mySpec.Customization = itmSpecItem.Spec;
     //
     // Handle hostname for either windows or linux
     //
     if (specType[specType.GetUpperBound(0)] == "Windows")
     {
         //
         // Create a windows sysprep object
         //
         CustomizationSysprep winIdent = (CustomizationSysprep)itmSpecItem.Spec.Identity;
         CustomizationFixedName hostname = new CustomizationFixedName();
         hostname.Name = txtTargetVm.Text;
         winIdent.UserData.ComputerName = hostname;
         //
         // Store identity in this CloneSpec
         //
         mySpec.Customization.Identity = winIdent;
     }
     if (specType[specType.GetUpperBound(0)] == "Linux")
     {
         //
         // Create a Linux "sysprep" object
         //
         CustomizationLinuxPrep linIdent = (CustomizationLinuxPrep)itmSpecItem.Spec.Identity;
         CustomizationFixedName hostname = new CustomizationFixedName();
         hostname.Name = txtTargetVm.Text;
         linIdent.HostName = hostname;
         //
         // Uncomment the line below to add a suffix to linux vm's
         //
         // linIdent.Domain = WebConfigurationManager.AppSettings["dnsSuffix"].ToString();
         //
         // Store identity in this CloneSpec
         //
         mySpec.Customization.Identity = linIdent;
     }
     //
     // Create a new ConfigSpec
     //
     mySpec.Config = new VirtualMachineConfigSpec();
     //
     // Set number of CPU's
     //
     int numCpus = new int();
     numCpus = Convert.ToInt16(cboCpus.SelectedValue);
     mySpec.Config.NumCPUs = numCpus;
     txtResults.Text += "CPU : " + numCpus + "\r\n";
     //
     // Set amount of RAM
     //
     long memoryMb = new long();
     memoryMb = (long)(Convert.ToInt16(cboRam.SelectedValue) * 1024);
     mySpec.Config.MemoryMB = memoryMb;
     txtResults.Text += "Ram : " + memoryMb + "\r\n";
     //
     // Only handle the first network card
     //
     mySpec.Customization.NicSettingMap = new CustomizationAdapterMapping[1];
     mySpec.Customization.NicSettingMap[0] = new CustomizationAdapterMapping();
     //
     // Read in the DNS from web.config and assign
     //
     string[] ipDns = new string[1];
     ipDns[0] = txtDnsServer.Text;
     mySpec.Customization.GlobalIPSettings = new CustomizationGlobalIPSettings();
     mySpec.Customization.GlobalIPSettings.DnsServerList = ipDns;
     txtResults.Text += "DNS : " + ipDns[0] + "\r\n";
     //
     // Create a new networkDevice
     //
     VirtualDevice networkDevice = new VirtualDevice();
     foreach (VirtualDevice vDevice in itmVirtualMachine.Config.Hardware.Device)
     {
         //
         // get nic on vm
         //
         if (vDevice.DeviceInfo.Label.Contains("Network"))
         {
             networkDevice = vDevice;
         }
     }
     //
     // Create a DeviceSpec
     //
     VirtualDeviceConfigSpec[] devSpec = new VirtualDeviceConfigSpec[0];
     mySpec.Config.DeviceChange = new VirtualDeviceConfigSpec[1];
     mySpec.Config.DeviceChange[0] = new VirtualDeviceConfigSpec();
     mySpec.Config.DeviceChange[0].Operation = VirtualDeviceConfigSpecOperation.edit;
     mySpec.Config.DeviceChange[0].Device = networkDevice;
     //
     // Define network settings for the new vm
     //
     //
     // Assign IP Address
     //
     CustomizationFixedIp ipAddress = new CustomizationFixedIp();
     ipAddress.IpAddress = txtIpAddress.Text;
     mySpec.Customization.NicSettingMap[0].Adapter = new CustomizationIPSettings();
     txtResults.Text += "IP : " + txtIpAddress.Text + "\r\n";
     //
     // Assign subnet mask
     //
     mySpec.Customization.NicSettingMap[0].Adapter.Ip = ipAddress;
     mySpec.Customization.NicSettingMap[0].Adapter.SubnetMask = txtSubnet.Text;
     txtResults.Text += "Subnet : " + txtSubnet.Text + "\r\n";
     //
     // Assign default gateway
     //
     string[] ipGateway = new string[1];
     ipGateway[0] = txtGateway.Text;
     mySpec.Customization.NicSettingMap[0].Adapter.Gateway = ipGateway;
     txtResults.Text += "Gateway : " + txtGateway.Text + "\r\n";
     //
     // Create network backing information
     //
     VirtualEthernetCardDistributedVirtualPortBackingInfo nicBack = new VirtualEthernetCardDistributedVirtualPortBackingInfo();
     nicBack.Port = new DistributedVirtualSwitchPortConnection();
     //
     // Connect to the virtual switch
     //
     VmwareDistributedVirtualSwitch dvSwitch = GetDvSwitch(vimClient, itmDvPortGroup.Config.DistributedVirtualSwitch);
     //
     // Assign the proper switch port
     //
     nicBack.Port.SwitchUuid = dvSwitch.Uuid;
     //
     // Connect the network card to proper port group
     //
     nicBack.Port.PortgroupKey = itmDvPortGroup.MoRef.Value;
     mySpec.Config.DeviceChange[0].Device.Backing = nicBack;
     //
     // Enable the network card at bootup
     //
     mySpec.Config.DeviceChange[0].Device.Connectable = new VirtualDeviceConnectInfo();
     mySpec.Config.DeviceChange[0].Device.Connectable.StartConnected = true;
     mySpec.Config.DeviceChange[0].Device.Connectable.AllowGuestControl = true;
     mySpec.Config.DeviceChange[0].Device.Connectable.Connected = true;
     //
     // Get the vmfolder from the datacenter
     //
     //
     // Perform the clone
     //
     ManagedObjectReference taskMoRef = itmVirtualMachine.CloneVM_Task(itmDatacenter.VmFolder, txtTargetVm.Text, mySpec);
     Task cloneVmTask = new Task(vimClient, taskMoRef);
     //
     // The following will make the browser appear to hang, I need to hide this panel, and show a working panel
     //
     ManagedObjectReference clonedMorRef = (ManagedObjectReference)vimClient.WaitForTask(cloneVmTask.MoRef);
     //
     // Connect to the VM in order to set the custom fields
     //
     List<VirtualMachine> clonedVMs = GetVirtualMachines(vimClient, null, txtTargetVm.Text);
     VirtualMachine clonedVM = clonedVMs[0];
     NameValueCollection vmFilter = new NameValueCollection();
     vmFilter.Add("name",txtTargetVm.Text);
     EntityViewBase vmViewBase = vimClient.FindEntityView(typeof(VirtualMachine),null,vmFilter,null);
     ManagedEntity vmEntity = new ManagedEntity(vimClient, clonedVM.MoRef);
     CustomFieldsManager fieldManager = new CustomFieldsManager(vimClient, clonedVM.MoRef);
     //
     // One or more custom field names could be stored in the web.config and processed in some fashion
     //
     foreach (CustomFieldDef thisField in clonedVM.AvailableField)
     { 
         if (thisField.Name.Equals("CreatedBy"))
         {
             fieldManager.SetField(clonedVM.MoRef, 1, txtUsername.Text);
         }
     }
     vimClient.Disconnect();
     //
     // Hide the vm controls and show the result box
     //
     Vm_Panel.Visible = false;
     Results_Panel.Visible = true;
 }