public static void Run() { var conf = new XMLConfiguration(); conf.Create(); conf.Root.Name = "This-is-Root"; var child1 = conf.Root.AddChildNode("Child_Node_1"); child1.AddChildNode("Grand-Child-1", "this is my value"); child1.AddAttributeNode("AttrWithoutValue"); child1.AddAttributeNode("Important", true); child1.AddAttributeNode("Age", 88); child1.AddAttributeNode("DateOf-Enlightement", App.LocalizedTime); child1.AddAttributeNode("HowFakeFakeAreYou", FakeType.TotalFraud); conf.Root.AddChildNode("Child2").AddChildNode("A").AddChildNode("B").AddChildNode("C"); conf.Root["Child2"]["A"]["B"]["C"].Value = "175"; Console.WriteLine(conf.Root["Child2"]["A"]["B"]["C"].ValueAsInt()); Console.WriteLine(conf.SaveToString(null)); conf.SaveAs("c:\\TEST.xml"); conf = new XMLConfiguration("c:\\TEST.xml"); Console.WriteLine(conf.Root["Child2"]["A"]["B"]["C"].ValueAsInt()); Console.WriteLine(conf.Root["Child_Node_1"].AttrByName("HowFakeFakeAreYou").ValueAsEnum <FakeType>(FakeType.RealStuff)); Console.ReadLine(); }
/// <summary> /// 默认虚拟机构造函数 /// </summary> /// <param name="workItem">系统组件容器</param> public DefaultVirtualCTI(WorkItem workItem) { this.workItem = workItem; this.workItem.Services.Add <IVirtualCTI>(this); logger = workItem.Services.Get <ILog>(); IConfigurationService configService = workItem.Services.Get <IConfigurationService>(); if (!configService.Exists(sectionPath)) { String errStr = "在系统配置文件中文件未找到 \"LightweightCTI\" 配置节。"; logger.Fatal(errStr); throw new Exception(errStr); } // 创建相关文件夹 if (!Directory.Exists(resourceDir)) { Directory.CreateDirectory(resourceDir); } if (!Directory.Exists(projectsDir)) { Directory.CreateDirectory(projectsDir); } IConfiguration config = new XMLConfiguration(configService.GetItem(sectionPath)); ConfigurationInterpreter confInterpreter = new ConfigurationInterpreter(workItem, config); confInterpreter.Parse(); // 解析配置信息并反序列化相关组件 }
public void TestSupplierConfigurationControllerUpdateModelIdLessThanZeroOrZeroReturnsBadResultObjectFail() { XMLConfiguration xmlConfiguration = new XMLConfiguration { AdvanceBookingDays = 2, CurrencyId = 1, IsCitySupported = true, MaxChildAge = 18, MaxHotelCodesInSearch = 1, MaxInfantge = 2, SupplierId = 2, MinChildAge = 3, MinInfantAge = 1, IsDeleted = false }; xmlConfigurationMasterMock.Setup(x => x.UpdateEntity(xmlConfiguration)).Returns(Task.FromResult(new BaseResult <bool>() { Result = true, IsError = false })); var result = supplierConfigurationControllerMock.Update(xmlConfiguration).Result; Assert.That(result is BadRequestObjectResult); }
public AddEditServoDevice(XMLConfiguration configuration, int servoDeviceIndex, RS232Configuration interf) { InitializeComponent(); _configuration = configuration; _servoDeviceIndex = servoDeviceIndex; _interf = interf; if (servoDeviceIndex < 0) { // dodanie nowego Text = "Dodaj nowe serwomechanizmy"; NumericUpDown2ValueChanged(null, null); } else { // edycja istniejącego Text = "Edycja serwomechanizmów"; ServoDevice servod = (ServoDevice)configuration.ServoDevices[servoDeviceIndex]; textBox2.Text = servod.Description; for (int j = 0; j < servod.Servos.Length; j++) { dataGridView1.Rows.Add((j + 1).ToString(), servod.Servos[j].Id, servod.Servos[j].Description); } if (dataGridView1.Rows.Count < numericUpDown2.Value) { NumericUpDown2ValueChanged(null, null); } numericUpDown2.Value = dataGridView1.Rows.Count; _loading = true; numericUpDown1.Value = servod.DeviceId; _loading = false; } }
public void FileDestinationFilenameConfigTest() { DateTime now = App.LocalizedTime; var TNAME = "TestDest-" + MethodBase.GetCurrentMethod().Name; var FNAME = "{0:yyyyMMdd}-{1}.log".Args(now, TNAME); var fname = Path.Combine(TEST_DIR, FNAME); IOMiscUtils.EnsureFileEventuallyDeleted(fname); var xml = @"<log> <destination type='NFX.Log.Destinations.DebugDestination, NFX' name='{0}' path='{1}' filename='{2}'/> </log>".Args(TNAME, TEST_DIR, FNAME); using (var svc = new TSLS()) using (Scope.OnExit(() => File.Delete(fname))) { svc.Configure(XMLConfiguration.CreateFromXML(xml).Root); svc.Start(); Aver.IsTrue(File.Exists(fname)); svc.WaitForCompleteStop(); } }
public void FileDestinationFilenameConfigTest() { DateTime now = App.LocalizedTime; string TNAME = "TestDest-" + MethodBase.GetCurrentMethod().Name; string FNAME = Path.Combine(TEST_DIR, "{0:yyyyMMdd}-{1}.log".Args(now, TNAME)); File.Delete(FNAME); var xml = @"<log> <destination type='NFX.Log.Destinations.DebugDestination, NFX' name='{0}' path='{1}'/> </log>".Args(TNAME, TEST_DIR); //var log = new TestMemoryLog(); //using (var app = new TestApplication { Log = log }) using (var svc = new TSLS()) using (Scope.OnExit(() => File.Delete(FNAME))) { svc.Configure(XMLConfiguration.CreateFromXML(xml).Root); svc.Start(); Assert.IsTrue(File.Exists(FNAME)); svc.WaitForCompleteStop(); } }
public MainWindow() { InitializeComponent(); SystemSingleton.Configuration.mainWindow = this; SystemSingleton.Configuration.tabControl = TabControl; SystemSingleton.Configuration.SqlConnections = new List <SqlConnection>(); App.LanguageChanged += LanguageChanged; CultureInfo currLang = App.Language; menuLanguage.Items.Clear(); foreach (var lang in App.Languages) { MenuItem menuLang = new MenuItem(); menuLang.Header = lang.DisplayName; menuLang.Tag = lang; menuLang.IsChecked = lang.Equals(currLang); menuLang.Click += ChangeLanguageClick; menuLanguage.Items.Add(menuLang); } if (!XMLConfiguration.Load("settings.xml")) { SendAttentionToBottomBar("m_tab_LogIn_BrokenSettingsFile"); EnvironmentHelper.SendLog("Broken Settings File"); TabControl.IsEnabled = false; return; } worker.DoWork += worker_CheckConnection; WorkingTab.Visibility = Visibility.Collapsed; SendInfoToBottomBar("m_tab_LogIn_CheckConnection"); TabControl.IsEnabled = false; worker.RunWorkerAsync(); TabControl.SelectionChanged += Handlers.TabControl_SelectionChanged; }
public override void Report(System.IO.TextWriter writer) { var conf = new XMLConfiguration(); conf.StrictNames = false; conf.Create(); conf.Root.Name = "health-check-list"; conf.Root.AddAttributeNode("successful", CheckList.Successful); var runNode = conf.Root.AddChildNode("run", null); if (CheckList.Status == CheckListStatus.Run) { runNode.AddAttributeNode("started", CheckList.RunStart); runNode.AddAttributeNode("finished", CheckList.RunFinish); runNode.AddAttributeNode("duration", CheckList.RunFinish - CheckList.RunStart); } else { runNode.AddAttributeNode("started", "never ran"); } var checksNode = conf.Root.AddChildNode("checks", null); foreach (var check in CheckList.Checks) { reportCheck(checksNode, check); } writer.Write(conf.ToString()); }
/// <summary> Inicializa uma nova instância da classe <see cref="OptionsMenu"/>. </summary> public OptionsMenu() { InitializeComponent(); _settings = Configuration.Settings; cboColors.SelectedItem = ThemeManager.GetAccent(_settings.Application.Property[3].Value); txtApplicationTitle.Text = _settings.Application.Property[0].Value; }
private void InterfaceConfiguration() { XMLConfiguration settings = Configuration.Settings; Title = settings.Application.Property[0].Value; ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent(settings.Application.Property[3].Value), ThemeManager.GetAppTheme("Base" + settings.Application.Property[2].Value)); }
public void XMLConfiguration_ctorTest() { Assert.AreEqual(true, configService.Exists("System/Services/SessionService")); XMLConfiguration config = new XMLConfiguration(configService.GetItem("System/Services/SessionService")); Console.WriteLine(config.ToString()); Assert.IsNotNull(config); }
/// <summary> /// Evaluates variables in a context of optional configuration supplied in XML format /// </summary> public static string EvaluateVarsInXMLConfigScope(this string line, string xmlScope = null, IEnvironmentVariableResolver envResolver = null, IMacroRunner macroRunner = null) { Configuration config = null; if (!string.IsNullOrWhiteSpace(xmlScope)) { config = XMLConfiguration.CreateFromXML(xmlScope); config.EnvironmentVarResolver = envResolver; config.MacroRunner = macroRunner; } return(line.EvaluateVarsInConfigScope(config)); }
public void CSVFileDestinationStartByConfig1() { string TNAME = "UnitTest-" + MethodBase.GetCurrentMethod().Name; string FNAME = TNAME + ".csv.log"; const string DATE = "20131012"; var xml = @"<log> <destination type='NFX.Log.Destinations.CSVFileDestination, NFX' name='{0}' filename='$(@~path)$(::now fmt=yyyyMMdd value={1})-$($name).csv.log' create-dir='true' /> </log>".Args(TNAME, DATE); var svc = new LSVC(null); var fname = Path.Combine(TEST_DIR, DATE + "-" + FNAME); if (File.Exists(fname)) { File.Delete(fname); } using (Scope.OnExit(() => File.Delete(fname))) { var cfg = XMLConfiguration.CreateFromXML(xml); cfg.EnvironmentVarResolver = new Vars { { "path", TEST_DIR } }; svc.Configure(cfg.Root); svc.Start(); svc.Write(new Message { Text = "1 message" }); svc.Write(new Message { Text = "2 message" }); svc.Write(new Message { Text = "3 message" }); svc.WaitForCompleteStop(); Assert.IsTrue(File.Exists(fname)); Assert.AreEqual(3, File.ReadAllLines(fname).Length); } }
public static void Main(string[] args) { string quoteMe = "Hallo IAIK!"; byte[] quoteMeBytes = System.Text.Encoding.ASCII.GetBytes(quoteMe); // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); ClientKeyHandle myFirstSignKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_sign_key", TPMKeyUsage.TPM_KEY_SIGNING); ISigner signer = myFirstSignKey.CreateSigner(); signer.Init(true, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); byte[] quote = signer.GenerateSignature(); Console.WriteLine("Sign of \"Hallo IAIK\" is:\n" + ByteHelper.ByteArrayToHexString(quote)); Console.WriteLine(); Console.WriteLine("Now we would verify this sign."); signer.Reset(); signer.Init(false, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); if (signer.VerifySignature(quote) == true) { Console.WriteLine("Sign is OK!"); } else { Console.WriteLine("UUUUPPPPSSS something went wrong!"); } }
public static void Main(string[] args) { // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); Console.WriteLine("Creating key 'my_first_storage_key'"); ClientKeyHandle myFirstStorageKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_storage_key", TPMKeyUsage.TPM_KEY_STORAGE); Console.WriteLine("Created key 'my_first_storage_key' with public key: {0}", myFirstStorageKey.PublicKey.PublicKey); Console.WriteLine("------------------------\n\n"); Console.WriteLine("Creating key 'my_second_storage_key'"); ClientKeyHandle mySecondStorageKey = myFirstStorageKey.CreateKey("my_second_storage_key", TPMKeyUsage.TPM_KEY_STORAGE); Console.WriteLine("Created key 'my_second_storage_key' with public key: {0}", mySecondStorageKey.PublicKey.PublicKey); Console.WriteLine("------------------------\n\n"); Console.WriteLine("Creating key 'binding_key'"); ClientKeyHandle bindingKey = mySecondStorageKey.CreateKey("binding_key", TPMKeyUsage.TPM_KEY_BIND); Console.WriteLine("Created key 'binding_key' with public key: {0}", bindingKey.PublicKey.PublicKey); Console.WriteLine("------------------------\n\n"); Console.WriteLine("Keystore now contains {0} keys", sessionToUse.Keystore.EnumerateFriendlyNames().Length); foreach (String keyFriendlyName in sessionToUse.Keystore.EnumerateFriendlyNames()) { KeyValuePair <string, string>?parent = sessionToUse.Keystore.FindParentKeyByFriendlyName(keyFriendlyName); Console.WriteLine("Key: '{0}' with parent '{1}'", keyFriendlyName, parent == null?"srk":parent.Value.Key); } }
public MainWindow() { InitializeComponent(); SystemSingleton.Configuration.ConsoleBox = ConsoleBox; SystemSingleton.Configuration.Window = this; SystemSingleton.Configuration.SqlConnections = new List <SqlConnection>(); SystemSingleton.Configuration.Waiters = new Dictionary <long, Waiter>(); if (!XMLConfiguration.Load("settings.xml")) { EnvironmentHelper.SendFatalLog("Broken Settings File"); } App.Language = new CultureInfo(SystemSingleton.Configuration.Language); SystemSingleton.WaitersWorker.LoadWaiters(); workerConnectionToBase.DoWork += WorkerConnectionToBaseOnDoWork; workerConnectionToBase.RunWorkerAsync(); workerBot.DoWork += WorkerBotOnDoWork; }
public void CSVFileDestinationStartByConfig2() { string TNAME = "UnitTest-" + MethodBase.GetCurrentMethod().Name; string FNAME = TNAME + ".csv.log"; var xml = @"<log> <destination type='NFX.Log.Destinations.CSVFileDestination, NFX' name='{0}' path='{1}' create-dir='true' name-time-format='' /> </log>".Args(TNAME, TEST_DIR); var svc = new LSVC(null); var fname = Path.Combine(TEST_DIR, FNAME); if (File.Exists(fname)) { File.Delete(fname); } using (Scope.OnExit(() => File.Delete(fname))) { svc.Configure(XMLConfiguration.CreateFromXML(xml).Root); svc.Start(); svc.Start(); svc.Write(new Message { Text = "1 message" }); svc.Write(new Message { Text = "2 message" }); svc.Write(new Message { Text = "3 message" }); svc.WaitForCompleteStop(); Assert.AreEqual(true, File.Exists(fname)); Assert.AreEqual(3, File.ReadAllLines(fname).Length); } }
public static ConfigSectionNode AsXMLConfig(this object val, ConfigSectionNode dflt = null, ConvertErrorHandling handling = ConvertErrorHandling.ReturnDefault) { try { if (val == null) { return(dflt); } var content = val.ToString(); return(XMLConfiguration.CreateFromXML(content).Root); } catch { if (handling != ConvertErrorHandling.ReturnDefault) { throw; } return(dflt); } }
public override void Uninitialize() { if (Motor1 != null) { Motor1.Uninitialize(); } if (Motor2 != null) { Motor2.Uninitialize(); } // RESET Interface.Write(new byte[] { DeviceId, 1, RESET }); // zapisanie stanu if (NeedToSaveState) { XMLConfiguration.Load().Save(); } }
public AddEditStepperDevice(XMLConfiguration configuration, StepperDevice stepperDevice, RS232Configuration interf) { _configuration = configuration; StepperDevice = stepperDevice; _interf = interf; // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); if (StepperDevice == null) { Text = "Dodaj silniki krokowe"; NumericUpDown1ValueChanged(this, EventArgs.Empty); } else { Text = "Edytuj silniki krokowe"; textBox2.Text = StepperDevice.Description; numericUpDown1.Value = StepperDevice.DeviceId; textBox1.Text = StepperDevice.Motor1.Id; textBox3.Text = StepperDevice.Motor1.Description; numericUpDown2.Value = StepperDevice.Motor1.StepsFor360; numericUpDown3.Value = StepperDevice.Motor1.MinStepInterval; checkBox1.Checked = StepperDevice.Motor1.HasZeroSensor; checkBox2.Checked = StepperDevice.Motor1.InvertZeroSensor; checkBox3.Checked = StepperDevice.Motor1.ReverseDirection; textBox5.Text = StepperDevice.Motor2.Id; textBox4.Text = StepperDevice.Motor2.Description; numericUpDown5.Value = StepperDevice.Motor2.StepsFor360; numericUpDown4.Value = StepperDevice.Motor2.MinStepInterval; checkBox6.Checked = StepperDevice.Motor2.HasZeroSensor; checkBox5.Checked = StepperDevice.Motor2.InvertZeroSensor; checkBox4.Checked = StepperDevice.Motor2.ReverseDirection; } }
public static void Main(string[] args) { // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session //foreach (TPMSession tpmSes in sessions.Values) // tpmSes.Keystore = new InMemoryKeystore(); TPMSession sessionToUse = sessions["local0"]; // sessionToUse.SetRequestSecretCallback(RequestSecret); ProtectedPasswordStorage pws = new ProtectedPasswordStorage(); pws.WellKnown(); sessionToUse.AdministrationClient.TakeOwnership(ConsoleUtils.ReadPassword("Owner Password: "******"PCRS = " + sessionToUse.CapabilityClient.GetPCRCount()); }
public void CSVFileDestinationStartByConfig2() { var TNAME = "UnitTest-" + MethodBase.GetCurrentMethod().Name; var FNAME = TNAME + ".csv.log"; var xml = @"<log> <destination type='NFX.Log.Destinations.CSVFileDestination, NFX' name='{0}' path='{1}' file-name='$($name).csv.log' /> </log>".Args(TNAME, TEST_DIR); var fname = Path.Combine(TEST_DIR, FNAME); IOMiscUtils.EnsureFileEventuallyDeleted(fname); using (var svc = new LSVC()) using (Scope.OnExit(() => File.Delete(fname))) { svc.Configure(XMLConfiguration.CreateFromXML(xml).Root); svc.Start(); svc.Write(new Message { Text = "1 message" }); svc.Write(new Message { Text = "2 message" }); svc.Write(new Message { Text = "3 message" }); svc.WaitForCompleteStop(); Aver.IsTrue(File.Exists(fname)); Aver.AreEqual(3, File.ReadAllLines(fname).Length); } }
private static void run(string[] args) { var config = new CommandArgsConfiguration(args); if (config.Root["?"].Exists || config.Root["h"].Exists || config.Root["help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Help.txt")); return; } if (!config.Root.AttrByIndex(0).Exists) { Console.WriteLine("Specify ';'-delimited assembly list"); return; } var manager = new InventorizationManager(config.Root.AttrByIndex(0).Value); var fnode = config.Root["f"]; if (!fnode.Exists) { fnode = config.Root["filter"]; } if (fnode.Exists) { ConfigAttribute.Apply(manager, fnode); } foreach (var n in config.Root.Children.Where(chi => chi.IsSameName("s") || chi.IsSameName("strat") || chi.IsSameName("strategy"))) { var tname = n.AttrByIndex(0).Value ?? "<unspecified>"; Type t = Type.GetType(tname); if (t == null) { throw new NFXException("Can not create strategy type: " + tname); } var strategy = Activator.CreateInstance(t) as IInventorization; if (strategy == null) { throw new NFXException("The supplied type is not strategy: " + tname); } manager.Strategies.Add(strategy); } if (manager.Strategies.Count == 0) { manager.Strategies.Add(new BasicInventorization()); } // if (config.Root["any"].Exists) // manager.OnlyAttributed = false; var result = new XMLConfiguration(); result.Create("inventory"); manager.Run(result.Root); Console.WriteLine(result.SaveToString()); }
protected override void DoCompileTemplateSource(CompileUnit unit) { var text = unit.TemplateSource.GetSourceContent().ToString().Trim(); var icname = unit.TemplateSource.InferClassName(); Configuration conf = new MemoryConfiguration(); var confLineCount = 0; if (text.StartsWith(CONFIG_START)) { var i = text.IndexOf(CONFIG_END); if (i < CONFIG_START.Length) { throw new TemplateParseException(StringConsts.TEMPLATE_CS_COMPILER_CONFIG_CLOSE_TAG_ERROR); } var confText = text.Substring(CONFIG_START.Length, i - CONFIG_START.Length); confLineCount = confText.Count(c => c == '\n'); //cut configuration out of template text = text.Substring(i + CONFIG_END.Length); try { conf = XMLConfiguration.CreateFromXML("<config>" + confText + "</config>"); } catch (Exception error) { throw new TemplateParseException(StringConsts.TEMPLATE_CS_COMPILER_CONFIG_ERROR + error.Message, error); } } else //20140103 DKh add Laconic support if (text.StartsWith(LACONFIG_START)) { var i = text.IndexOf(LACONFIG_END); if (i < LACONFIG_START.Length) { throw new TemplateParseException(StringConsts.TEMPLATE_CS_COMPILER_CONFIG_CLOSE_TAG_ERROR); } var confText = text.Substring(LACONFIG_START.Length, i - LACONFIG_START.Length); confLineCount = confText.Count(c => c == '\n'); //cut configuration out of template text = text.Substring(i + LACONFIG_END.Length); try { conf = LaconicConfiguration.CreateFromString("config{" + confText + "}"); } catch (Exception error) { throw new TemplateParseException(StringConsts.TEMPLATE_CS_COMPILER_CONFIG_ERROR + error.Message, error); } } var compilerNode = conf.Root[CONFIG_COMPILER_SECTION]; //add referenced assemblies foreach (var anode in compilerNode.Children.Where(cn => cn.IsSameName(CONFIG_REF_ASSEMBLY_SECTION))) { this.ReferenceAssembly(anode.AttrByName(CONFIG_REF_ASSEMBLY_NAME_ATTR).Value); } //add usings var usings = new HashSet <string>(); RegisterDefaultUsings(usings); foreach (var unode in compilerNode.Children.Where(cn => cn.IsSameName(CONFIG_USING_SECTION))) { usings.Add(unode.AttrByName(CONFIG_USING_NS_ATTR).Value); } //add attributes var attributes = new List <string>(); foreach (var anode in compilerNode.Children.Where(cn => cn.IsSameName(CONFIG_ATTRIBUTE_SECTION))) { attributes.Add(anode.AttrByName(CONFIG_ATTRIBUTE_DECL_ATTR).Value); } unit.CompiledSource = new FSM() { Compiler = this, Unit = unit, InferredClassName = icname, ConfigNode = conf.Root, Source = text, Usings = usings, Attributes = attributes, LineNo = confLineCount + 1 }.Build().ToString(); }
public static void Main(string[] args) { string quoteMe = "Hallo IAIK!"; byte[] quoteMeBytes = System.Text.Encoding.ASCII.GetBytes(quoteMe); // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); ClientKeyHandle myFirstQuoteKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_quote_key", TPMKeyUsage.TPM_KEY_SIGNING); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); TPMPCRSelection pcrselect = sessionToUse.CreateEmptyPCRSelection(); pcrselect.PcrSelection[0] = true; pcrselect.PcrSelection[1] = true; pcrselect.PcrSelection[2] = true; ISigner signer = myFirstQuoteKey.CreateQuoter(pcrselect); signer.Init(true, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); byte[] quote = signer.GenerateSignature(); Console.WriteLine("Quote of \"Hallo IAIK\" is:\n" + ByteHelper.ByteArrayToHexString(quote)); Console.WriteLine(); Console.WriteLine("Now we would verify this quote."); signer.Reset(); signer.Init(false, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); if (signer.VerifySignature(quote) == true) { Console.WriteLine("Quote is OK!"); } else { Console.WriteLine("UUUUPPPPSSS something went wrong!"); } Console.WriteLine("Extending PCRs, Quote should fail now!"); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); if (signer.VerifySignature(quote) == true) { Console.WriteLine("UUUUPPPPSSS something went wrong!"); } else { Console.WriteLine("Quote is NOT OK, that's the way it should be."); } }
public void LogLevelsTest() { DateTime now = App.LocalizedTime; DateTime time = new DateTime(now.Year, now.Month, now.Day, 3, 4, 5); string TNAME = "TestDest-" + MethodBase.GetCurrentMethod().Name; string FNAME = Path.Combine(TEST_DIR, "{0:yyyyMMdd}-{1}.log".Args(now, TNAME)); File.Delete(FNAME); var xml = @"<log> <destination type='NFX.Log.Destinations.DebugDestination, NFX' name='{0}' path='{1}' levels='DebugB-DebugC,InfoB-InfoD,Warning,Emergency'/> </log>".Args(TNAME, TEST_DIR); //var log = new TestMemoryLog(); //using (var app = new TestApplication { Log = log }) using (var svc = new TSLS()) using (Scope.OnExit(() => File.Delete(FNAME))) { svc.Configure(XMLConfiguration.CreateFromXML(xml).Root); svc.Start(); Assert.IsTrue(File.Exists(FNAME)); Array mts = Enum.GetValues(typeof(MessageType)); foreach (var mt in mts) { svc.Write(new Message { Type = (MessageType)mt, Text = ((int)mt).ToString(), TimeStamp = now }); } svc.WaitForCompleteStop(); string[] lines = File.ReadAllLines(FNAME); Assert.AreEqual(7, lines.Length); lines.Select((s, i) => { var sa = s.Split('|'); MessageType mt; Assert.IsTrue(Enum.TryParse(sa[3], out mt)); Assert.AreEqual( "{0:yyyyMMdd}-030405.000000| {1}||Debug|{2}||0|".Args(now, Thread.CurrentThread.ManagedThreadId, (int)mt), s); return(0); }); } Assert.AreEqual( new Destination.LevelsList { new Tuple <MessageType, MessageType>(MessageType.DebugA, MessageType.DebugZ) }, Destination.ParseLevels("DebugA-DebugZ")); Assert.AreEqual( new Destination.LevelsList { new Tuple <MessageType, MessageType>(MessageType.Debug, MessageType.Info) }, Destination.ParseLevels("-Info")); Assert.AreEqual( new Destination.LevelsList { new Tuple <MessageType, MessageType>(MessageType.Info, MessageType.CatastrophicError) }, Destination.ParseLevels("Info-")); Assert.AreEqual( new Destination.LevelsList { new Tuple <MessageType, MessageType>(MessageType.Trace, MessageType.TraceZ), new Tuple <MessageType, MessageType>(MessageType.Info, MessageType.CatastrophicError) }, Destination.ParseLevels("Trace - TraceZ, Info-")); Assert.AreEqual( new Destination.LevelsList { new Tuple <MessageType, MessageType>(MessageType.Trace, MessageType.Trace), new Tuple <MessageType, MessageType>(MessageType.Info, MessageType.Info), new Tuple <MessageType, MessageType>(MessageType.Warning, MessageType.Warning) }, Destination.ParseLevels("Trace | Info | Warning")); Assert.AreEqual( new Destination.LevelsList { new Tuple <MessageType, MessageType>(MessageType.Trace, MessageType.Trace), new Tuple <MessageType, MessageType>(MessageType.Info, MessageType.Info) }, Destination.ParseLevels("Trace; Info")); }
private static void TestXmlConfig(string filename) { IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(filename); }
public static void Main(string[] args) { string[] sealMe = { "Hallo", "IAIK!" }; // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); Console.WriteLine("Create Cipher Key"); ClientKeyHandle myFirstSealKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_seal_key", TPMKeyUsage.TPM_KEY_STORAGE); Console.WriteLine("Key: {0}\n{1}", myFirstSealKey.FriendlyName, myFirstSealKey.PublicKey); Console.WriteLine("---------------------------------\n"); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); TPMPCRSelection pcrselect = sessionToUse.CreateEmptyPCRSelection(); pcrselect.PcrSelection[0] = true; pcrselect.PcrSelection[1] = true; pcrselect.PcrSelection[2] = true; Console.WriteLine("Create Cipher, init and cipher"); IAsymmetricBlockCipher cipher = myFirstSealKey.CreateSealBlockCipher(pcrselect); cipher.Init(true, null); byte[][] cipherText = new byte[sealMe.Length][]; int i = 0; foreach (string msg in sealMe) { byte[] block = System.Text.ASCIIEncoding.ASCII.GetBytes(msg); cipherText[i] = cipher.ProcessBlock(block, 0, block.Length); i++; } Console.WriteLine("Original vs. CiperText:"); for (i = 0; i < sealMe.Length; i++) { Console.WriteLine("{0} --> {1}", sealMe[i], ByteHelper.ByteArrayToHexString(cipherText[i])); } Console.WriteLine("---------------------------------\n"); Console.WriteLine("Init and decode"); cipher.Init(false, null); byte[][] decode = new byte[sealMe.Length][]; i = 0; foreach (byte[] msg in cipherText) { decode[i] = cipher.ProcessBlock(msg, 0, msg.Length); i++; } Console.WriteLine("Does it work?:"); for (i = 0; i < sealMe.Length; i++) { Console.WriteLine("{0}: {1}", sealMe[i] == System.Text.ASCIIEncoding.ASCII.GetString(decode[i])?"Y":"N", System.Text.ASCIIEncoding.ASCII.GetString(decode[i])); } Console.WriteLine("---------------------------------\n"); Console.WriteLine("Changing PCR Values"); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); Console.WriteLine("Decode, now an TPMRequest Exception should be thrown, with Error Code (0x18): TPM_WRONGPCRVAL"); decode = new byte[sealMe.Length][]; i = 0; foreach (byte[] msg in cipherText) { try { decode[i] = cipher.ProcessBlock(msg, 0, msg.Length); Console.WriteLine("UUUUUPPPPSSSS, something went wrong!"); } catch (TPMRequestException e) { Console.WriteLine(e.ToString()); } i++; } }
/// <summary> /// 从插件描述文件加载插件 /// </summary> /// <param name="filename"></param> private void Load(string filename) { string addInfile = filename; if (!File.Exists(addInfile)) { List <string> files = FileUtility.SearchDirectory(Directory.GetParent(Environment.CurrentDirectory) + AddinsPath, addInfile); if (files.Count > 0) { addInfile = files[0]; addInFileName = addInfile; } else { return; } } XMLConfigurationService configService = new XMLConfigurationService(addInfile); logger.Info(String.Format("开始解析插件描述文件 \"{0}\":", Path.GetFileName(addInfile))); IConfiguration configuration = null; // 解析插件描述文件信息 configuration = new XMLConfiguration(configService.GetItem("")); if (configuration != null) { if (configuration.Attributes["name"] != null) { name = configuration.Attributes["name"]; } if (configuration.Attributes["author"] != null) { author = configuration.Attributes["author"]; } if (configuration.Attributes["copyright"] != null) { copyright = configuration.Attributes["copyright"]; } if (configuration.Attributes["description"] != null) { description = configuration.Attributes["description"]; } if (configuration.Attributes["url"] != null) { url = configuration.Attributes["url"]; } if (configuration.Attributes["hideninmanager"] != null) { hidenInManager = bool.Parse(configuration.Attributes["hideninmanager"]); } else { hidenInManager = false; } } // 解析图象、字符串资源 if (configService.Exists(ResourcesPath)) { configuration = new XMLConfiguration(configService.GetItem(ResourcesPath)); ParseResource(configuration); } // 解析构建器 if (configService.Exists(BuildersPath)) { configuration = new XMLConfiguration(configService.GetItem(BuildersPath)); ParseBuilders(configuration); } // 解析插件 if (configService.Exists(AddInPath)) { configuration = new XMLConfiguration(configService.GetItem(AddInPath)); ParseAddIn(configuration); } logger.Info(String.Format("完成解析插件描述文件 \"{0}\"", Path.GetFileName(addInfile))); }
public SchemaMap(ErlDataStore store, string xmlContent) { m_Store = store; m_ErlSchema = XMLConfiguration.CreateFromXML(xmlContent); }