Esempio n. 1
0
        public string GetUsage()
        {
            string usage = "Arguments:" + Environment.NewLine;

            //			usage += ApplicationName + Environment.NewLine;
            string[] switchLine = new string[Switches.Length];
            int      maxWidth   = 0;

            for (int i = 0; i < Switches.Length; i++)
            {
                SwitchInfo s = Switches[i];
                switchLine[i] = "-" + s.Name;
                if (s.Aliases != null)
                {
                    foreach (string alias in s.Aliases)
                    {
                        switchLine[i] += ", -" + alias;
                    }
                }
                maxWidth = Math.Max(maxWidth, switchLine[i].Length);
            }
            for (int i = 0; i < Switches.Length; i++)
            {
                SwitchInfo s = Switches[i];
                usage += (switchLine[i] + ":").PadRight(maxWidth + 5) + s.Description + ((s.Required) ? " (REQUIRED)" : "") + Environment.NewLine;
            }
            return(usage);
        }
Esempio n. 2
0
        private void EmitSwitchBuckets(SwitchInfo info, List <List <SwitchLabel> > buckets, int first, int last)
        {
            if (first == last)
            {
                EmitSwitchBucket(info, buckets[first]);
                return;
            }

            // Split the buckets into two groups, and use an if test to find
            // the right bucket. This ensures we'll only need O(lg(B)) tests
            // where B is the number of buckets
            int mid = (int)(((long)first + last + 1) / 2);

            if (first == mid - 1)
            {
                EmitSwitchBucket(info, buckets[first]);
            }
            else
            {
                // If the first half contains more than one, we need to emit an
                // explicit guard
                Label secondHalf = _ilg.DefineLabel();
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(buckets[mid - 1].Last().Constant);
                _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf);
                EmitSwitchBuckets(info, buckets, first, mid - 1);
                _ilg.MarkLabel(secondHalf);
            }

            EmitSwitchBuckets(info, buckets, mid, last);
        }
        public async Task <SwitchInfo> GetSwitchInfo()
        {
            var client = GetClient(cookies);

            var responseBody = await client.GetStringSafeAsync(GetUrl(connectionInfo, URLs.Index));

            try
            {
                var switchInfo = new SwitchInfo();

                var controllerName = ParseControllerName(responseBody);
                var newOutlets     = ParseRelayName(responseBody);

                switchInfo.Name    = controllerName;
                switchInfo.Outlets = new OutletInfo[newOutlets.Count];
                int index = 0;
                foreach (var item in newOutlets)
                {
                    switchInfo.Outlets[index++] = new OutletInfo()
                    {
                        Index = item.Index, Name = item.Name, IsOn = item.IsOn
                    };
                }

                return(switchInfo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }


            return(null);
        }
 public IHttpActionResult CreateSwitchInfo(SwitchInfoModel model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var switchinformation = new SwitchInfo();
             switchinformation.HostName           = model.HostName;
             switchinformation.SelectManufacturer = model.SelectManufacturer;
             switchinformation.Model     = model.Model;
             switchinformation.OS        = model.OS;
             switchinformation.OSVersion = model.OSVersion;
             switchinformation.ManufacturerPartNumber           = model.ManufacturerPartNumber;
             switchinformation.SerialNumber                     = model.SerialNumber;
             switchinformation.InstallDate                      = model.InstallDate;
             switchinformation.WarrantyStarted                  = model.WarrantyStarted;
             switchinformation.WarrantyExpires                  = model.WarrantyExpires;
             switchinformation.UploadNetworkSwitchConfiguration = model.UploadNetworkSwitchConfiguration;
             switchinformation.Notes     = model.Notes;
             switchinformation.SelectTag = model.SelectTag;
             switchinformation.CompanyId = model.CompanyId;
             db.SwitchInfoes.Add(switchinformation);
             db.SaveChanges();
             return(Ok(switchinformation));
         }
         else
         {
             return(Ok("Please Enter All the mandatory Fields"));
         }
     }
     catch (Exception ex)
     {
         return(Ok("" + ex.Message + ""));
     }
 }
Esempio n. 5
0
 void CreateSwitchInfos(ConfigNode node)
 {
     var si_list = node.GetNodes ("SwitchInfo");
     switch_infos = new List<SwitchInfo> ();
     foreach (var si_node in si_list) {
         var si = new SwitchInfo (internalProp);
         si.Load (si_node);
         switch_infos.Add (si);
     }
 }
Esempio n. 6
0
    public void SwitchType()
    {
        SwitchInfo info = GameController.manager.doorMan.GetSwitchInfoById(id);

        if (info == null)
        {
            return;
        }
        info.SwitchType();
        sr.sprite = spList[(int)info.colorType];
    }
        public static string ToDetailsString(this SwitchInfo switchInfo)
        {
            var sb = new StringBuilder();

            sb.AppendLine($"Switch: {switchInfo.Name}");
            foreach (var o in switchInfo.Outlets)
            {
                sb.AppendLine(o.ToDetailsString());
            }
            return(sb.ToString());
        }
Esempio n. 8
0
    public bool CanEnter()
    {
        bool       sameControl = false;
        SwitchInfo switchInfo  = GameController.manager.doorMan.GetSwitchInfoById(switchId);

        if (switchInfo == null)
        {
            return(false);
        }

        return(switchInfo.colorType == colorType);
    }
Esempio n. 9
0
        // CreateSwitch()
        public void CreateSwitch(SwitchInfo NewSwitch)
        {
            var db = new PocoDynamo(con.GetClient());

            try
            {
                db.RegisterTable <SwitchInfo>();
                db.PutItem(NewSwitch);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nError \nUbicación: Capa DAL -> MSwitchInfo -> CreateSwitch(). \nDescripción: " + ex.Message);
            }
        }
Esempio n. 10
0
        public void CTOR_RecognizesValidFilePath_NonExistent()
        {
            //Arrange
            string[] args = new string[]
            {
                VALID_FILEPATH_NONEXISTENT
            };
            bool expected = true;

            //Act
            SwitchInfo switchInfo = new SwitchInfo(args);
            bool       actual     = switchInfo.TargetFile == VALID_FILEPATH_NONEXISTENT;

            //Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 11
0
        public void CTOR_RecognizesValidFilePath()
        {
            //Arrange
            string[] args = new string[]
            {
                Application_Test.GetAnyFile()
            };
            bool expected = true;

            //Act
            SwitchInfo switchInfo = new SwitchInfo(args);
            bool       actual     = switchInfo.TargetFile == Application_Test.GetAnyFile();

            //Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 12
0
        public void CTOR_TakesR()
        {
            //Arrange
            string[] args = new string[]
            {
                "-r"
            };
            bool expected = true;

            //Act
            SwitchInfo switchInfo = new SwitchInfo(args);
            bool       actual     = switchInfo.Mode == CryptoMode.Read;

            //Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 13
0
        public void CTOR_RejectsInvalidFilePath()
        {
            //Arrange
            string[] args = new string[]
            {
                INVALID_FILEPATH
            };
            bool expected = false;

            //Act
            SwitchInfo switchInfo = new SwitchInfo(args);
            bool       actual     = switchInfo.TargetFile == INVALID_FILEPATH;

            //Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 14
0
        public static void CreateSwitch(string Type, string Switches, string Current, string Caliber, string Comments)
        {
            var IdSwitch  = _tools.Decrypt(IdPanel) + "_" + Switches;
            var NewSwitch = new SwitchInfo
            {
                IdSwitch    = _tools.Encrypt(IdSwitch),
                IdPanel     = IdPanel,
                Type        = _tools.Encrypt(_tools.Capitalize(Type)),
                Switches    = _tools.Encrypt(Switches),
                Current     = _tools.Encrypt(Current),
                Caliber     = _tools.Encrypt(Caliber),
                Comments    = _tools.Encrypt(_tools.Capitalize(Comments)),
                IsAvailable = true
            };

            _switchInfo.CreateSwitch(NewSwitch);
        }
Esempio n. 15
0
 private void Start()
 {
     StartCoroutine(Util.DelayExecute(() =>
     {
         return(GameController.manager.doorMan.initFinish);
     }, () =>
     {
         SwitchInfo info = GameController.manager.doorMan.GetSwitchInfoById(id);
         Debug.Log(info);
         if (info == null)
         {
             return;
         }
         Debug.Log(info.colorType);
         sr.sprite = spList[(int)info.colorType];
         sr.transform.localPosition = new Vector3(sr.transform.localPosition.x, sr.transform.localPosition.y, -0.1f);
     }));
 }
Esempio n. 16
0
    public void ParseDoorInfos()
    {
        JsonData controlData = JsonMapper.ToObject(Resources.Load <TextAsset>("DoorData/doors").text);

        foreach (JsonData item in controlData)
        {
            DoorInfo doorInfo = new DoorInfo();
            doorInfo.id        = (int)item["id"];
            doorInfo.switchId  = (int)item["switchId"];
            doorInfo.colorType = (ColorType)(int)item["type"];
            JsonData dt = item["rooms"];
            for (int i = 0; i < dt.Count; i++)
            {
                doorInfo.roomList.Add((int)dt[i]);
            }
            doorInfoDict[doorInfo.id] = doorInfo;
        }

        JsonData normalData = JsonMapper.ToObject(Resources.Load <TextAsset>("DoorData/switches").text);

        foreach (JsonData item in normalData)
        {
            SwitchInfo switchInfo = new SwitchInfo();
            switchInfo.id                 = (int)item["id"];
            switchInfo.colorType          = (ColorType)(int)item["type"];
            switchInfoDict[switchInfo.id] = switchInfo;
        }

        JsonData enterData = JsonMapper.ToObject(Resources.Load <TextAsset>("DoorData/enters").text);

        foreach (JsonData item in enterData)
        {
            EnterInfo enterInfo = new EnterInfo();
            enterInfo.id = (int)item["id"];
            JsonData dt = item["rooms"];
            for (int i = 0; i < dt.Count; i++)
            {
                enterInfo.roomList.Add((int)dt[i]);
            }
            enterInfoDict[enterInfo.id] = enterInfo;
        }

        initFinish = true;
    }
Esempio n. 17
0
 public EnumSwitchHandler(SwitchInfo switchInfo)
     : base(switchInfo)
 {
 }
        // Tries to emit switch as a jmp table
        private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) {
            // If we have a comparison, bail
            if (node.Comparison != null) {
                return false;
            }

            // Make sure the switch value type and the right side type
            // are types we can optimize
            Type type = node.SwitchValue.Type;
            if (!CanOptimizeSwitchType(type) ||
                !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type)) {
                return false;
            }

            // Make sure all test values are constant, or we can't emit the
            // jump table.
            if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) {
                return false;
            }

            //
            // We can emit the optimized switch, let's do it.
            //

            // Build target labels, collect keys.
            var labels = new Label[node.Cases.Count];
            var isGoto = new bool[node.Cases.Count];

            var uniqueKeys = new Set<decimal>();
            var keys = new List<SwitchLabel>();
            for (int i = 0; i < node.Cases.Count; i++) {

                DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]);

                foreach (ConstantExpression test in node.Cases[i].TestValues) {
                    // Guarenteed to work thanks to CanOptimizeSwitchType.
                    //
                    // Use decimal because it can hold Int64 or UInt64 without
                    // precision loss or signed/unsigned conversions.
                    decimal key = ConvertSwitchValue(test.Value);

                    // Only add each key once. If it appears twice, it's
                    // allowed, but can't be reached.
                    if (!uniqueKeys.Contains(key)) {
                        keys.Add(new SwitchLabel(key, test.Value, labels[i]));
                        uniqueKeys.Add(key);
                    }
                }
            }

            // Sort the keys, and group them into buckets.
            keys.Sort((x, y) => Math.Sign(x.Key - y.Key));
            var buckets = new List<List<SwitchLabel>>();
            foreach (var key in keys) {
                AddToBuckets(buckets, key);
            }

            // Emit the switchValue
            LocalBuilder value = GetLocal(node.SwitchValue.Type);
            EmitExpression(node.SwitchValue);
            _ilg.Emit(OpCodes.Stloc, value);

            // Create end label, and default label if needed
            Label end = _ilg.DefineLabel();
            Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel();

            // Emit the switch
            var info = new SwitchInfo(node, value, @default);
            EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1);

            // Emit the case bodies and default
            EmitSwitchCases(node, labels, isGoto, @default, end, flags);

            FreeLocal(value);
            return true;
        }
Esempio n. 19
0
 public IntSwitchHandler(SwitchInfo switchInfo)
     : base(switchInfo)
 {
 }
Esempio n. 20
0
		} // With
	
	
	// Return a switch statement.
	public StmtFrag Switch( SrcLoc loc, ExprFrag switchValue,
							SwitchInfo switchInfo )
		{
		// HACK snewman 8/15/01: implement switch statements.
		throw new ParseError( "Switch statements not yet implemented",
							  loc );
		} // Switch
        EnumerateSwitch(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");

            //
            // Initialize our SwitchInfo structure to hold information about the switch.
            //
            SwitchInfo ethernetSwitchInfo = new SwitchInfo();

            ethernetSwitchInfo.Name              = switchName;
            ethernetSwitchInfo.Type              = SwitchConnectionType.Private;
            ethernetSwitchInfo.PortList          = new List <PortInfo>();
            ethernetSwitchInfo.SwitchFeatureList = new List <NetworkingUtilities.SwitchFeatureType>();

            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
            {
                //
                // Enumerate the switch's ports.
                //
                using (ManagementObjectCollection portCollection = ethernetSwitch.GetRelated("Msvm_EthernetSwitchPort",
                                                                                             "Msvm_SystemDevice",
                                                                                             null, null, null, null, false, null))
                {
                    foreach (ManagementObject port in portCollection)
                    {
                        using (port)
                        {
                            //
                            // Initialize a PortInfo structure to hold information about this port.
                            //
                            PortInfo portInfo = new PortInfo();
                            portInfo.Type        = PortConnectionType.Nothing;
                            portInfo.FeatureList = new List <NetworkingUtilities.PortFeatureType>();

                            //
                            // The port's connection settings are stored on its related
                            // Msvm_EthernetPortAllocationSettingData object.
                            //
                            using (ManagementObject portSettings = WmiUtilities.GetFirstObjectFromCollection(
                                       port.GetRelated("Msvm_EthernetPortAllocationSettingData",
                                                       "Msvm_ElementSettingData",
                                                       null, null, null, null, false, null)))
                            {
                                //
                                // Determine the port's connection type.
                                //
                                portInfo.Type = DeterminePortType(portSettings);

                                if (portInfo.Type == PortConnectionType.VirtualMachine)
                                {
                                    // Get the name of the connected virtual machine.
                                    using (ManagementObject virtualMachineSettings = WmiUtilities.GetFirstObjectFromCollection(
                                               portSettings.GetRelated("Msvm_VirtualSystemSettingData",
                                                                       "Msvm_VirtualSystemSettingDataComponent",
                                                                       null, null, null, null, false, null)))
                                    {
                                        portInfo.ConnectedName = (string)virtualMachineSettings["ElementName"];
                                    }
                                }
                                else if (portInfo.Type == PortConnectionType.External)
                                {
                                    // Get the name of the external connection.
                                    using (ManagementObject externalAdapter = new ManagementObject(
                                               ((string[])portSettings["HostResource"])[0]))
                                    {
                                        portInfo.ConnectedName = (string)externalAdapter["ElementName"];
                                    }
                                }

                                //
                                // Now determine which advanced properties are configured for this port.
                                // Each Feature has its own class definition and is related to the portSettings
                                // through the Msvm_EthernetPortSettingDataComponent association.
                                //
                                using (ManagementObjectCollection portFeatureCollection =
                                           portSettings.GetRelated("Msvm_EthernetSwitchPortFeatureSettingData",
                                                                   "Msvm_EthernetPortSettingDataComponent",
                                                                   null, null, null, null, false, null))
                                {
                                    foreach (ManagementObject portFeature in portFeatureCollection)
                                    {
                                        using (portFeature)
                                        {
                                            portInfo.FeatureList.Add(DeterminePortFeatureType(portFeature));
                                        }
                                    }
                                }
                            }

                            ethernetSwitchInfo.PortList.Add(portInfo);
                        }
                    }
                }

                //
                // Then enumerate the switch's features.
                //
                using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                           ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                                                     "Msvm_SettingsDefineState",
                                                     null, null, null, null, false, null)))
                    using (ManagementObjectCollection switchFeatures = ethernetSwitchSetting.GetRelated(
                               "Msvm_EthernetSwitchFeatureSettingData",
                               "Msvm_VirtualEthernetSwitchSettingDataComponent",
                               null, null, null, null, false, null))
                        foreach (ManagementObject switchFeature in switchFeatures)
                        {
                            using (switchFeature)
                            {
                                ethernetSwitchInfo.SwitchFeatureList.Add(DetermineSwitchFeatureType(switchFeature));
                            }
                        }
            }

            //
            // Now that we have enumerated all of the switch's ports, we can determine the
            // switch's connection type.
            //
            ethernetSwitchInfo.Type = DetermineSwitchConnectionType(ethernetSwitchInfo.PortList);

            //
            // We now have all of the information we need - output it to the console.
            //
            OutputSwitchInfo(ethernetSwitchInfo);
        }
Esempio n. 22
0
 protected SwitchHandler(SwitchInfo switchInfo)
 {
     SwitchName = switchInfo.Name;
     SwitchProperty = switchInfo.PropertyInfo;
     DefaultValue = switchInfo.DefaultValue;
 }
Esempio n. 23
0
            public static SwitchHandler GetSwitchHandler(SwitchInfo switchInfo)
            {
                var switchType = switchInfo.PropertyInfo.PropertyType;

                if (switchType == typeof(bool))
                {
                    return new ToggleSwitchHandler(switchInfo);
                }

                if (switchType == typeof(int))
                {
                    return new IntSwitchHandler(switchInfo);
                }

                if (switchType == typeof(string))
                {
                    return new ValueSwitchHandler(switchInfo);
                }

                if (switchType.IsSubclassOf(typeof(Enum)))
                {
                    return new EnumSwitchHandler(switchInfo);

                }
                throw new InvalidOperationException(string.Format("Unhandled type for switch {0}", switchInfo.Name));
            }
        private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket) {
            // No need for switch if we only have one value
            if (bucket.Count == 1) {
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(bucket[0].Constant);
                _ilg.Emit(OpCodes.Beq, bucket[0].Label);
                return;
            }

            // 
            // If we're switching off of Int64/UInt64, we need more guards here
            // because we'll have to narrow the switch value to an Int32, and
            // we can't do that unless the value is in the right range.
            //
            Label? after = null;
            if (info.Is64BitSwitch) {
                after = _ilg.DefineLabel();
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(bucket.Last().Constant);
                _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value);
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(bucket[0].Constant);
                _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value);
            }

            _ilg.Emit(OpCodes.Ldloc, info.Value);

            // Normalize key
            decimal key = bucket[0].Key;
            if (key != 0) {
                _ilg.EmitConstant(bucket[0].Constant);
                _ilg.Emit(OpCodes.Sub);
            }

            if (info.Is64BitSwitch) {
                _ilg.Emit(OpCodes.Conv_I4);
            }

            // Collect labels
            int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1);
            Label[] jmpLabels = new Label[len];

            // Initialize all labels to the default
            int slot = 0;
            foreach (SwitchLabel label in bucket) {
                while (key++ != label.Key) {
                    jmpLabels[slot++] = info.Default;
                }
                jmpLabels[slot++] = label.Label;
            }

            // check we used all keys and filled all slots
            Debug.Assert(key == bucket[bucket.Count - 1].Key + 1);
            Debug.Assert(slot == jmpLabels.Length);

            // Finally, emit the switch instruction
            _ilg.Emit(OpCodes.Switch, jmpLabels);

            if (info.Is64BitSwitch) {
                _ilg.MarkLabel(after.Value);
            }
        }
        OutputSwitchInfo(
            SwitchInfo switchInfo)
        {
            Console.WriteLine("Successfully enumerated the ports and port features of the switch '{0}'\n",
                switchInfo.Name);
            Console.WriteLine("The switch's connection type is:");
            Console.WriteLine("    {0}\n", switchInfo.Type);

            //
            // If the switch is connected to an external network, output the name of the network.
            //
            if (switchInfo.Type == SwitchConnectionType.External ||
                switchInfo.Type == SwitchConnectionType.ExternalOnly)
            {
                Console.WriteLine("The switch is connected to the following network:");
                foreach (PortInfo portInfo in switchInfo.PortList)
                {
                    if (portInfo.Type == PortConnectionType.External)
                    {
                        Console.WriteLine("    {0}", portInfo.ConnectedName);
                    }
                }
                Console.WriteLine();
            }

            //
            // Output the virtual machines that are currently connected to this switch.
            //
            Console.WriteLine("The switch is connected to the following virtual machines:");
            
            bool atLeastOneVirtualMachine = false;
            foreach (string virtualMachineName in GetConnectedVirtualMachineList(switchInfo.PortList))
            {
                atLeastOneVirtualMachine = true;
                Console.WriteLine("    {0}", virtualMachineName);
            }

            if (!atLeastOneVirtualMachine)
            {
                Console.WriteLine("    The switch is not connected to any virtual machines");
            }

            Console.WriteLine();

            //
            // Output the advanced features that have been configured for the switch.
            //
            Console.WriteLine("The switch has the following advanced features: ");

            if (switchInfo.SwitchFeatureList.Count > 0)
            {
                foreach (NetworkingUtilities.SwitchFeatureType featureType in switchInfo.SwitchFeatureList)
                {
                    Console.WriteLine("    {0}", featureType.ToString());
                }
            }
            else
            {
                Console.WriteLine("    The switch has no advanced features");
            }

            Console.WriteLine();

            //
            // Now output information about features for each port.
            //
            Console.WriteLine("The switch is connected to {0} ports.", switchInfo.PortList.Count);

            if (switchInfo.PortList.Count > 0)
            {
                Console.WriteLine("Outputting port features for each port:\n");

                int count = 1;
                foreach (PortInfo portInfo in switchInfo.PortList)
                {
                    switch (portInfo.Type)
                    {
                        case PortConnectionType.VirtualMachine:
                            Console.WriteLine("    Port {0} connected to virtual machine '{1}' has the following features:",
                                count, portInfo.ConnectedName);
                            break;

                        case PortConnectionType.External:
                            Console.WriteLine("    Port {0} connected to the external network '{1}' has the following features:",
                                count, portInfo.ConnectedName);
                            break;

                        case PortConnectionType.Internal:
                            Console.WriteLine("    Port {0} connected to the internal network has the following features:",
                                count);
                            break;

                        case PortConnectionType.Nothing:
                            Console.WriteLine("    Port {0} not connected to anything has the following features:",
                                count);
                            break;
                    }

                    if (portInfo.FeatureList.Count > 0)
                    {
                        foreach (NetworkingUtilities.PortFeatureType featureType in portInfo.FeatureList)
                        {
                            Console.WriteLine("       {0}", featureType.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("       The port has no advanced features");
                    }

                    count++;
                    Console.WriteLine();
                }
            }
        }
Esempio n. 26
0
 public ToggleSwitchHandler(SwitchInfo switchInfo)
     : base(switchInfo)
 {
 }
        EnumerateSwitch(
            string switchName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization\v2");
            
            //
            // Initialize our SwitchInfo structure to hold information about the switch.
            //
            SwitchInfo ethernetSwitchInfo = new SwitchInfo();
            ethernetSwitchInfo.Name = switchName;
            ethernetSwitchInfo.Type = SwitchConnectionType.Private;
            ethernetSwitchInfo.PortList = new List<PortInfo>();
            ethernetSwitchInfo.SwitchFeatureList = new List<NetworkingUtilities.SwitchFeatureType>();

            using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope))
            {
                //
                // Enumerate the switch's ports.
                //
                using (ManagementObjectCollection portCollection = ethernetSwitch.GetRelated("Msvm_EthernetSwitchPort",
                    "Msvm_SystemDevice",
                    null, null, null, null, false, null))
                {
                    foreach (ManagementObject port in portCollection)
                    using (port)
                    {
                        //
                        // Initialize a PortInfo structure to hold information about this port.
                        //
                        PortInfo portInfo = new PortInfo();
                        portInfo.Type = PortConnectionType.Nothing;
                        portInfo.FeatureList = new List<NetworkingUtilities.PortFeatureType>();

                        //
                        // The port's connection settings are stored on its related 
                        // Msvm_EthernetPortAllocationSettingData object.
                        //
                        using (ManagementObject portSettings = WmiUtilities.GetFirstObjectFromCollection(
                            port.GetRelated("Msvm_EthernetPortAllocationSettingData",
                                "Msvm_ElementSettingData",
                                null, null, null, null, false, null)))
                        {
                            //
                            // Determine the port's connection type.
                            //
                            portInfo.Type = DeterminePortType(portSettings);

                            if (portInfo.Type == PortConnectionType.VirtualMachine)
                            {
                                // Get the name of the connected virtual machine.
                                using (ManagementObject virtualMachineSettings = WmiUtilities.GetFirstObjectFromCollection(
                                    portSettings.GetRelated("Msvm_VirtualSystemSettingData",
                                        "Msvm_VirtualSystemSettingDataComponent",
                                        null, null, null, null, false, null)))
                                {
                                    portInfo.ConnectedName = (string)virtualMachineSettings["ElementName"];
                                }
                            }
                            else if (portInfo.Type == PortConnectionType.External)
                            {
                                // Get the name of the external connection.
                                using (ManagementObject externalAdapter = new ManagementObject(
                                    ((string[])portSettings["HostResource"])[0]))
                                {
                                    portInfo.ConnectedName = (string)externalAdapter["ElementName"];
                                }
                            }

                            //
                            // Now determine which advanced properties are configured for this port. 
                            // Each Feature has its own class definition and is related to the portSettings
                            // through the Msvm_EthernetPortSettingDataComponent association.
                            //
                            using (ManagementObjectCollection portFeatureCollection =
                                    portSettings.GetRelated("Msvm_EthernetSwitchPortFeatureSettingData",
                                        "Msvm_EthernetPortSettingDataComponent",
                                        null, null, null, null, false, null))
                            {
                                foreach (ManagementObject portFeature in portFeatureCollection)
                                    using (portFeature)
                                    {
                                        portInfo.FeatureList.Add(DeterminePortFeatureType(portFeature));
                                    }
                            }
                        }

                        ethernetSwitchInfo.PortList.Add(portInfo);
                    }
                }

                //
                // Then enumerate the switch's features.
                //
                using (ManagementObject ethernetSwitchSetting = WmiUtilities.GetFirstObjectFromCollection(
                    ethernetSwitch.GetRelated("Msvm_VirtualEthernetSwitchSettingData",
                        "Msvm_SettingsDefineState",
                        null, null, null, null, false, null)))
                using (ManagementObjectCollection switchFeatures = ethernetSwitchSetting.GetRelated(
                    "Msvm_EthernetSwitchFeatureSettingData",
                    "Msvm_VirtualEthernetSwitchSettingDataComponent",
                    null, null, null, null, false, null))
                foreach (ManagementObject switchFeature in switchFeatures)
                using (switchFeature)
                {
                    ethernetSwitchInfo.SwitchFeatureList.Add(DetermineSwitchFeatureType(switchFeature));
                }
            }

            //
            // Now that we have enumerated all of the switch's ports, we can determine the 
            // switch's connection type.
            //
            ethernetSwitchInfo.Type = DetermineSwitchConnectionType(ethernetSwitchInfo.PortList);

            //
            // We now have all of the information we need - output it to the console.
            //
            OutputSwitchInfo(ethernetSwitchInfo);
        }
Esempio n. 28
0
 public ValueSwitchHandler(SwitchInfo switchInfo)
     : base(switchInfo)
 {
     _pattern = string.Format(@"^-{0}:((""(.+)"")|([^""]\S*))", switchInfo.Name);
 }
Esempio n. 29
0
		} // ParseForStatement
	
	
	// Parse a Statement.
	private StmtFrag ParseStatement(FunctionInfo info)
		{
		StringCollection labels = MatchLabelSet();
		
		if (tok.TryMatchKeyword("do"))
			{
			LoopInfo loopInfo = gen.NewLoopInfo( curCGFuncInfo, tok.Prev().loc,
												 labels );
			loops.Push(loopInfo);
			
			StmtFrag body = ParseStatement(info);
			tok.MatchKeyword("while");
			tok.MatchOp("(");
			ExprFrag condition = ParseExpression(info, true);
			tok.MatchOp(")");
			tok.MatchOp(";");
			
			LoopInfo temp = (LoopInfo) loops.Pop();
			Trace.Assert(temp == loopInfo);
			
			return gen.DoWhile(loopInfo, body, condition);
			}
		else if (tok.TryMatchKeyword("while"))
			{
			LoopInfo loopInfo = gen.NewLoopInfo( curCGFuncInfo, tok.Prev().loc,
												 labels );
			loops.Push(loopInfo);
			
			tok.MatchOp("(");
			ExprFrag condition = ParseExpression(info, true);
			tok.MatchOp(")");
			StmtFrag body = ParseStatement(info);
			
			LoopInfo temp = (LoopInfo) loops.Pop();
			Trace.Assert(temp == loopInfo);
			
			return gen.WhileDo(loopInfo, condition, body);
			}
		else if (tok.TryMatchKeyword("for"))
			return ParseForStatement(info, labels);
		else
			{
			bool isSwitch = tok.PeekKeyword("switch");
			LoopInfo labelInfo = null;
			if (labels != null || isSwitch)
				{
				labelInfo = gen.NewLabeledStmtInfo( curCGFuncInfo, tok.Prev().loc,
													labels, isSwitch );
				loops.Push(labelInfo);
				}
			
			StmtFrag stmt;
			if (tok.PeekOp("{"))
				stmt = ParseBlock(info);
			else if (tok.TryMatchKeyword("var"))
				{
				stmt = gen.NewStmtFrag(tok.Prev().loc);
				
				do
					{
					string varName;
					SrcLoc varLoc;
					stmt.Append(ParseVariableDeclaration( info, true, out varName,
														  out varLoc ));
					}
				while (tok.TryMatchOp(","));
				tok.MatchOp(";");
				}
			else if (tok.TryMatchOp(";"))
				{
				// EmptyStatement
				stmt = gen.NewStmtFrag(tok.Prev().loc);
				}
			else if (tok.TryMatchKeyword("if"))
				{
				SrcLoc ifLoc = tok.Prev().loc;
				
				tok.MatchOp("(");
				ExprFrag condition = ParseExpression(info, true);
				tok.MatchOp(")");
				
				StmtFrag ifClause = ParseStatement(info);
				StmtFrag elseClause = null;
				if (tok.TryMatchKeyword("else"))
					elseClause = ParseStatement(info);
				
				stmt = gen.IfThenElse(ifLoc, condition, ifClause, elseClause);
				}
			else if (tok.TryMatchKeyword("continue"))
				{
				SrcLoc continueLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (ContinueStatement) specifies
				// "no LineTerminator here".
				string id;
				tok.TryMatchID(out id);
				tok.MatchOp(";");
				
				stmt = gen.Continue(continueLoc, id, CloneStack(loops));
				}
			else if (tok.TryMatchKeyword("break"))
				{
				SrcLoc breakLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (BreakStatement) specifies
				// "no LineTerminator here".
				string id;
				tok.TryMatchID(out id);
				tok.MatchOp(";");
				
				stmt = gen.Break(breakLoc, id, CloneStack(loops));
				}
			else if (tok.TryMatchKeyword("return"))
				{
				SrcLoc returnLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (ReturnStatement) specifies
				// "no LineTerminator here".
				if (tok.TryMatchOp(";"))
					stmt = gen.Return(returnLoc, null);
				else
					{
					ExprFrag value = ParseExpression(info, true);
					tok.MatchOp(";");
					stmt = gen.Return(returnLoc, value);
					}
				
				}
			else if (tok.TryMatchKeyword("with"))
				{
				SrcLoc withLoc = tok.Prev().loc;
				
				tok.MatchOp("(");
				ExprFrag value = ParseExpression(info, true);
				tok.MatchOp(")");
				
				WithInfo withInfo = gen.NewWithInfo(curCGFuncInfo, withLoc);
				withs.Push(withInfo);
				
				StmtFrag body = ParseStatement(info);
				
				WithInfo temp = (WithInfo) withs.Pop();
				Trace.Assert(temp == withInfo);
				
				stmt = gen.With(withInfo, value, body);
				}
			else if (tok.TryMatchKeyword("switch"))
				{
				SrcLoc switchLoc = tok.Prev().loc;
				SwitchInfo switchInfo = gen.NewSwitchInfo();
				
				tok.MatchOp("(");
				ExprFrag switchValue = ParseExpression(info, true);
				tok.MatchOp(")");
				
				tok.MatchOp("{");
				while (!tok.TryMatchOp("}"))
					{
					ExprFrag caseValue;
					if (tok.TryMatchKeyword("default"))
						caseValue = null;
					else
						{
						tok.MatchKeyword("case");
						caseValue = ParseExpression(info, true);
						}
					
					StmtFrag clauseStmt = null;
					tok.MatchOp(":");
					while ( !tok.PeekOp("}") && !tok.PeekKeyword("case") &&
							!tok.PeekKeyword("default") )
						{
						StmtFrag tempStmt = ParseStatement(info);
						if (clauseStmt == null)
							clauseStmt = tempStmt;
						else
							clauseStmt.Append(tempStmt);
						}
					
					switchInfo.AddCase(caseValue, clauseStmt);
					}
				
				stmt = gen.Switch(switchLoc, switchValue, switchInfo);
				}
			else if (tok.TryMatchKeyword("throw"))
				{
				SrcLoc throwLoc = tok.Prev().loc;
				
				// HACK snewman 8/7/01: the grammar (ThrowStatement) specifies
				// "no LineTerminator here".
				ExprFrag value = ParseExpression(info, true);
				tok.MatchOp(";");
				
				stmt = gen.Throw(throwLoc, value);
				}
			else if (tok.TryMatchKeyword("try"))
				{
				SrcLoc tryLoc = tok.Prev().loc;
				StmtFrag tryBody = ParseBlock(info);
				String catchVar        = null;
				WithInfo catchWithInfo = null;
				StmtFrag catchBody     = null;
				StmtFrag finallyBody   = null;
				
				if (tok.TryMatchKeyword("catch"))
					{
					SrcLoc catchLoc = tok.Prev().loc;
					
					tok.MatchOp("(");
					catchVar = tok.MatchID();
					tok.MatchOp(")");
					
					catchWithInfo = gen.NewWithInfo(curCGFuncInfo, catchLoc);
					withs.Push(catchWithInfo);
					
					catchBody = ParseBlock(info);
					
					WithInfo temp = (WithInfo) withs.Pop();
					Trace.Assert(temp == catchWithInfo);
					}
				
				if (tok.TryMatchKeyword("finally"))
					finallyBody = ParseBlock(info);
				
				stmt = gen.TryCatchFinally( tryLoc, tryBody, catchVar,
											catchWithInfo, catchBody, finallyBody );
				}
			else
				{
				ExprFrag expr = ParseExpression(info, true);
				tok.MatchOp(";");
				stmt = gen.ExpressionStmt(expr);
				}
			
			if (labelInfo != null)
				{
				LoopInfo temp2 = (LoopInfo) loops.Pop();
				Trace.Assert(temp2 == labelInfo);
				
				stmt = gen.LabeledStmt(labelInfo, stmt);
				}
			
			return stmt;
			}
		
		} // ParseStatement
        private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets, int first, int last) {
            if (first == last) {
                EmitSwitchBucket(info, buckets[first]);
                return;
            }

            // Split the buckets into two groups, and use an if test to find
            // the right bucket. This ensures we'll only need O(lg(B)) tests
            // where B is the number of buckets
            int mid = (int)(((long)first + last + 1) / 2);

            if (first == mid - 1) {
                EmitSwitchBucket(info, buckets[first]);
            } else {
                // If the first half contains more than one, we need to emit an
                // explicit guard
                Label secondHalf = _ilg.DefineLabel();
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(buckets[mid - 1].Last().Constant);
                _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf);
                EmitSwitchBuckets(info, buckets, first, mid - 1);
                _ilg.MarkLabel(secondHalf);
            }

            EmitSwitchBuckets(info, buckets, mid, last);
        }
Esempio n. 31
0
        public void read(Reader reader)
        {
            foreach (ScriptSub sub in subs)
            {
                sub.scriptCode.Clear();
                sub.blankLines.Clear();
                sub.labels.Clear();
                sub.jumpTable.Clear();

                bool finishedScriptCode = false;

                int scriptCodeLength = reader.ReadByte() << 8;
                scriptCodeLength |= reader.ReadByte();

                sub.scriptCode.Clear();
                while (!finishedScriptCode)
                {
                    byte scriptOpcode = reader.ReadByte();
                    if (scriptOpcode == 0xFF)
                    {
                        scriptOpcode = reader.ReadByte();
                        if (scriptOpcode == 0xFF)
                        {
                            scriptOpcode = reader.ReadByte();
                            if (scriptOpcode == 0xFF)
                            {
                                scriptOpcode = reader.ReadByte();
                                if (scriptOpcode == 0xFF)
                                {
                                    finishedScriptCode = true;
                                }
                            }
                        }
                    }

                    if (!finishedScriptCode)
                    {
                        OpcodeInfo opInfo = new OpcodeInfo();

                        opInfo.opcode = scriptOpcode;

                        uint paramCount = (uint)opcodeList[scriptOpcode].paramCount;
                        opInfo.parameters.Clear();

                        for (int p = 0; p < paramCount; p++)
                        {
                            ParamInfo param = new ParamInfo();

                            int paramType = reader.ReadByte(); // if 0 then int constant, else variable

                            if (paramType != 0)
                            {
                                param.isVariable = true;

                                param.value = reader.ReadByte();

                                int arrayIndex = reader.ReadByte();
                                if (arrayIndex > 0x80)
                                {
                                    arrayIndex = 0x80 - arrayIndex;
                                }

                                param.arrayIndex = (sbyte)arrayIndex;
                            }
                            else
                            {
                                param.isVariable = false;
                                param.arrayIndex = -1;

                                int byte1    = reader.ReadByte();
                                int constVal = 0;
                                if (byte1 < 0x80) // unsigned uint16
                                {
                                    constVal  = byte1 << 8;
                                    constVal |= reader.ReadByte();
                                }
                                else // signed uint16
                                {
                                    constVal  = (byte1 - 0x80) << 8;
                                    constVal |= reader.ReadByte();
                                    constVal  = -constVal;
                                }

                                param.value = constVal;
                            }
                            opInfo.parameters.Add(param);
                        }

                        sub.scriptCode.Add(opInfo);
                    }
                }

                int blankLineUnused = reader.ReadByte();
                int blankLineCount  = reader.ReadByte();
                for (int u = 0; u < blankLineCount; u++)
                {
                    int blankLineID = reader.ReadByte() << 8;
                    blankLineID |= reader.ReadByte();
                    sub.blankLines.Add(blankLineID);
                }

                int labelUnused = reader.ReadByte();
                int labelCount  = reader.ReadByte();
                for (int l = 0; l < labelCount; l++)
                {
                    LabelInfo label = new LabelInfo();

                    label.scriptCodePos  = reader.ReadByte() << 8;
                    label.scriptCodePos |= reader.ReadByte();

                    label.id  = reader.ReadByte() << 8;
                    label.id |= reader.ReadByte();

                    label.lineID  = reader.ReadByte() << 8;
                    label.lineID |= reader.ReadByte();

                    sub.labels.Add(label);
                }

                int jumpTableUnused = reader.ReadByte();
                int jumpTableCount  = reader.ReadByte();
                for (int s = 0; s < jumpTableCount; ++s)
                {
                    SwitchInfo info = new SwitchInfo();

                    info.scriptCodePos  = reader.ReadByte() << 8;
                    info.scriptCodePos |= reader.ReadByte();

                    int caseCount = reader.ReadByte() << 8;
                    caseCount |= reader.ReadByte();

                    info.defaultScriptCodePos  = reader.ReadByte() << 8;
                    info.defaultScriptCodePos |= reader.ReadByte();

                    info.defaultCaseLineID  = reader.ReadByte() << 8;
                    info.defaultCaseLineID |= reader.ReadByte();

                    info.endScriptCodePos  = reader.ReadByte() << 8;
                    info.endScriptCodePos |= reader.ReadByte();

                    // if (info.defaultScriptCodePos == 0)
                    //     info.defaultScriptCodePos = info.endScriptCodePos;

                    int lowestCase  = 0x8000;
                    int highestCase = 0;
                    info.cases.Clear();
                    for (int c = 0; c < caseCount; c++)
                    {
                        SwitchCaseInfo caseInfo = new SwitchCaseInfo();

                        caseInfo.scriptCodePos  = reader.ReadByte() << 8;
                        caseInfo.scriptCodePos |= reader.ReadByte();

                        caseInfo.caseNum  = reader.ReadByte() << 8;
                        caseInfo.caseNum |= reader.ReadByte();

                        if (caseInfo.caseNum < lowestCase)
                        {
                            lowestCase = caseInfo.caseNum;
                        }

                        if (caseInfo.caseNum > highestCase)
                        {
                            highestCase = caseInfo.caseNum;
                        }

                        caseInfo.lineID  = reader.ReadByte() << 8;
                        caseInfo.lineID |= reader.ReadByte();

                        info.cases.Add(caseInfo);
                    }


                    info.lowestCase  = lowestCase;
                    info.highestCase = highestCase;

                    // Take any duds and make em default cases
                    // for (int m = lowestCase; m <= highestCase; ++m)
                    // {
                    //     int jump = sub.scriptCode[caseTablePos + m];
                    //     if (jump == 0)
                    //         sub.scriptCode[caseTablePos + m] = sub.jumpTable[startSwitchTablePos + 2];
                    // }

                    // wow this is weird
                    // it manually goes and sets up the offsets instead of doing it at compile-time like later RSDK versions
                    int pos = 0;
                    foreach (OpcodeInfo opcodeInfo in sub.scriptCode)
                    {
                        if (pos == info.scriptCodePos)
                        {
                            opcodeInfo.parameters[1].value = pos;
                            break;
                        }
                        pos += opcodeInfo.size;
                    }

                    sub.jumpTable.Add(info);
                }
            }

            reader.Close();
        }
Esempio n. 32
0
        // Tries to emit switch as a jmp table
        private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags)
        {
            // If we have a comparison, bail
            if (node.Comparison != null)
            {
                return(false);
            }

            // Make sure the switch value type and the right side type
            // are types we can optimize
            Type type = node.SwitchValue.Type;

            if (!CanOptimizeSwitchType(type) ||
                !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type))
            {
                return(false);
            }

            // Make sure all test values are constant, or we can't emit the
            // jump table.
            if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression)))
            {
                return(false);
            }

            //
            // We can emit the optimized switch, let's do it.
            //

            // Build target labels, collect keys.
            var labels = new Label[node.Cases.Count];
            var isGoto = new bool[node.Cases.Count];

            var uniqueKeys = new HashSet <decimal>();
            var keys       = new List <SwitchLabel>();

            for (int i = 0; i < node.Cases.Count; i++)
            {
                DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]);

                foreach (ConstantExpression test in node.Cases[i].TestValues)
                {
                    // Guaranteed to work thanks to CanOptimizeSwitchType.
                    //
                    // Use decimal because it can hold Int64 or UInt64 without
                    // precision loss or signed/unsigned conversions.
                    decimal key = ConvertSwitchValue(test.Value);

                    // Only add each key once. If it appears twice, it's
                    // allowed, but can't be reached.
                    if (uniqueKeys.Add(key))
                    {
                        keys.Add(new SwitchLabel(key, test.Value, labels[i]));
                    }
                }
            }

            // Sort the keys, and group them into buckets.
            keys.Sort((x, y) => Math.Sign(x.Key - y.Key));
            var buckets = new List <List <SwitchLabel> >();

            foreach (var key in keys)
            {
                AddToBuckets(buckets, key);
            }

            // Emit the switchValue
            LocalBuilder value = GetLocal(node.SwitchValue.Type);

            EmitExpression(node.SwitchValue);
            _ilg.Emit(OpCodes.Stloc, value);

            // Create end label, and default label if needed
            Label end      = _ilg.DefineLabel();
            Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel();

            // Emit the switch
            var info = new SwitchInfo(node, value, @default);

            EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1);

            // Emit the case bodies and default
            EmitSwitchCases(node, labels, isGoto, @default, end, flags);

            FreeLocal(value);
            return(true);
        }
        OutputSwitchInfo(
            SwitchInfo switchInfo)
        {
            Console.WriteLine("Successfully enumerated the ports and port features of the switch '{0}'\n",
                              switchInfo.Name);
            Console.WriteLine("The switch's connection type is:");
            Console.WriteLine("    {0}\n", switchInfo.Type);

            //
            // If the switch is connected to an external network, output the name of the network.
            //
            if (switchInfo.Type == SwitchConnectionType.External ||
                switchInfo.Type == SwitchConnectionType.ExternalOnly)
            {
                Console.WriteLine("The switch is connected to the following network:");
                foreach (PortInfo portInfo in switchInfo.PortList)
                {
                    if (portInfo.Type == PortConnectionType.External)
                    {
                        Console.WriteLine("    {0}", portInfo.ConnectedName);
                    }
                }
                Console.WriteLine();
            }

            //
            // Output the virtual machines that are currently connected to this switch.
            //
            Console.WriteLine("The switch is connected to the following virtual machines:");

            bool atLeastOneVirtualMachine = false;

            foreach (string virtualMachineName in GetConnectedVirtualMachineList(switchInfo.PortList))
            {
                atLeastOneVirtualMachine = true;
                Console.WriteLine("    {0}", virtualMachineName);
            }

            if (!atLeastOneVirtualMachine)
            {
                Console.WriteLine("    The switch is not connected to any virtual machines");
            }

            Console.WriteLine();

            //
            // Output the advanced features that have been configured for the switch.
            //
            Console.WriteLine("The switch has the following advanced features: ");

            if (switchInfo.SwitchFeatureList.Count > 0)
            {
                foreach (NetworkingUtilities.SwitchFeatureType featureType in switchInfo.SwitchFeatureList)
                {
                    Console.WriteLine("    {0}", featureType.ToString());
                }
            }
            else
            {
                Console.WriteLine("    The switch has no advanced features");
            }

            Console.WriteLine();

            //
            // Now output information about features for each port.
            //
            Console.WriteLine("The switch is connected to {0} ports.", switchInfo.PortList.Count);

            if (switchInfo.PortList.Count > 0)
            {
                Console.WriteLine("Outputting port features for each port:\n");

                int count = 1;
                foreach (PortInfo portInfo in switchInfo.PortList)
                {
                    switch (portInfo.Type)
                    {
                    case PortConnectionType.VirtualMachine:
                        Console.WriteLine("    Port {0} connected to virtual machine '{1}' has the following features:",
                                          count, portInfo.ConnectedName);
                        break;

                    case PortConnectionType.External:
                        Console.WriteLine("    Port {0} connected to the external network '{1}' has the following features:",
                                          count, portInfo.ConnectedName);
                        break;

                    case PortConnectionType.Internal:
                        Console.WriteLine("    Port {0} connected to the internal network has the following features:",
                                          count);
                        break;

                    case PortConnectionType.Nothing:
                        Console.WriteLine("    Port {0} not connected to anything has the following features:",
                                          count);
                        break;
                    }

                    if (portInfo.FeatureList.Count > 0)
                    {
                        foreach (NetworkingUtilities.PortFeatureType featureType in portInfo.FeatureList)
                        {
                            Console.WriteLine("       {0}", featureType.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("       The port has no advanced features");
                    }

                    count++;
                    Console.WriteLine();
                }
            }
        }
Esempio n. 34
0
        private void EmitSwitchBucket(SwitchInfo info, List <SwitchLabel> bucket)
        {
            // No need for switch if we only have one value
            if (bucket.Count == 1)
            {
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(bucket[0].Constant);
                _ilg.Emit(OpCodes.Beq, bucket[0].Label);
                return;
            }

            //
            // If we're switching off of Int64/UInt64, we need more guards here
            // because we'll have to narrow the switch value to an Int32, and
            // we can't do that unless the value is in the right range.
            //
            Label?after = null;

            if (info.Is64BitSwitch)
            {
                after = _ilg.DefineLabel();
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(bucket.Last().Constant);
                _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value);
                _ilg.Emit(OpCodes.Ldloc, info.Value);
                _ilg.EmitConstant(bucket[0].Constant);
                _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value);
            }

            _ilg.Emit(OpCodes.Ldloc, info.Value);

            // Normalize key
            decimal key = bucket[0].Key;

            if (key != 0)
            {
                _ilg.EmitConstant(bucket[0].Constant);
                _ilg.Emit(OpCodes.Sub);
            }

            if (info.Is64BitSwitch)
            {
                _ilg.Emit(OpCodes.Conv_I4);
            }

            // Collect labels
            int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1);

            Label[] jmpLabels = new Label[len];

            // Initialize all labels to the default
            int slot = 0;

            foreach (SwitchLabel label in bucket)
            {
                while (key++ != label.Key)
                {
                    jmpLabels[slot++] = info.Default;
                }
                jmpLabels[slot++] = label.Label;
            }

            // check we used all keys and filled all slots
            Debug.Assert(key == bucket[bucket.Count - 1].Key + 1);
            Debug.Assert(slot == jmpLabels.Length);

            // Finally, emit the switch instruction
            _ilg.Emit(OpCodes.Switch, jmpLabels);

            if (info.Is64BitSwitch)
            {
                _ilg.MarkLabel(after.Value);
            }
        }
Esempio n. 35
0
 // CreateSwitch()
 public void CreateSwitch(SwitchInfo NewSwitch)
 {
     _switchInfo.CreateSwitch(NewSwitch);
 }