context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// .Net client wrapper for the REST API for Azure ApiManagement Service /// </summary> public static partial class ProductPolicyOperationsExtensions { /// <summary> /// Deletes specific product policy of the Api Management service /// instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string etag) { return Task.Factory.StartNew((object s) => { return ((IProductPolicyOperations)s).DeleteAsync(resourceGroupName, serviceName, pid, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes specific product policy of the Api Management service /// instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string etag) { return operations.DeleteAsync(resourceGroupName, serviceName, pid, etag, CancellationToken.None); } /// <summary> /// Gets specific product policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml /// </param> /// <returns> /// The response model for the get policy output operation. /// </returns> public static PolicyGetResponse Get(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format) { return Task.Factory.StartNew((object s) => { return ((IProductPolicyOperations)s).GetAsync(resourceGroupName, serviceName, pid, format); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets specific product policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml /// </param> /// <returns> /// The response model for the get policy output operation. /// </returns> public static Task<PolicyGetResponse> GetAsync(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format) { return operations.GetAsync(resourceGroupName, serviceName, pid, format, CancellationToken.None); } /// <summary> /// Sets policy for product. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml /// </param> /// <param name='policyStream'> /// Required. Policy stream. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Set(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format, Stream policyStream, string etag) { return Task.Factory.StartNew((object s) => { return ((IProductPolicyOperations)s).SetAsync(resourceGroupName, serviceName, pid, format, policyStream, etag); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Sets policy for product. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.ApiManagement.IProductPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='format'> /// Required. Format of the policy. Supported formats: /// application/vnd.ms-azure-apim.policy+xml /// </param> /// <param name='policyStream'> /// Required. Policy stream. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> SetAsync(this IProductPolicyOperations operations, string resourceGroupName, string serviceName, string pid, string format, Stream policyStream, string etag) { return operations.SetAsync(resourceGroupName, serviceName, pid, format, policyStream, etag, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Text.RegularExpressions; using CSL; namespace CS461_Access_Control { public partial class frmSettings : Form { CSL_Settings s; Regex rxIP = new Regex(@"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"); //For IP Address validation public frmSettings(CSL.CS461_HL_API reader, CSL.CSL_Settings settings) { s = settings; InitializeComponent(); cbLogLevel.Items.Add("Disable"); cbLogLevel.Items.Add("Info"); cbLogLevel.Items.Add("Verbose"); cbModProfile.Items.Add("Profile0"); cbModProfile.Items.Add("Profile1"); cbModProfile.Items.Add("Profile2"); cbModProfile.Items.Add("Profile3"); cbModProfile.Items.Add("Profile4"); cbDuplicateEliminationMethod.Items.Add("Autonomous Time Trigger"); cbDuplicateEliminationMethod.Items.Add("Polling Trigger by Client"); cbSearchMode.Items.Add("Default"); cbSearchMode.Items.Add("Single Target Large Population Inventory"); cbRxSensitivity.Items.Add("Maximum sensitivity"); cbRxSensitivity.Items.Add("Variable sensitivity"); cbAnt1Pwr.BeginUpdate(); cbAnt2Pwr.BeginUpdate(); cbAnt3Pwr.BeginUpdate(); cbAnt4Pwr.BeginUpdate(); for (double d = 15.00; d <= 30.00; d += 0.25) { cbAnt1Pwr.Items.Add(d.ToString("N2")); cbAnt2Pwr.Items.Add(d.ToString("N2")); cbAnt3Pwr.Items.Add(d.ToString("N2")); cbAnt4Pwr.Items.Add(d.ToString("N2")); } cbAnt1Pwr.EndUpdate(); cbAnt2Pwr.EndUpdate(); cbAnt3Pwr.EndUpdate(); cbAnt4Pwr.EndUpdate(); cbAnt1RSSI.BeginUpdate(); cbAnt2RSSI.BeginUpdate(); cbAnt3RSSI.BeginUpdate(); cbAnt4RSSI.BeginUpdate(); for (int i = -70; i <= -30.00; i++) { cbAnt1RSSI.Items.Add(i.ToString()); cbAnt2RSSI.Items.Add(i.ToString()); cbAnt3RSSI.Items.Add(i.ToString()); cbAnt4RSSI.Items.Add(i.ToString()); } cbAnt1RSSI.EndUpdate(); cbAnt2RSSI.EndUpdate(); cbAnt3RSSI.EndUpdate(); cbAnt4RSSI.EndUpdate(); cbTagICModel.BeginUpdate(); cbTagICModel.Items.Add("GenericTID32"); cbTagICModel.Items.Add("GenericTID64"); cbTagICModel.Items.Add("Monza"); cbTagICModel.Items.Add("Monaco"); cbTagICModel.Items.Add("Monza ID"); cbTagICModel.Items.Add("NXP"); cbTagICModel.EndUpdate(); cbMemoryBanks.BeginUpdate(); cbMemoryBanks.Items.Add("None"); cbMemoryBanks.Items.Add("Bank0"); cbMemoryBanks.Items.Add("Bank2"); cbMemoryBanks.Items.Add("Bank3"); cbMemoryBanks.EndUpdate(); cbAntennaPortScheme.BeginUpdate(); cbAntennaPortScheme.Items.Add("Combined"); cbAntennaPortScheme.Items.Add("Separated"); cbAntennaPortScheme.EndUpdate(); IPHostEntry he = Dns.GetHostEntry(System.Environment.MachineName); for (int i = 0; i < he.AddressList.Length; i++) { cbLocalIP.Items.Add(he.AddressList[i].ToString()); } } private void frmSettings_Load(object sender, EventArgs e) { txtURI.Text = s.Text("CS461/Reader/URI", "http://192.168.25.248/"); txtName.Text = s.Text("CS461/Reader/Login/Name", "root"); txtPass.Text = s.Text("CS461/Reader/Login/Password", "csl2006"); cbModProfile.Text = s.Text("CS461/Reader/ModulationProfile", "Profile0"); numSession.Value = (decimal)s.Int16("CS461/Reader/Session", 1); numPopulation.Value = (decimal)s.Int16("CS461/Reader/PopulationEstimation", 32); cbSearchMode.Text = s.Text("CS461/Reader/InventorySearchMode", "Default"); cbRxSensitivity.Text = s.Text("CS461/Reader/ReceiveSensitivity", "Maximum sensitivity"); cbAnt1Pwr.Text = s.Text("CS461/Reader/Antennas/Ant1/Power", "30.00"); cbAnt2Pwr.Text = s.Text("CS461/Reader/Antennas/Ant2/Power", "30.00"); cbAnt3Pwr.Text = s.Text("CS461/Reader/Antennas/Ant3/Power", "30.00"); cbAnt4Pwr.Text = s.Text("CS461/Reader/Antennas/Ant4/Power", "30.00"); chkAnt1.Checked = s.Boolean("CS461/Reader/Antennas/Ant1/Enabled", false); chkAnt2.Checked = s.Boolean("CS461/Reader/Antennas/Ant2/Enabled", false); chkAnt3.Checked = s.Boolean("CS461/Reader/Antennas/Ant3/Enabled", false); chkAnt4.Checked = s.Boolean("CS461/Reader/Antennas/Ant4/Enabled", false); cbAnt1RSSI.Text = s.Text("CS461/Reader/Antennas/Ant1/RSSI", "-70.00"); cbAnt2RSSI.Text = s.Text("CS461/Reader/Antennas/Ant2/RSSI", "-70.00"); cbAnt3RSSI.Text = s.Text("CS461/Reader/Antennas/Ant3/RSSI", "-70.00"); cbAnt4RSSI.Text = s.Text("CS461/Reader/Antennas/Ant4/RSSI", "-70.00"); cbDuplicateEliminationMethod.Text = s.Text("CS461/Reader/DuplicationElimination/Method", "Autonomous Time Trigger"); numDuplicateElimination.Value = (decimal)s.Int16("CS461/Reader/DuplicationElimination/Time", 1000); cbLogLevel.Text = s.Text("CS461/Application/LogLevel", "Info"); numListeningPort.Value = (decimal)s.Int16("CS461/Application/ServerPort", 9090); numHttp.Value = (decimal)s.Int16("CS461/SocketTimeout/Http", 30000); numTcp.Value = (decimal)s.Int16("CS461/SocketTimeout/Tcp", 30000); cbTagICModel.Text = s.Text("CS461/Reader/TagIC", "GenericTID32"); cbMemoryBanks.Text = s.Text("CS461/Reader/AdditionalMemoryBank", "None"); cbAntennaPortScheme.SelectedIndex = s.Text("CS461/Reader/DuplicationElimination/AntennaPortScheme", "false").Equals("true") ? 1 : 0; cbLocalIP.Text = s.Text("CS461/Application/LocalIP", "0.0.0.0"); } private void btnLoad_Click(object sender, EventArgs e) { defaultSettings(); } private void btnSave_Click(object sender, EventArgs e) { s.Save(); this.Close(); } private void defaultSettings() { txtURI.Text = "http://192.168.25.248/"; txtName.Text = "root"; txtPass.Text = "csl2006"; cbModProfile.Text = "Profile0"; numSession.Value = 1; numPopulation.Value = 32; cbSearchMode.Text = "Default"; cbRxSensitivity.Text = "Maximum sensitivity"; cbAnt1Pwr.Text = "30.00"; cbAnt2Pwr.Text = "30.00"; cbAnt3Pwr.Text = "30.00"; cbAnt4Pwr.Text = "30.00"; chkAnt1.Checked = true; chkAnt2.Checked = false; chkAnt3.Checked = false; chkAnt4.Checked = false; cbAnt1RSSI.Text = "-70.00"; cbAnt2RSSI.Text = "-70.00"; cbAnt3RSSI.Text = "-70.00"; cbAnt4RSSI.Text = "-70.00"; cbDuplicateEliminationMethod.Text = "Autonomous Time Trigger"; numDuplicateElimination.Value = 1000; cbLogLevel.Text = "Info"; numListeningPort.Value = 9090; numHttp.Value = 30000; numTcp.Value = 30000; cbTagICModel.Text = "GenericTID32"; cbMemoryBanks.Text = "None"; cbAntennaPortScheme.SelectedIndex = 0; cbLocalIP.SelectedIndex = 0; } private void txtURI_TextChanged(object sender, EventArgs e) { try { Uri u = new Uri(txtURI.Text); txtURI.BackColor = Color.White; s.Set("CS461/Reader/URI", txtURI.Text); } catch { txtURI.BackColor = Color.Red; } } private void txtName_TextChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Login/Name", txtName.Text); } private void txtPass_TextChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Login/Password", txtPass.Text); } private void cbModProfile_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/ModulationProfile", cbModProfile.Text); } private void numSession_ValueChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Session", numSession.Value.ToString()); } private void numPopulation_ValueChanged(object sender, EventArgs e) { s.Set("CS461/Reader/PopulationEstimation", numPopulation.Value.ToString()); } private void cbSearchMode_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/InventorySearchMode", cbSearchMode.Text); } private void cbRxSensitivity_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/ReceiveSensitivity", cbRxSensitivity.Text); if (cbRxSensitivity.SelectedIndex == 0) { cbAnt1RSSI.Enabled = false; cbAnt2RSSI.Enabled = false; cbAnt3RSSI.Enabled = false; cbAnt4RSSI.Enabled = false; } else { cbAnt1RSSI.Enabled = true; cbAnt2RSSI.Enabled = true; cbAnt3RSSI.Enabled = true; cbAnt4RSSI.Enabled = true; } } private void cbDuplicateEliminationMethod_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/DuplicationElimination/Method", cbDuplicateEliminationMethod.Text); } private void numDuplicateElimination_ValueChanged(object sender, EventArgs e) { s.Set("CS461/Reader/DuplicationElimination/Time", numDuplicateElimination.Value.ToString()); } private void chkAnt1_CheckedChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant1/Enabled", chkAnt1.Checked ? "true" : "false"); } private void chkAnt2_CheckedChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant2/Enabled", chkAnt2.Checked ? "true" : "false"); } private void chkAnt3_CheckedChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant3/Enabled", chkAnt3.Checked ? "true" : "false"); } private void chkAnt4_CheckedChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant4/Enabled", chkAnt4.Checked ? "true" : "false"); } private void cbAnt1Pwr_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant1/Power", cbAnt1Pwr.Text); } private void cbAnt2Pwr_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant2/Power", cbAnt2Pwr.Text); } private void cbAnt3Pwr_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant3/Power", cbAnt3Pwr.Text); } private void cbAnt4Pwr_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant4/Power", cbAnt4Pwr.Text); } private void cbAnt1RSSI_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant1/RSSI", cbAnt1RSSI.Text); } private void cbAnt2RSSI_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant2/RSSI", cbAnt2RSSI.Text); } private void cbAnt3RSSI_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant3/RSSI", cbAnt3RSSI.Text); } private void cbAnt4RSSI_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/Antennas/Ant4/RSSI", cbAnt4RSSI.Text); } private void cbLogLevel_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Application/LogLevel", cbLogLevel.Text); } private void numListeningPort_ValueChanged(object sender, EventArgs e) { s.Set("CS461/Application/ServerPort", numListeningPort.Value.ToString()); } private void numHttp_ValueChanged(object sender, EventArgs e) { s.Set("CS461/SocketTimeout/Http", numHttp.Value.ToString()); } private void numTcp_ValueChanged(object sender, EventArgs e) { s.Set("CS461/SocketTimeout/Tcp", numTcp.Value.ToString()); } private void cbTagICModel_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/TagIC", cbTagICModel.Text); } private void cbMemoryBanks_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/AdditionalMemoryBank", cbMemoryBanks.Text); } private void cbAntennaPortScheme_SelectedIndexChanged(object sender, EventArgs e) { s.Set("CS461/Reader/DuplicationElimination/AntennaPortScheme", cbAntennaPortScheme.SelectedIndex == 1 ? "true" : "false"); } private void cbLocalIP_SelectedIndexChanged(object sender, EventArgs e) { if (rxIP.IsMatch(cbLocalIP.Text) == true) { cbLocalIP.BackColor = Color.White; s.Set("CS461/Application/LocalIP", cbLocalIP.Text); } else { cbLocalIP.BackColor = Color.Red; } } } }
// Copyright 2005-2012 Moonfire Games // Released under the MIT license // http://mfgames.com/mfgames-cil/license using System.Collections.Generic; using MfGames.Exceptions; using MfGames.HierarchicalPaths; using NUnit.Framework; namespace UnitTests { /// <summary> /// Testing fixture to test all of the various methods or possible /// errors involved with a node reference. /// </summary> [TestFixture] public class HierarchicalPathTests { #region Methods [Test] public void AreEqual() { // Setup var expected = new HierarchicalPath("/Application/Quit"); // Operation var path = new HierarchicalPath("/Application/Quit"); // Verification Assert.AreEqual(expected, path); Assert.IsTrue(expected == path); } /// <summary> /// Tests the index accessor to the created children. /// </summary> [Test] public void ChildIndex() { var up = new HierarchicalPath("/dir1/sub1"); HierarchicalPath c1 = up["sub2/sub3"]; Assert.AreEqual("/dir1/sub1/sub2/sub3", c1.Path); } /// <summary> /// Tests the number of components /// </summary> [Test] public void Count1() { var nr = new HierarchicalPath("/a/b/c"); Assert.AreEqual(3, nr.Count); } /// <summary> /// Tests the number of simple components /// </summary> [Test] public void Count2() { var nr = new HierarchicalPath("/a"); Assert.AreEqual(1, nr.Count); } /// <summary> /// Tests the number of the root context /// </summary> [Test] public void Count3() { var nr = new HierarchicalPath("/"); Assert.AreEqual(0, nr.Count); } /// <summary> /// Tests the leading "/a/b/../c" path construct. /// </summary> [Test] public void DoubleDot() { var nr = new HierarchicalPath("/a/b/../c"); Assert.AreEqual("/a/c", nr.Path); } /// <summary> /// Tests the leading "/a/.." path construct. /// </summary> [Test] public void DoubleDotTop() { var nr = new HierarchicalPath("/a/.."); Assert.AreEqual("/", nr.Path); } [Test] public void InDictionary() { // Setup var dictionary = new Dictionary<HierarchicalPath, string>(); dictionary[new HierarchicalPath("/Application/Quit")] = "yes"; // Operation var key = new HierarchicalPath("/Application/Quit"); string value = dictionary[key]; // Verification Assert.IsTrue(dictionary.ContainsKey(key)); Assert.AreEqual("yes", value); } /// <summary> /// Tests the leading "/../.." path construct. /// </summary> [Test] [ExpectedException(typeof (InvalidPathException))] public void InvalidDoubleDot2() { var nr = new HierarchicalPath("/../.."); Assert.AreEqual("/", nr.Path); } /// <summary> /// Tests the leading "." path. /// </summary> [Test] public void LeadingDot() { var context = new HierarchicalPath("/"); var path = new HierarchicalPath(".", context); Assert.AreEqual("/", path.Path); } /// <summary> /// Tests the leading "./" path construct. /// </summary> [Test] public void LeadingDotSlash() { var context = new HierarchicalPath("/"); var nr = new HierarchicalPath("./", context); Assert.AreEqual("/", nr.Path); } /// <summary> /// Tests the name of the components /// </summary> [Test] public void Name() { var nr = new HierarchicalPath("/a/b/c"); Assert.AreEqual("c", nr.Last); } /// <summary> /// Test lack of absolute path. /// </summary> [Test] public void NoAbsolute() { var path = new HierarchicalPath("foo"); Assert.IsTrue(path.IsRelative); Assert.AreEqual("./foo", path.Path); } /// <summary> /// Tests that the request for the direct path is valid. /// </summary> [Test] public void ParentPath() { var up = new HierarchicalPath("/dir1/sub1"); string up1 = up.Parent.Path; Assert.AreEqual("/dir1", up1); } /// <summary> /// Tests that a basic parent request returns the proper value. /// </summary> [Test] public void ParentRef() { var up = new HierarchicalPath("/dir1/sub1"); HierarchicalPath up1 = up.Parent; Assert.AreEqual("/dir1", up1.Path); } /// <summary> /// Tests various broken parsing tests. /// </summary> [Test] public void ParsePluses() { var nr = new HierarchicalPath("/Test/Test +1/Test +2"); Assert.AreEqual("/Test/Test +1/Test +2", nr.ToString()); Assert.AreEqual("Test +2", nr.Last); } /// <summary> /// Just tests the basic construction of a path. /// </summary> [Test] public void Simple() { var up = new HierarchicalPath("/dir1/sub1"); Assert.AreEqual("/dir1/sub1", up.Path); } /// <summary> /// Tests for the basic case of StartsWith. /// </summary> [Test] public void StartsWith1() { var nr = new HierarchicalPath("/this/is"); var sr = new HierarchicalPath("/this/is/a/path"); Assert.AreEqual(false, nr.StartsWith(sr)); } /// <summary> /// Tests for the case of not including. /// </summary> [Test] public void StartsWith2() { var nr = new HierarchicalPath("/this/is"); var sr = new HierarchicalPath("/not/in/is/a/path"); Assert.AreEqual(false, nr.StartsWith(sr)); } /// <summary> /// Tests for the identical cases /// </summary> [Test] public void StartsWith3() { var nr = new HierarchicalPath("/this/is"); var sr = new HierarchicalPath("/this/is"); Assert.AreEqual(true, nr.StartsWith(sr)); } /// <summary> /// Tests for the same parents /// </summary> [Test] public void StartsWith4() { var nr = new HierarchicalPath("/this/is"); var sr = new HierarchicalPath("/this"); Assert.AreEqual(true, nr.StartsWith(sr)); } /// <summary> /// Tests for a sub path isolation. /// </summary> [Test] public void SubRef1() { var nr = new HierarchicalPath("/this/is"); var sr = new HierarchicalPath("/this/is/a/path"); Assert.AreEqual("./a/path", sr.GetPathAfter(nr).Path); } /// <summary> /// Tests for a equal sub path isolation. /// </summary> [Test] public void SubRef2() { var nr = new HierarchicalPath("/this/is"); var sr = new HierarchicalPath("/this/is"); Assert.AreEqual(".", nr.GetPathAfter(sr).Path); } /// <summary> /// Tests for reverse items. /// </summary> [Test] [ExpectedException(typeof (HierarchicalPathException))] public void SubRef3() { var nr = new HierarchicalPath("/this/is/a/path"); var sr = new HierarchicalPath("/this/is"); sr.GetPathAfter(nr); } /// <summary> /// Tests for completely different sub reference. /// </summary> [Test] [ExpectedException(typeof (HierarchicalPathException))] public void SubRef4() { var nr = new HierarchicalPath("/this/is/a/path"); var sr = new HierarchicalPath("/not/a/path"); nr.GetPathAfter(sr); } /// <summary> /// Tests getting a subpath with a plus symbol. /// </summary> [Test] public void SubpathWithPluses() { var nr = new HierarchicalPath("/Test +1/A"); var nr2 = new HierarchicalPath("/Test +1"); HierarchicalPath nr3 = nr.GetPathAfter(nr2); Assert.AreEqual("./A", nr3.ToString()); } /// <summary> /// Tests an unescaped path. /// </summary> [Test] public void TestEscapedNone() { var nr = new HierarchicalPath("/a/b/c"); Assert.AreEqual("/a/b/c", nr.ToString(), "String comparison"); } /// <summary> /// Tests the basic create child functionality. /// </summary> [Test] public void TestNodeCreateChild() { var up = new HierarchicalPath("/dir1/sub1"); HierarchicalPath c1 = up.Append("sub2"); Assert.AreEqual("/dir1/sub1/sub2", c1.Path); } [Test] public void TestSplice1() { // Setup var path = new HierarchicalPath("/a/b/c/d/e"); // Operation HierarchicalPath results = path.Splice(0, 2); // Verification Assert.AreEqual("/a/b", results.ToString()); } [Test] public void TestSplice2() { // Setup var path = new HierarchicalPath("/a/b/c/d/e"); // Operation HierarchicalPath results = path.Splice(2, 2); // Verification Assert.AreEqual("./c/d", results.ToString()); } [Test] public void TestSplice3() { // Setup var path = new HierarchicalPath("/a/b/c/d/e"); // Operation HierarchicalPath results = path.Splice(3, 2); // Verification Assert.AreEqual("./d/e", results.ToString()); } #endregion } }
using System; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.Models; using umbraco; using umbraco.cms.businesslogic.web; using Umbraco.Core.Persistence.Repositories; namespace Umbraco.Web.Cache { /// <summary> /// Extension methods for <see cref="DistributedCache"/> /// </summary> internal static class DistributedCacheExtensions { #region Public access public static void RefreshPublicAccess(this DistributedCache dc) { dc.RefreshAll(DistributedCache.PublicAccessCacheRefresherGuid); } #endregion #region Application tree cache public static void RefreshAllApplicationTreeCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.ApplicationTreeCacheRefresherGuid); } #endregion #region Application cache public static void RefreshAllApplicationCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.ApplicationCacheRefresherGuid); } #endregion #region User type cache public static void RemoveUserTypeCache(this DistributedCache dc, int userTypeId) { dc.Remove(DistributedCache.UserTypeCacheRefresherGuid, userTypeId); } public static void RefreshUserTypeCache(this DistributedCache dc, int userTypeId) { dc.Refresh(DistributedCache.UserTypeCacheRefresherGuid, userTypeId); } public static void RefreshAllUserTypeCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserTypeCacheRefresherGuid); } #endregion #region User cache public static void RemoveUserCache(this DistributedCache dc, int userId) { dc.Remove(DistributedCache.UserCacheRefresherGuid, userId); } public static void RefreshUserCache(this DistributedCache dc, int userId) { dc.Refresh(DistributedCache.UserCacheRefresherGuid, userId); } public static void RefreshAllUserCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserCacheRefresherGuid); } #endregion #region User permissions cache public static void RemoveUserPermissionsCache(this DistributedCache dc, int userId) { dc.Remove(DistributedCache.UserPermissionsCacheRefresherGuid, userId); } public static void RefreshUserPermissionsCache(this DistributedCache dc, int userId) { dc.Refresh(DistributedCache.UserPermissionsCacheRefresherGuid, userId); } public static void RefreshAllUserPermissionsCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserPermissionsCacheRefresherGuid); } #endregion #region Template cache public static void RefreshTemplateCache(this DistributedCache dc, int templateId) { dc.Refresh(DistributedCache.TemplateRefresherGuid, templateId); } public static void RemoveTemplateCache(this DistributedCache dc, int templateId) { dc.Remove(DistributedCache.TemplateRefresherGuid, templateId); } #endregion #region Dictionary cache public static void RefreshDictionaryCache(this DistributedCache dc, int dictionaryItemId) { dc.Refresh(DistributedCache.DictionaryCacheRefresherGuid, dictionaryItemId); } public static void RemoveDictionaryCache(this DistributedCache dc, int dictionaryItemId) { dc.Remove(DistributedCache.DictionaryCacheRefresherGuid, dictionaryItemId); } #endregion #region Data type cache public static void RefreshDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) return; dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } public static void RemoveDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) return; dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } #endregion #region Page cache public static void RefreshAllPageCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.PageCacheRefresherGuid); } public static void RefreshPageCache(this DistributedCache dc, int documentId) { dc.Refresh(DistributedCache.PageCacheRefresherGuid, documentId); } public static void RefreshPageCache(this DistributedCache dc, params IContent[] content) { dc.Refresh(DistributedCache.PageCacheRefresherGuid, x => x.Id, content); } public static void RemovePageCache(this DistributedCache dc, params IContent[] content) { dc.Remove(DistributedCache.PageCacheRefresherGuid, x => x.Id, content); } public static void RemovePageCache(this DistributedCache dc, int documentId) { dc.Remove(DistributedCache.PageCacheRefresherGuid, documentId); } public static void RefreshUnpublishedPageCache(this DistributedCache dc, params IContent[] content) { dc.Refresh(DistributedCache.UnpublishedPageCacheRefresherGuid, x => x.Id, content); } public static void RemoveUnpublishedPageCache(this DistributedCache dc, params IContent[] content) { dc.Remove(DistributedCache.UnpublishedPageCacheRefresherGuid, x => x.Id, content); } public static void RemoveUnpublishedCachePermanently(this DistributedCache dc, params int[] contentIds) { dc.RefreshByJson(DistributedCache.UnpublishedPageCacheRefresherGuid, UnpublishedPageCacheRefresher.SerializeToJsonPayloadForPermanentDeletion(contentIds)); } #endregion #region Member cache public static void RefreshMemberCache(this DistributedCache dc, params IMember[] members) { dc.Refresh(DistributedCache.MemberCacheRefresherGuid, x => x.Id, members); } public static void RemoveMemberCache(this DistributedCache dc, params IMember[] members) { dc.Remove(DistributedCache.MemberCacheRefresherGuid, x => x.Id, members); } [Obsolete("Use the RefreshMemberCache with strongly typed IMember objects instead")] public static void RefreshMemberCache(this DistributedCache dc, int memberId) { dc.Refresh(DistributedCache.MemberCacheRefresherGuid, memberId); } [Obsolete("Use the RemoveMemberCache with strongly typed IMember objects instead")] public static void RemoveMemberCache(this DistributedCache dc, int memberId) { dc.Remove(DistributedCache.MemberCacheRefresherGuid, memberId); } #endregion #region Member group cache public static void RefreshMemberGroupCache(this DistributedCache dc, int memberGroupId) { dc.Refresh(DistributedCache.MemberGroupCacheRefresherGuid, memberGroupId); } public static void RemoveMemberGroupCache(this DistributedCache dc, int memberGroupId) { dc.Remove(DistributedCache.MemberGroupCacheRefresherGuid, memberGroupId); } #endregion #region Media Cache public static void RefreshMediaCache(this DistributedCache dc, params IMedia[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayload(MediaCacheRefresher.OperationType.Saved, media)); } public static void RefreshMediaCacheAfterMoving(this DistributedCache dc, params MoveEventInfo<IMedia>[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForMoving(MediaCacheRefresher.OperationType.Saved, media)); } // clearing by Id will never work for load balanced scenarios for media since we require a Path // to clear all of the cache but the media item will be removed before the other servers can // look it up. Only here for legacy purposes. [Obsolete("Ensure to clear with other RemoveMediaCache overload")] public static void RemoveMediaCache(this DistributedCache dc, int mediaId) { dc.Remove(new Guid(DistributedCache.MediaCacheRefresherId), mediaId); } public static void RemoveMediaCacheAfterRecycling(this DistributedCache dc, params MoveEventInfo<IMedia>[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForMoving(MediaCacheRefresher.OperationType.Trashed, media)); } public static void RemoveMediaCachePermanently(this DistributedCache dc, params int[] mediaIds) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForPermanentDeletion(mediaIds)); } #endregion #region Macro Cache public static void ClearAllMacroCacheOnCurrentServer(this DistributedCache dc) { var macroRefresher = CacheRefreshersResolver.Current.GetById(DistributedCache.MacroCacheRefresherGuid); macroRefresher.RefreshAll(); } public static void RefreshMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RefreshMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, macro macro) { if (macro == null || macro.Model == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } #endregion #region Document type cache public static void RefreshContentTypeCache(this DistributedCache dc, IContentType contentType) { if (contentType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, contentType)); } public static void RemoveContentTypeCache(this DistributedCache dc, IContentType contentType) { if (contentType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, contentType)); } #endregion #region Media type cache public static void RefreshMediaTypeCache(this DistributedCache dc, IMediaType mediaType) { if (mediaType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, mediaType)); } public static void RemoveMediaTypeCache(this DistributedCache dc, IMediaType mediaType) { if (mediaType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, mediaType)); } #endregion #region Media type cache public static void RefreshMemberTypeCache(this DistributedCache dc, IMemberType memberType) { if (memberType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, memberType)); } public static void RemoveMemberTypeCache(this DistributedCache dc, IMemberType memberType) { if (memberType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, memberType)); } #endregion #region Stylesheet Cache public static void RefreshStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) { if (styleSheetProperty == null) return; dc.Refresh(DistributedCache.StylesheetPropertyCacheRefresherGuid, styleSheetProperty.Id); } public static void RemoveStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) { if (styleSheetProperty == null) return; dc.Remove(DistributedCache.StylesheetPropertyCacheRefresherGuid, styleSheetProperty.Id); } public static void RefreshStylesheetCache(this DistributedCache dc, StyleSheet styleSheet) { if (styleSheet == null) return; dc.Refresh(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RemoveStylesheetCache(this DistributedCache dc, StyleSheet styleSheet) { if (styleSheet == null) return; dc.Remove(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RefreshStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet) { if (styleSheet == null) return; dc.Refresh(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RemoveStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet) { if (styleSheet == null) return; dc.Remove(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } #endregion #region Domain Cache public static void RefreshDomainCache(this DistributedCache dc, IDomain domain) { if (domain == null) return; dc.Refresh(DistributedCache.DomainCacheRefresherGuid, domain.Id); } public static void RemoveDomainCache(this DistributedCache dc, IDomain domain) { if (domain == null) return; dc.Remove(DistributedCache.DomainCacheRefresherGuid, domain.Id); } public static void ClearDomainCacheOnCurrentServer(this DistributedCache dc) { var domainRefresher = CacheRefreshersResolver.Current.GetById(DistributedCache.DomainCacheRefresherGuid); domainRefresher.RefreshAll(); } #endregion #region Language Cache public static void RefreshLanguageCache(this DistributedCache dc, ILanguage language) { if (language == null) return; dc.Refresh(DistributedCache.LanguageCacheRefresherGuid, language.Id); } public static void RemoveLanguageCache(this DistributedCache dc, ILanguage language) { if (language == null) return; dc.Remove(DistributedCache.LanguageCacheRefresherGuid, language.Id); } public static void RefreshLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language) { if (language == null) return; dc.Refresh(DistributedCache.LanguageCacheRefresherGuid, language.id); } public static void RemoveLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language) { if (language == null) return; dc.Remove(DistributedCache.LanguageCacheRefresherGuid, language.id); } #endregion #region Xslt Cache public static void ClearXsltCacheOnCurrentServer(this DistributedCache dc) { if (UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration <= 0) return; ApplicationContext.Current.ApplicationCache.ClearCacheObjectTypes("MS.Internal.Xml.XPath.XPathSelectionIterator"); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins { public class SensorRepeat { public AsyncCommandManager m_CmdManager; public SensorRepeat(AsyncCommandManager CmdManager) { m_CmdManager = CmdManager; maximumRange = CmdManager.m_ScriptEngine.Config.GetDouble("SensorMaxRange", 96.0d); maximumToReturn = CmdManager.m_ScriptEngine.Config.GetInt("SensorMaxResults", 16); } private Object SenseLock = new Object(); private const int AGENT = 1; private const int AGENT_BY_USERNAME = 0x10; private const int ACTIVE = 2; private const int PASSIVE = 4; private const int SCRIPTED = 8; private double maximumRange = 96.0; private int maximumToReturn = 16; // // SenseRepeater and Sensors // private class SenseRepeatClass { public uint localID; public UUID itemID; public double interval; public DateTime next; public string name; public UUID keyID; public int type; public double range; public double arc; public SceneObjectPart host; } // // Sensed entity // private class SensedEntity : IComparable { public SensedEntity(double detectedDistance, UUID detectedID) { distance = detectedDistance; itemID = detectedID; } public int CompareTo(object obj) { if (!(obj is SensedEntity)) throw new InvalidOperationException(); SensedEntity ent = (SensedEntity)obj; if (ent == null || ent.distance < distance) return 1; if (ent.distance > distance) return -1; return 0; } public UUID itemID; public double distance; } private List<SenseRepeatClass> SenseRepeaters = new List<SenseRepeatClass>(); private object SenseRepeatListLock = new object(); public void SetSenseRepeatEvent(uint m_localID, UUID m_itemID, string name, UUID keyID, int type, double range, double arc, double sec, SceneObjectPart host) { // Always remove first, in case this is a re-set UnSetSenseRepeaterEvents(m_localID, m_itemID); if (sec == 0) // Disabling timer return; // Add to timer SenseRepeatClass ts = new SenseRepeatClass(); ts.localID = m_localID; ts.itemID = m_itemID; ts.interval = sec; ts.name = name; ts.keyID = keyID; ts.type = type; if (range > maximumRange) ts.range = maximumRange; else ts.range = range; ts.arc = arc; ts.host = host; ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); lock (SenseRepeatListLock) { SenseRepeaters.Add(ts); } } public void UnSetSenseRepeaterEvents(uint m_localID, UUID m_itemID) { // Remove from timer lock (SenseRepeatListLock) { List<SenseRepeatClass> NewSensors = new List<SenseRepeatClass>(); foreach (SenseRepeatClass ts in SenseRepeaters) { if (ts.localID != m_localID && ts.itemID != m_itemID) { NewSensors.Add(ts); } } SenseRepeaters.Clear(); SenseRepeaters = NewSensors; } } public void CheckSenseRepeaterEvents() { // Nothing to do here? if (SenseRepeaters.Count == 0) return; lock (SenseRepeatListLock) { // Go through all timers foreach (SenseRepeatClass ts in SenseRepeaters) { // Time has passed? if (ts.next.ToUniversalTime() < DateTime.Now.ToUniversalTime()) { SensorSweep(ts); // set next interval ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); } } } // lock } public void SenseOnce(uint m_localID, UUID m_itemID, string name, UUID keyID, int type, double range, double arc, SceneObjectPart host) { // Add to timer SenseRepeatClass ts = new SenseRepeatClass(); ts.localID = m_localID; ts.itemID = m_itemID; ts.interval = 0; ts.name = name; ts.keyID = keyID; ts.type = type; if (range > maximumRange) ts.range = maximumRange; else ts.range = range; ts.arc = arc; ts.host = host; SensorSweep(ts); } private void SensorSweep(SenseRepeatClass ts) { if (ts.host == null) { return; } List<SensedEntity> sensedEntities = new List<SensedEntity>(); // Is the sensor type is AGENT and not SCRIPTED then include agents if ((ts.type & (AGENT | AGENT_BY_USERNAME)) != 0 && (ts.type & SCRIPTED) == 0) { sensedEntities.AddRange(doAgentSensor(ts)); } // If SCRIPTED or PASSIVE or ACTIVE check objects if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0) { sensedEntities.AddRange(doObjectSensor(ts)); } lock (SenseLock) { if (sensedEntities.Count == 0) { // send a "no_sensor" // Add it to queue m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID, new EventParams("no_sensor", new Object[0], new DetectParams[0])); } else { // Sort the list to get everything ordered by distance sensedEntities.Sort(); int count = sensedEntities.Count; int idx; List<DetectParams> detected = new List<DetectParams>(); for (idx = 0; idx < count; idx++) { try { DetectParams detect = new DetectParams(); detect.Key = sensedEntities[idx].itemID; detect.Populate(m_CmdManager.m_ScriptEngine.World); detected.Add(detect); } catch (Exception) { // Ignore errors, the object has been deleted or the avatar has gone and // there was a problem in detect.Populate so nothing added to the list } if (detected.Count == maximumToReturn) break; } if (detected.Count == 0) { // To get here with zero in the list there must have been some sort of problem // like the object being deleted or the avatar leaving to have caused some // difficulty during the Populate above so fire a no_sensor event m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID, new EventParams("no_sensor", new Object[0], new DetectParams[0])); } else { m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID, new EventParams("sensor", new Object[] {new LSL_Types.LSLInteger(detected.Count) }, detected.ToArray())); } } } } private List<SensedEntity> doObjectSensor(SenseRepeatClass ts) { List<EntityBase> Entities; List<SensedEntity> sensedEntities = new List<SensedEntity>(); // If this is an object sense by key try to get it directly // rather than getting a list to scan through if (ts.keyID != UUID.Zero) { EntityBase e = null; m_CmdManager.m_ScriptEngine.World.Entities.TryGetValue(ts.keyID, out e); if (e == null) return sensedEntities; Entities = new List<EntityBase>(); Entities.Add(e); } else { Entities = new List<EntityBase>(m_CmdManager.m_ScriptEngine.World.GetEntities()); } SceneObjectPart SensePoint = ts.host; Vector3 fromRegionPos = SensePoint.AbsolutePosition; // pre define some things to avoid repeated definitions in the loop body Vector3 toRegionPos; double dis; int objtype; SceneObjectPart part; float dx; float dy; float dz; Quaternion q = SensePoint.RotationOffset; if (SensePoint.ParentGroup.RootPart.IsAttachment) { // In attachments, the sensor cone always orients with the // avatar rotation. This may include a nonzero elevation if // in mouselook. ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.RootPart.AttachedAvatar); q = avatar.Rotation; } LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); Vector3 ZeroVector = new Vector3(0, 0, 0); bool nameSearch = (ts.name != null && ts.name != ""); foreach (EntityBase ent in Entities) { bool keep = true; if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search continue; if (ent.IsDeleted) // taken so long to do this it has gone from the scene continue; if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar continue; toRegionPos = ent.AbsolutePosition; // Calculation is in line for speed dx = toRegionPos.X - fromRegionPos.X; dy = toRegionPos.Y - fromRegionPos.Y; dz = toRegionPos.Z - fromRegionPos.Z; // Weed out those that will not fit in a cube the size of the range // no point calculating if they are within a sphere the size of the range // if they arent even in the cube if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range) dis = ts.range + 1.0; else dis = Math.Sqrt(dx * dx + dy * dy + dz * dz); if (keep && dis <= ts.range && ts.host.UUID != ent.UUID) { // In Range and not the object containing the script, is it the right Type ? objtype = 0; part = ((SceneObjectGroup)ent).RootPart; if (part.AttachmentPoint != 0) // Attached so ignore continue; if (part.Inventory.ContainsScripts()) { objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ... } else { if (ent.Velocity.Equals(ZeroVector)) { objtype |= PASSIVE; // Passive non-moving } else { objtype |= ACTIVE; // moving so active } } // If any of the objects attributes match any in the requested scan type if (((ts.type & objtype) != 0)) { // Right type too, what about the other params , key and name ? if (ts.arc < Math.PI) { // not omni-directional. Can you see it ? // vec forward_dir = llRot2Fwd(llGetRot()) // vec obj_dir = toRegionPos-fromRegionPos // dot=dot(forward_dir,obj_dir) // mag_fwd = mag(forward_dir) // mag_obj = mag(obj_dir) // ang = acos(dot /(mag_fwd*mag_obj)) double ang_obj = 0; try { Vector3 diff = toRegionPos - fromRegionPos; LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z); double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir); double mag_obj = LSL_Types.Vector3.Mag(obj_dir); ang_obj = Math.Acos(dot / (mag_fwd * mag_obj)); } catch { } if (ang_obj > ts.arc) keep = false; } if (keep == true) { // add distance for sorting purposes later sensedEntities.Add(new SensedEntity(dis, ent.UUID)); } } } } return sensedEntities; } private List<SensedEntity> doAgentSensor(SenseRepeatClass ts) { List<SensedEntity> sensedEntities = new List<SensedEntity>(); // If nobody about quit fast if (m_CmdManager.m_ScriptEngine.World.GetRootAgentCount() == 0) return sensedEntities; SceneObjectPart SensePoint = ts.host; Vector3 fromRegionPos = SensePoint.AbsolutePosition; Quaternion q = SensePoint.RotationOffset; LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W); LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r); double mag_fwd = LSL_Types.Vector3.Mag(forward_dir); bool attached = (SensePoint.AttachmentPoint != 0); Vector3 toRegionPos; double dis; Action<ScenePresence> senseEntity = new Action<ScenePresence>(delegate(ScenePresence presence) { if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0) return; // if the object the script is in is attached and the avatar is the owner // then this one is not wanted if (attached && presence.UUID == SensePoint.OwnerID) return; toRegionPos = presence.AbsolutePosition; dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos)); // are they in range if (dis <= ts.range) { // Are they in the required angle of view if (ts.arc < Math.PI) { // not omni-directional. Can you see it ? // vec forward_dir = llRot2Fwd(llGetRot()) // vec obj_dir = toRegionPos-fromRegionPos // dot=dot(forward_dir,obj_dir) // mag_fwd = mag(forward_dir) // mag_obj = mag(obj_dir) // ang = acos(dot /(mag_fwd*mag_obj)) double ang_obj = 0; try { Vector3 diff = toRegionPos - fromRegionPos; LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z); double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir); double mag_obj = LSL_Types.Vector3.Mag(obj_dir); ang_obj = Math.Acos(dot / (mag_fwd * mag_obj)); } catch { } if (ang_obj <= ts.arc) { sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } else { sensedEntities.Add(new SensedEntity(dis, presence.UUID)); } } }); // If this is an avatar sense by key try to get them directly // rather than getting a list to scan through if (ts.keyID != UUID.Zero) { ScenePresence sp; // Try direct lookup by UUID if (!m_CmdManager.m_ScriptEngine.World.TryGetScenePresence(ts.keyID, out sp)) return sensedEntities; senseEntity(sp); } else if (ts.name != null && ts.name != "") { ScenePresence sp; // Try lookup by name will return if/when found if (((ts.type & AGENT) != 0) && m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp)) senseEntity(sp); if ((ts.type & AGENT_BY_USERNAME) != 0) { m_CmdManager.m_ScriptEngine.World.ForEachScenePresence( delegate (ScenePresence ssp) { if (ssp.Lastname == "Resident") { if (ssp.Firstname.ToLower() == ts.name) senseEntity(ssp); return; } if (ssp.Name.Replace(" ", ".").ToLower() == ts.name) senseEntity(ssp); } ); } return sensedEntities; } else { m_CmdManager.m_ScriptEngine.World.ForEachScenePresence(senseEntity); } return sensedEntities; } public Object[] GetSerializationData(UUID itemID) { List<Object> data = new List<Object>(); lock (SenseRepeatListLock) { foreach (SenseRepeatClass ts in SenseRepeaters) { if (ts.itemID == itemID) { data.Add(ts.interval); data.Add(ts.name); data.Add(ts.keyID); data.Add(ts.type); data.Add(ts.range); data.Add(ts.arc); } } } return data.ToArray(); } public void CreateFromData(uint localID, UUID itemID, UUID objectID, Object[] data) { SceneObjectPart part = m_CmdManager.m_ScriptEngine.World.GetSceneObjectPart( objectID); if (part == null) return; int idx = 0; while (idx < data.Length) { SenseRepeatClass ts = new SenseRepeatClass(); ts.localID = localID; ts.itemID = itemID; ts.interval = (double)data[idx]; ts.name = (string)data[idx+1]; ts.keyID = (UUID)data[idx+2]; ts.type = (int)data[idx+3]; ts.range = (double)data[idx+4]; ts.arc = (double)data[idx+5]; ts.host = part; ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); SenseRepeaters.Add(ts); idx += 6; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Abstractions.Models; using BTCPayServer.Models.ServerViewModels; using BTCPayServer.Storage.Models; using BTCPayServer.Storage.Services.Providers.AmazonS3Storage; using BTCPayServer.Storage.Services.Providers.AmazonS3Storage.Configuration; using BTCPayServer.Storage.Services.Providers.AzureBlobStorage; using BTCPayServer.Storage.Services.Providers.AzureBlobStorage.Configuration; using BTCPayServer.Storage.Services.Providers.FileSystemStorage; using BTCPayServer.Storage.Services.Providers.FileSystemStorage.Configuration; using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage; using BTCPayServer.Storage.Services.Providers.GoogleCloudStorage.Configuration; using BTCPayServer.Storage.Services.Providers.Models; using BTCPayServer.Storage.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Newtonsoft.Json.Linq; namespace BTCPayServer.Controllers { public partial class UIServerController { [HttpGet("server/files")] public async Task<IActionResult> Files([FromQuery] string[] fileIds = null) { var model = new ViewFilesViewModel() { Files = await _StoredFileRepository.GetFiles(), DirectUrlByFiles = null, StorageConfigured = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) != null }; if (fileIds != null && fileIds.Length > 0) { bool allFilesExist = true; Dictionary<string, string> directUrlByFiles = new Dictionary<string, string>(); foreach (string filename in fileIds) { string fileUrl = await _FileService.GetFileUrl(Request.GetAbsoluteRootUri(), filename); if (fileUrl == null) { allFilesExist = false; break; } directUrlByFiles.Add(filename, fileUrl); } if (!allFilesExist) { this.TempData.SetStatusMessageModel(new StatusMessageModel() { Message = "Some of the files were not found", Severity = StatusMessageModel.StatusSeverity.Warning, }); } else { model.DirectUrlByFiles = directUrlByFiles; } } return View(model); } [HttpGet("server/files/{fileId}/delete")] public async Task<IActionResult> DeleteFile(string fileId) { try { await _FileService.RemoveFile(fileId, null); return RedirectToAction(nameof(Files), new { fileIds = Array.Empty<string>(), statusMessage = "File removed" }); } catch (Exception e) { TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Error, Message = e.Message }); return RedirectToAction(nameof(Files)); } } [HttpGet("server/files/{fileId}/tmp")] public async Task<IActionResult> CreateTemporaryFileUrl(string fileId) { var file = await _StoredFileRepository.GetFile(fileId); if (file == null) { return NotFound(); } return View(new CreateTemporaryFileUrlViewModel()); } [HttpPost("server/files/{fileId}/tmp")] public async Task<IActionResult> CreateTemporaryFileUrl(string fileId, CreateTemporaryFileUrlViewModel viewModel) { if (viewModel.TimeAmount <= 0) { ModelState.AddModelError(nameof(viewModel.TimeAmount), "Time must be at least 1"); } if (!ModelState.IsValid) { return View(viewModel); } var file = await _StoredFileRepository.GetFile(fileId); if (file == null) { return NotFound(); } var expiry = DateTimeOffset.UtcNow; switch (viewModel.TimeType) { case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Seconds: expiry = expiry.AddSeconds(viewModel.TimeAmount); break; case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Minutes: expiry = expiry.AddMinutes(viewModel.TimeAmount); break; case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Hours: expiry = expiry.AddHours(viewModel.TimeAmount); break; case CreateTemporaryFileUrlViewModel.TmpFileTimeType.Days: expiry = expiry.AddDays(viewModel.TimeAmount); break; default: throw new ArgumentOutOfRangeException(); } var url = await _FileService.GetTemporaryFileUrl(Request.GetAbsoluteRootUri(), fileId, expiry, viewModel.IsDownload); TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Success, Html = $"Generated Temporary Url for file {file.FileName} which expires at {expiry.ToBrowserDate()}. <a href='{url}' target='_blank'>{url}</a>" }); return RedirectToAction(nameof(Files), new { fileIds = new string[] { fileId } }); } public class CreateTemporaryFileUrlViewModel { public enum TmpFileTimeType { Seconds, Minutes, Hours, Days } public int TimeAmount { get; set; } public TmpFileTimeType TimeType { get; set; } public bool IsDownload { get; set; } } [HttpPost("server/files/upload")] public async Task<IActionResult> CreateFiles(List<IFormFile> files) { if (files != null && files.Count > 0) { int invalidFileNameCount = 0; List<string> fileIds = new List<string>(); foreach (IFormFile file in files) { if (!file.FileName.IsValidFileName()) { invalidFileNameCount++; continue; } var newFile = await _FileService.AddFile(file, GetUserId()); fileIds.Add(newFile.Id); } StatusMessageModel.StatusSeverity statusMessageSeverity; string statusMessage; if (invalidFileNameCount == 0) { statusMessage = "Files Added Successfully"; statusMessageSeverity = StatusMessageModel.StatusSeverity.Success; } else if (invalidFileNameCount > 0 && invalidFileNameCount < files.Count) { statusMessage = $"{files.Count - invalidFileNameCount} files were added. {invalidFileNameCount} files had invalid names"; statusMessageSeverity = StatusMessageModel.StatusSeverity.Error; } else { statusMessage = $"Files could not be added due to invalid names"; statusMessageSeverity = StatusMessageModel.StatusSeverity.Error; } this.TempData.SetStatusMessageModel(new StatusMessageModel() { Message = statusMessage, Severity = statusMessageSeverity }); return RedirectToAction(nameof(Files), new { fileIds = fileIds.ToArray(), }); } else { return RedirectToAction(nameof(Files)); } } private string GetUserId() { return _UserManager.GetUserId(ControllerContext.HttpContext.User); } [HttpGet("server/storage")] public async Task<IActionResult> Storage(bool forceChoice = false) { var savedSettings = await _SettingsRepository.GetSettingAsync<StorageSettings>(); if (forceChoice || savedSettings == null) { var providersList = _StorageProviderServices.Select(a => new SelectListItem(a.StorageProvider().ToString(), a.StorageProvider().ToString()) ); return View(new ChooseStorageViewModel() { ProvidersList = providersList, ShowChangeWarning = savedSettings != null, Provider = savedSettings?.Provider ?? BTCPayServer.Storage.Models.StorageProvider.FileSystem }); } return RedirectToAction(nameof(StorageProvider), new { provider = savedSettings.Provider }); } [HttpPost("server/storage")] public IActionResult Storage(StorageSettings viewModel) { return RedirectToAction("StorageProvider", "UIServer", new { provider = viewModel.Provider.ToString() }); } [HttpGet("server/storage/{provider}")] public async Task<IActionResult> StorageProvider(string provider) { if (!Enum.TryParse(typeof(StorageProvider), provider, out var storageProvider)) { TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Error, Message = $"{provider} provider is not supported" }); return RedirectToAction(nameof(Storage)); } var data = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) ?? new StorageSettings(); var storageProviderService = _StorageProviderServices.SingleOrDefault(service => service.StorageProvider().Equals(storageProvider)); switch (storageProviderService) { case null: TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Error, Message = $"{storageProvider} is not supported" }); return RedirectToAction(nameof(Storage)); case AzureBlobStorageFileProviderService fileProviderService: return View(nameof(EditAzureBlobStorageStorageProvider), fileProviderService.GetProviderConfiguration(data)); case AmazonS3FileProviderService fileProviderService: return View(nameof(EditAmazonS3StorageProvider), fileProviderService.GetProviderConfiguration(data)); case GoogleCloudStorageFileProviderService fileProviderService: return View(nameof(EditGoogleCloudStorageStorageProvider), fileProviderService.GetProviderConfiguration(data)); case FileSystemFileProviderService fileProviderService: if (data.Provider != BTCPayServer.Storage.Models.StorageProvider.FileSystem) { _ = await SaveStorageProvider(new FileSystemStorageConfiguration(), BTCPayServer.Storage.Models.StorageProvider.FileSystem); } return View(nameof(EditFileSystemStorageProvider), fileProviderService.GetProviderConfiguration(data)); } return NotFound(); } [HttpPost("server/storage/AzureBlobStorage")] public async Task<IActionResult> EditAzureBlobStorageStorageProvider(AzureBlobStorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.AzureBlobStorage); } [HttpPost("server/storage/AmazonS3")] public async Task<IActionResult> EditAmazonS3StorageProvider(AmazonS3StorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.AmazonS3); } [HttpPost("server/storage/GoogleCloudStorage")] public async Task<IActionResult> EditGoogleCloudStorageStorageProvider( GoogleCloudStorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.GoogleCloudStorage); } [HttpPost("server/storage/FileSystem")] public async Task<IActionResult> EditFileSystemStorageProvider(FileSystemStorageConfiguration viewModel) { return await SaveStorageProvider(viewModel, BTCPayServer.Storage.Models.StorageProvider.FileSystem); } private async Task<IActionResult> SaveStorageProvider(IBaseStorageConfiguration viewModel, StorageProvider storageProvider) { if (!ModelState.IsValid) { return View(viewModel); } var data = (await _SettingsRepository.GetSettingAsync<StorageSettings>()) ?? new StorageSettings(); data.Provider = storageProvider; data.Configuration = JObject.FromObject(viewModel); await _SettingsRepository.UpdateSetting(data); TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Success, Message = "Storage settings updated successfully" }); return View(viewModel); } } }
using System; using Mono.CSharp; using Mono.Terminal; using System.Collections.Generic; using System.IO; using System.Collections; namespace Mono { public class CSharpShell { static bool isatty = true, is_unix = false; protected string [] startup_files; Mono.Terminal.LineEditor editor; bool dumb; readonly Evaluator evaluator; IConsole Console; public CSharpShell (Evaluator evaluator, IConsole console) { this.evaluator = evaluator; this.Console = console; } protected virtual void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a) { // Do not about our program a.Cancel = true; evaluator.Interrupt (); } void SetupConsole () { if (is_unix){ string term = Environment.GetEnvironmentVariable ("TERM"); dumb = term == "dumb" || term == null || isatty == false; } else dumb = false; editor = new Mono.Terminal.LineEditor (new RealConsole(), "csharp", 300); InteractiveBaseShell.Editor = editor; editor.AutoCompleteEvent += delegate (string s, int pos){ string prefix = null; string complete = s.Substring (0, pos); string [] completions = evaluator.GetCompletions (complete, out prefix); return new Mono.Terminal.LineEditor.Completion (prefix, completions); }; #if false // // This is a sample of how completions sould be implemented. // editor.AutoCompleteEvent += delegate (string s, int pos){ // Single match: "Substring": Sub-string if (s.EndsWith ("Sub")){ return new string [] { "string" }; } // Multiple matches: "ToString" and "ToLower" if (s.EndsWith ("T")){ return new string [] { "ToString", "ToLower" }; } return null; }; #endif Console.CancelKeyPress += ConsoleInterrupt; } string GetLine (bool primary) { string prompt = primary ? InteractiveBase.Prompt : InteractiveBase.ContinuationPrompt; if (dumb){ if (isatty) Console.Write (prompt); return Console.ReadLine (); } else { return editor.Edit (prompt, ""); } } delegate string ReadLiner (bool primary); void InitializeUsing () { Evaluate ("using System; using System.Linq; using System.Collections.Generic; using System.Collections;"); } void InitTerminal (bool show_banner) { int p = (int) Environment.OSVersion.Platform; is_unix = (p == 4) || (p == 128); #if NET_4_5 isatty = !Console.IsInputRedirected && !Console.IsOutputRedirected; #else isatty = true; #endif // Work around, since Console is not accounting for // cursor position when writing to Stderr. It also // has the undesirable side effect of making // errors plain, with no coloring. // Report.Stderr = Console.Out; SetupConsole (); if (isatty && show_banner) Console.WriteLine ("Mono C# Shell, type \"help;\" for help\n\nEnter statements below."); } void ExecuteSources (IEnumerable<string> sources, bool ignore_errors) { foreach (string file in sources){ try { try { bool first = true; using (System.IO.StreamReader r = System.IO.File.OpenText (file)){ ReadEvalPrintLoopWith (p => { var line = r.ReadLine (); if (first){ if (line.StartsWith ("#!")) line = r.ReadLine (); first = false; } return line; }); } } catch (FileNotFoundException){ Console.WriteLine ("cs2001: Source file `{0}' not found", file); return; } } catch { if (!ignore_errors) throw; } } } protected virtual void LoadStartupFiles () { string dir = Path.Combine ( Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "csharp"); if (!Directory.Exists (dir)) return; List<string> sources = new List<string> (); List<string> libraries = new List<string> (); foreach (string file in System.IO.Directory.GetFiles (dir)){ string l = file.ToLower (); if (l.EndsWith (".cs")) sources.Add (file); else if (l.EndsWith (".dll")) libraries.Add (file); } foreach (string file in libraries) evaluator.LoadAssembly (file); ExecuteSources (sources, true); } void ReadEvalPrintLoopWith (ReadLiner readline) { string expr = null; while (!InteractiveBase.QuitRequested){ string input = readline (expr == null); if (input == null) return; if (input == "") continue; expr = expr == null ? input : expr + "\n" + input; expr = Evaluate (expr); } } public int ReadEvalPrintLoop () { if (startup_files != null && startup_files.Length == 0) InitTerminal (startup_files.Length == 0 && Driver.StartupEvalExpression == null); InitializeUsing (); LoadStartupFiles (); if (startup_files != null && startup_files.Length != 0) { ExecuteSources (startup_files, false); } else { if (Driver.StartupEvalExpression != null){ ReadEvalPrintLoopWith (p => { var ret = Driver.StartupEvalExpression; Driver.StartupEvalExpression = null; return ret; }); } else { ReadEvalPrintLoopWith (GetLine); } editor.SaveHistory (); } Console.CancelKeyPress -= ConsoleInterrupt; return 0; } protected virtual string Evaluate (string input) { bool result_set; object result; try { input = evaluator.Evaluate (input, out result, out result_set); if (result_set){ PrettyPrint (Console, result); Console.WriteLine (); } } catch (Exception e){ Console.WriteLine (e); return null; } return input; } static void p (IConsole output, string s) { output.Write (s); } static string EscapeString (string s) { return s.Replace ("\"", "\\\""); } static void EscapeChar (IConsole output, char c) { if (c == '\''){ output.Write ("'\\''"); return; } if (c > 32){ output.Write (string.Format("'{0}'", c)); return; } switch (c){ case '\a': output.Write ("'\\a'"); break; case '\b': output.Write ("'\\b'"); break; case '\n': output.Write ("'\\n'"); break; case '\v': output.Write ("'\\v'"); break; case '\r': output.Write ("'\\r'"); break; case '\f': output.Write ("'\\f'"); break; case '\t': output.Write ("'\\t"); break; default: output.Write (string.Format("'\\x{0:x}", (int) c)); break; } } // Some types (System.Json.JsonPrimitive) implement // IEnumerator and yet, throw an exception when we // try to use them, helper function to check for that // condition static internal bool WorksAsEnumerable (object obj) { IEnumerable enumerable = obj as IEnumerable; if (enumerable != null){ try { enumerable.GetEnumerator (); return true; } catch { // nothing, we return false below } } return false; } internal static void PrettyPrint (IConsole output, object result) { if (result == null){ p (output, "null"); return; } if (result is Array){ Array a = (Array) result; p (output, "{ "); int top = a.GetUpperBound (0); for (int i = a.GetLowerBound (0); i <= top; i++){ PrettyPrint (output, a.GetValue (i)); if (i != top) p (output, ", "); } p (output, " }"); } else if (result is bool){ if ((bool) result) p (output, "true"); else p (output, "false"); } else if (result is string){ p (output, String.Format ("\"{0}\"", EscapeString ((string)result))); } else if (result is IDictionary){ IDictionary dict = (IDictionary) result; int top = dict.Count, count = 0; p (output, "{"); foreach (DictionaryEntry entry in dict){ count++; p (output, "{ "); PrettyPrint (output, entry.Key); p (output, ", "); PrettyPrint (output, entry.Value); if (count != top) p (output, " }, "); else p (output, " }"); } p (output, "}"); } else if (WorksAsEnumerable (result)) { int i = 0; p (output, "{ "); foreach (object item in (IEnumerable) result) { if (i++ != 0) p (output, ", "); PrettyPrint (output, item); } p (output, " }"); } else if (result is char) { EscapeChar (output, (char) result); } else { p (output, result.ToString ()); } } public virtual int Run (string [] startup_files) { this.startup_files = startup_files; return ReadEvalPrintLoop (); } } #if !ON_DOTNET // // A shell connected to a CSharpAgent running in a remote process. // - maybe add 'class_name' and 'method_name' arguments to LoadAgent. // - Support Gtk and Winforms main loops if detected, this should // probably be done as a separate agent in a separate place. // class ClientCSharpShell : CSharpShell { NetworkStream ns, interrupt_stream; public ClientCSharpShell (Evaluator evaluator, int pid) : base (evaluator) { // Create a server socket we listen on whose address is passed to the agent TcpListener listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0)); listener.Start (); TcpListener interrupt_listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0)); interrupt_listener.Start (); string agent_assembly = typeof (ClientCSharpShell).Assembly.Location; string agent_arg = String.Format ("--agent:{0}:{1}" , ((IPEndPoint)listener.Server.LocalEndPoint).Port, ((IPEndPoint)interrupt_listener.Server.LocalEndPoint).Port); var vm = new Attach.VirtualMachine (pid); vm.Attach (agent_assembly, agent_arg); /* Wait for the client to connect */ TcpClient client = listener.AcceptTcpClient (); ns = client.GetStream (); TcpClient interrupt_client = interrupt_listener.AcceptTcpClient (); interrupt_stream = interrupt_client.GetStream (); Console.WriteLine ("Connected."); } // // A remote version of Evaluate // protected override string Evaluate (string input) { ns.WriteString (input); while (true) { AgentStatus s = (AgentStatus) ns.ReadByte (); switch (s){ case AgentStatus.PARTIAL_INPUT: return input; case AgentStatus.ERROR: string err = ns.GetString (); Console.Error.WriteLine (err); break; case AgentStatus.RESULT_NOT_SET: return null; case AgentStatus.RESULT_SET: string res = ns.GetString (); Console.WriteLine (res); return null; } } } public override int Run (string [] startup_files) { // The difference is that we do not call Evaluator.Init, that is done on the target this.startup_files = startup_files; return ReadEvalPrintLoop (); } protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a) { // Do not about our program a.Cancel = true; interrupt_stream.WriteByte (0); int c = interrupt_stream.ReadByte (); if (c != -1) Console.WriteLine ("Execution interrupted"); } } // // Stream helper extension methods // public static class StreamHelper { static DataConverter converter = DataConverter.LittleEndian; public static int GetInt (this Stream stream) { byte [] b = new byte [4]; if (stream.Read (b, 0, 4) != 4) throw new IOException ("End reached"); return converter.GetInt32 (b, 0); } public static string GetString (this Stream stream) { int len = stream.GetInt (); byte [] b = new byte [len]; if (stream.Read (b, 0, len) != len) throw new IOException ("End reached"); return Encoding.UTF8.GetString (b); } public static void WriteInt (this Stream stream, int n) { byte [] bytes = converter.GetBytes (n); stream.Write (bytes, 0, bytes.Length); } public static void WriteString (this Stream stream, string s) { stream.WriteInt (s.Length); byte [] bytes = Encoding.UTF8.GetBytes (s); stream.Write (bytes, 0, bytes.Length); } } public enum AgentStatus : byte { // Received partial input, complete PARTIAL_INPUT = 1, // The result was set, expect the string with the result RESULT_SET = 2, // No result was set, complete RESULT_NOT_SET = 3, // Errors and warnings string follows ERROR = 4, } // // This is the agent loaded into the target process when using --attach. // class CSharpAgent { NetworkStream interrupt_stream; readonly Evaluator evaluator; TextWriter stderr; public CSharpAgent (Evaluator evaluator, String arg, TextWriter stderr) { this.evaluator = evaluator; this.stderr = stderr; new Thread (new ParameterizedThreadStart (Run)).Start (arg); } public void InterruptListener () { while (true){ int b = interrupt_stream.ReadByte(); if (b == -1) return; evaluator.Interrupt (); interrupt_stream.WriteByte (0); } } public void Run (object o) { string arg = (string)o; string ports = arg.Substring (8); int sp = ports.IndexOf (':'); int port = Int32.Parse (ports.Substring (0, sp)); int interrupt_port = Int32.Parse (ports.Substring (sp+1)); Console.WriteLine ("csharp-agent: started, connecting to localhost:" + port); TcpClient client = new TcpClient ("127.0.0.1", port); TcpClient interrupt_client = new TcpClient ("127.0.0.1", interrupt_port); Console.WriteLine ("csharp-agent: connected."); NetworkStream s = client.GetStream (); interrupt_stream = interrupt_client.GetStream (); new Thread (InterruptListener).Start (); try { // Add all assemblies loaded later AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded; // Add all currently loaded assemblies foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) { // Some assemblies seem to be already loaded, and loading them again causes 'defined multiple times' errors if (a.GetName ().Name != "mscorlib" && a.GetName ().Name != "System.Core" && a.GetName ().Name != "System") evaluator.ReferenceAssembly (a); } RunRepl (s); } finally { AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoaded; client.Close (); interrupt_client.Close (); Console.WriteLine ("csharp-agent: disconnected."); } } void AssemblyLoaded (object sender, AssemblyLoadEventArgs e) { evaluator.ReferenceAssembly (e.LoadedAssembly); } public void RunRepl (NetworkStream s) { string input = null; while (!InteractiveBase.QuitRequested) { try { string error_string; StringWriter error_output = (StringWriter)stderr; string line = s.GetString (); bool result_set; object result; if (input == null) input = line; else input = input + "\n" + line; try { input = evaluator.Evaluate (input, out result, out result_set); } catch (Exception e) { s.WriteByte ((byte) AgentStatus.ERROR); s.WriteString (e.ToString ()); s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET); continue; } if (input != null){ s.WriteByte ((byte) AgentStatus.PARTIAL_INPUT); continue; } // Send warnings and errors back error_string = error_output.ToString (); if (error_string.Length != 0){ s.WriteByte ((byte) AgentStatus.ERROR); s.WriteString (error_output.ToString ()); error_output.GetStringBuilder ().Clear (); } if (result_set){ s.WriteByte ((byte) AgentStatus.RESULT_SET); StringWriter sr = new StringWriter (); CSharpShell.PrettyPrint (sr, result); s.WriteString (sr.ToString ()); } else { s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET); } } catch (IOException) { break; } catch (Exception e){ Console.WriteLine (e); } } } } public class UnixUtils { [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")] extern static int _isatty (int fd); public static bool isatty (int fd) { try { return _isatty (fd) == 1; } catch { return false; } } } #endif }
//----------------------------------------------------------------- // Evaluator // Copyright 2009-2012 MrJoy, Inc. // All rights reserved // //----------------------------------------------------------------- // Core evaluation loop, including environment handling for living in the Unity // editor and dealing with its code reloading behaviors. //----------------------------------------------------------------- using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using System.IO; using Mono.CSharp; class EvaluationHelper { private StringWriter reportWriter = new StringWriter(); public EvaluationHelper() { StringBuilder buffer = FluffReporter(); TryLoadingAssemblies(); buffer.Length = 0; } protected StringBuilder FluffReporter() { if(Report.Stderr is StringWriter) { // In case the brutal assembly reloading Unity does caused an old instance // of our StringWriter to stick around, we resurrect it to avoid the // chance that someone's holding a reference to it and writing to THAT // instead of what we assign to Report.Stderr. reportWriter = (StringWriter)Report.Stderr; } Report.Stderr = reportWriter; // Commenting this out to see if we can reliably get ONLY output from the // compiler... //InteractiveBase.Error = reportWriter; //InteractiveBase.Output = reportWriter; return reportWriter.GetStringBuilder(); } protected void TryLoadingAssemblies() { foreach(Assembly b in AppDomain.CurrentDomain.GetAssemblies()) { string assemblyShortName = b.GetName().Name; if(!(assemblyShortName.StartsWith("Mono.CSharp") || assemblyShortName.StartsWith("UnityDomainLoad") || assemblyShortName.StartsWith("interactive"))) { //System.Console.WriteLine("Giving Mono.CSharp a reference to " + assemblyShortName); Evaluator.ReferenceAssembly(b); } } // These won't work the first time through after an assembly reload. No // clue why, but the Unity* namespaces don't get found. Perhaps they're // being loaded into our AppDomain asynchronously and just aren't done yet? // Regardless, attempting to hit them early and then trying again later // seems to work fine. Evaluator.Run("using System;"); Evaluator.Run("using System.IO;"); Evaluator.Run("using System.Linq;"); Evaluator.Run("using System.Collections;"); Evaluator.Run("using System.Collections.Generic;"); Evaluator.Run("using UnityEditor;"); Evaluator.Run("using UnityEngine;"); } public bool Init(ref bool isInitialized) { // Don't be executing code when we're about to reload it. Not sure this is // actually needed but seems prudent to be wary of it. if(EditorApplication.isCompiling) return false; StringBuilder buffer = FluffReporter(); buffer.Length = 0; /* We need to tell the evaluator to reference stuff we care about. Since there's a lot of dynamically named stuff that we might want, we just pull the list of loaded assemblies and include them "all" (with the exception of a couple that I have a sneaking suspicion may be bad to reference -- noted below). Examples of what we might get when asking the current AppDomain for all assemblies (short names only): Stuff we avoid: UnityDomainLoad <-- Unity gubbins. Probably want to avoid this. Mono.CSharp <-- The self-same package used to pull this off. Probably safe, but not taking any chances. interactive0 <-- Looks like what Mono.CSharp is making on the fly. If we load those, it APPEARS we may wind up holding onto them 'forever', so... Don't even try. Mono runtime, which we probably get 'for free', but include just in case: System mscorlib Unity runtime, which we definitely want: UnityEditor UnityEngine UnityScript.Lang Boo.Lang The assemblies Unity generated from our project code, and whose names we can't predict (thus all this headache of doing this dynamically): 66e7989537eed4bf0b3da7923cca36a5 3355ac06262db4cc485a4df3f5d80f92 056b51e0f06e443768d0eec4b9a4e6c0 bb4826d22f7064220b2889d64c02fea6 5025cb470ec5941b9b5afef2b57be7d4 78b446ec0e1c748e3ba1927569415c6a */ bool retVal = false; if(!isInitialized) { TryLoadingAssemblies(); if(buffer.Length > 0) { // Whoops! Something didn't go right! //Console.WriteLine("Got some (hopefully transient) static while initializing:"); //Console.WriteLine(buffer); buffer.Length = 0; retVal = false; } else { isInitialized = true; retVal = true; } } else { retVal = true; } if(retVal) { if(Evaluator.InteractiveBaseClass != typeof(UnityBaseClass)) Evaluator.InteractiveBaseClass = typeof(UnityBaseClass); } return retVal; } private StringBuilder outputBuffer = new StringBuilder(); public bool Eval(List<LogEntry> logEntries, string code) { EditorApplication.LockReloadAssemblies(); bool status = false; bool hasOutput = false; object output = null; LogEntry cmdEntry = null; string tmpCode = code.Trim(); cmdEntry = new LogEntry() { logEntryType = LogEntryType.Command, command = tmpCode }; bool isExpression = false; try { if(tmpCode.StartsWith("=")) { tmpCode = "(" + tmpCode.Substring(1, tmpCode.Length-1) + ");"; isExpression = true; } Application.RegisterLogCallback(delegate(string cond, string sTrace, LogType lType) { cmdEntry.Add(new LogEntry() { logEntryType = LogEntryType.ConsoleLog, condition = cond, stackTrace = sTrace, consoleLogType = lType }); }); status = Evaluator.Evaluate(tmpCode, out output, out hasOutput) == null; if(status) logEntries.Add(cmdEntry); } catch(Exception e) { cmdEntry.Add(new LogEntry() { logEntryType = LogEntryType.EvaluationError, error = e.ToString().Trim() // TODO: Produce a stack trace a la Debug, and put it in stackTrace so we can filter it. }); output = new Evaluator.NoValueSet(); hasOutput = false; status = true; // Need this to avoid 'stickiness' where we let user // continue editing due to incomplete code. logEntries.Add(cmdEntry); } finally { Application.RegisterLogCallback(null); } // Catch compile errors that are not dismissed as a product of interactive // editing by Mono.CSharp.Evaluator... StringBuilder buffer = FluffReporter(); string tmp = buffer.ToString().Trim(); buffer.Length = 0; if(!String.IsNullOrEmpty(tmp)) { cmdEntry.Add(new LogEntry() { logEntryType = LogEntryType.SystemConsole, error = tmp }); status = false; } if(hasOutput && (isExpression || output is REPLMessage)) { if(status) { outputBuffer.Length = 0; PrettyPrint.PP(outputBuffer, output); cmdEntry.Add(new LogEntry() { logEntryType = LogEntryType.Output, output = outputBuffer.ToString().Trim() }); } } EditorApplication.UnlockReloadAssemblies(); return status; } } // WARNING: Absolutely NOT thread-safe! internal class EvaluatorProxy : ReflectionProxy { private static readonly Type _Evaluator = typeof(Evaluator); private static readonly FieldInfo _fields = _Evaluator.GetField("fields", NONPUBLIC_STATIC); internal static Hashtable fields { get { return (Hashtable)_fields.GetValue(null); } } } // WARNING: Absolutely NOT thread-safe! internal class TypeManagerProxy : ReflectionProxy { private static readonly Type _TypeManager = typeof(Evaluator).Assembly.GetType("Mono.CSharp.TypeManager"); private static readonly MethodInfo _CSharpName = _TypeManager.GetMethod("CSharpName", PUBLIC_STATIC, null, Signature(typeof(Type)), null); // Save an allocation per access here... private static readonly object[] _CSharpNameParams = new object[] { null }; internal static string CSharpName(Type t) { // TODO: What am I doing wrong here that this throws on generics?? string name = ""; try { _CSharpNameParams[0] = t; name = (string)_CSharpName.Invoke(null, _CSharpNameParams); } catch(Exception) { name = "?"; } return name; } } // Dummy class so we can output a string and bypass pretty-printing of it. public struct REPLMessage { public string msg; public REPLMessage(string m) { msg = m; } } public class UnityBaseClass { private static readonly REPLMessage _help = new REPLMessage(@"UnityREPL v." + Shell.VERSION + @": help; -- This screen; help for helper commands. Click the '?' icon on the toolbar for more comprehensive help. vars; -- Show the variables you've created this session, and their current values. "); public static REPLMessage help { get { return _help; } } public static REPLMessage vars { get { Hashtable fields = EvaluatorProxy.fields; StringBuilder tmp = new StringBuilder(); // TODO: Sort this list... foreach(DictionaryEntry kvp in fields) { FieldInfo field = (FieldInfo)kvp.Value; tmp .Append(TypeManagerProxy.CSharpName(field.FieldType)) .Append(" ") .Append(kvp.Key) .Append(" = "); PrettyPrint.PP(tmp, field.GetValue(null)); tmp.Append(";\n"); } return new REPLMessage(tmp.ToString()); } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq { internal class JPath { private readonly string _expression; public List<object> Parts { get; private set; } private int _currentIndex; public JPath(string expression) { ValidationUtils.ArgumentNotNull(expression, "expression"); _expression = expression; Parts = new List<object>(); ParseMain(); } private void ParseMain() { int currentPartStartIndex = _currentIndex; bool followingIndexer = false; while (_currentIndex < _expression.Length) { char currentChar = _expression[_currentIndex]; switch (currentChar) { case '[': case '(': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } ParseIndexer(currentChar); currentPartStartIndex = _currentIndex + 1; followingIndexer = true; break; case ']': case ')': throw new JsonException("Unexpected character while parsing path: " + currentChar); case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } currentPartStartIndex = _currentIndex + 1; followingIndexer = false; break; default: if (followingIndexer) throw new JsonException("Unexpected character following indexer: " + currentChar); break; } _currentIndex++; } if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); Parts.Add(member); } } private void ParseIndexer(char indexerOpenChar) { _currentIndex++; char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; int indexerStart = _currentIndex; int indexerLength = 0; bool indexerClosed = false; while (_currentIndex < _expression.Length) { char currentCharacter = _expression[_currentIndex]; if (char.IsDigit(currentCharacter)) { indexerLength++; } else if (currentCharacter == indexerCloseChar) { indexerClosed = true; break; } else { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } _currentIndex++; } if (!indexerClosed) throw new JsonException("Path ended with open indexer. Expected " + indexerCloseChar); if (indexerLength == 0) throw new JsonException("Empty path indexer."); string indexer = _expression.Substring(indexerStart, indexerLength); Parts.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); } internal JToken Evaluate(JToken root, bool errorWhenNoMatch) { JToken current = root; foreach (object part in Parts) { string propertyName = part as string; if (propertyName != null) { JObject o = current as JObject; if (o != null) { current = o[propertyName]; if (current == null && errorWhenNoMatch) throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } else { if (errorWhenNoMatch) throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name)); return null; } } else { int index = (int) part; JArray a = current as JArray; JConstructor c = current as JConstructor; if (a != null) { if (a.Count <= index) { if (errorWhenNoMatch) throw new JsonException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); return null; } current = a[index]; } else if (c != null) { if (c.Count <= index) { if (errorWhenNoMatch) throw new JsonException("Index {0} outside the bounds of JConstructor.".FormatWith(CultureInfo.InvariantCulture, index)); return null; } current = c[index]; } else { if (errorWhenNoMatch) throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name)); return null; } } } return current; } } } #endif
#region License /* * Copyright (C) 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using Java.Util.Concurrent.Helpers; namespace Java.Util.Concurrent { /// <summary> /// An optionally-bounded <see cref="IBlockingQueue{T}"/> based on /// linked nodes. /// </summary> /// <remarks> /// <para> /// This queue orders elements FIFO (first-in-first-out). /// The <b>head</b> of the queue is that element that has been on the /// queue the longest time. /// The <b>tail</b> of the queue is that element that has been on the /// queue the shortest time. New elements /// are inserted at the tail of the queue, and the queue retrieval /// operations obtain elements at the head of the queue. /// Linked queues typically have higher throughput than array-based queues but /// less predictable performance in most concurrent applications. /// </para> /// <para> /// The optional capacity bound constructor argument serves as a /// way to prevent excessive queue expansion. The capacity, if unspecified, /// is equal to <see cref="System.Int32.MaxValue"/>. Linked nodes are /// dynamically created upon each insertion unless this would bring the /// queue above capacity. /// </para> /// </remarks> /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> [Serializable] public class LinkedBlockingQueue<T> : AbstractBlockingQueue<T>, ISerializable //BACKPORT_3_1 { #region inner classes internal class Node { internal T Item; internal Node Next; internal Node(T x) { Item = x; } } #endregion #region private fields /// <summary>The capacity bound, or <see cref="int.MaxValue"/> if none </summary> private readonly int _capacity; /// <summary>Current number of elements </summary> [NonSerialized] private volatile int _activeCount; [NonSerialized] private volatile bool _isBroken; /// <summary>Head of linked list </summary> [NonSerialized] private Node _head; /// <summary>Tail of linked list </summary> [NonSerialized] private Node _last; /// <summary>Lock held by take, poll, etc </summary> [NonSerialized] private readonly object _takeLock = new object(); /// <summary>Lock held by put, offer, etc </summary> [NonSerialized] private readonly object _putLock = new object(); #endregion #region ctors /// <summary> Creates a <see cref="LinkedBlockingQueue{T}"/> with a capacity of /// <see cref="System.Int32.MaxValue"/>. /// </summary> public LinkedBlockingQueue() : this(Int32.MaxValue) { } /// <summary> Creates a <see cref="LinkedBlockingQueue{T}"/> with the given (fixed) capacity.</summary> /// <param name="capacity">the capacity of this queue</param> /// <exception cref="System.ArgumentException">if the <paramref name="capacity"/> is not greater than zero.</exception> public LinkedBlockingQueue(int capacity) { if(capacity <= 0) throw new ArgumentOutOfRangeException( "capacity", capacity, "Capacity must be positive integer."); _capacity = capacity; _last = _head = new Node(default(T)); } /// <summary> Creates a <see cref="LinkedBlockingQueue{T}"/> with a capacity of /// <see cref="System.Int32.MaxValue"/>, initially containing the elements o)f the /// given collection, added in traversal order of the collection's iterator. /// </summary> /// <param name="collection">the collection of elements to initially contain</param> /// <exception cref="System.ArgumentNullException">if the collection or any of its elements are null.</exception> /// <exception cref="System.ArgumentException">if the collection size exceeds the capacity of this queue.</exception> public LinkedBlockingQueue(ICollection<T> collection) : this(Int32.MaxValue) { if(collection == null) { throw new ArgumentNullException("collection", "must not be null."); } int count = 0; foreach (var item in collection) { Insert(item); count++; // we must count ourselves, as collection can change. } _activeCount = count; } /// <summary> Reconstitute this queue instance from a stream (that is, /// deserialize it). /// </summary> /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param> protected LinkedBlockingQueue(SerializationInfo info, StreamingContext context) { SerializationUtilities.DefaultReadObject(info, context, this); _last = _head = new Node(default(T)); T[] items = (T[]) info.GetValue("Data", typeof (T[])); foreach (var item in items) Insert(item); _activeCount = items.Length; } #endregion #region ISerializable Members /// <summary> ///Populates a <see cref="System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { lock(_putLock) { lock(_takeLock) { SerializationUtilities.DefaultWriteObject(info, context, this); info.AddValue("Data", ToArray()); } } } #endregion #region base class overrides /// <summary> /// Inserts the specified element into this queue, waiting if necessary /// for space to become available. /// </summary> /// <param name="element">the element to add</param> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> /// <exception cref="QueueBrokenException"> /// If the queue is already <see cref="IsBroken">closed</see>. /// </exception> public override void Put(T element) { if(!TryPut(element)) throw new QueueBrokenException(); } /// <summary> /// Inserts the specified element into this queue, waiting if necessary /// for space to become available. /// </summary> /// <remarks> /// <see cref="Break"/> the queue will cause a waiting <see cref="TryPut"/> /// to returned <c>false</c>. This is very useful to indicate that the /// consumer is stopped or going to stop so that the producer should not /// put more items into the queue. /// </remarks> /// <param name="element">the element to add</param> /// <returns> /// <c>true</c> if succesfully and <c>false</c> if queue <see cref="IsBroken"/>. /// </returns> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> public virtual bool TryPut(T element) { int tempCount; lock (_putLock) { /* * Note that count is used in wait guard even though it is * not protected by lock. This works because count can * only decrease at this point (all other puts are shut * out by lock), and we (or some other waiting put) are * signaled if it ever changes from capacity. Similarly * for all other uses of count in other wait guards. */ if (_isBroken) return false; try { while(_activeCount == _capacity) { Monitor.Wait(_putLock); if (_isBroken) return false; } } catch(ThreadInterruptedException e) { Monitor.Pulse(_putLock); throw SystemExtensions.PreserveStackTrace(e); } Insert(element); lock(this) { tempCount = _activeCount++; } if(tempCount + 1 < _capacity) Monitor.Pulse(_putLock); } if(tempCount == 0) SignalNotEmpty(); return true; } /// <summary> /// Inserts the specified element into this queue, waiting up to the /// specified wait time if necessary for space to become available. /// </summary> /// <param name="element">the element to add</param> /// <param name="duration">how long to wait before giving up</param> /// <returns> <c>true</c> if successful, or <c>false</c> if /// the specified waiting time elapses before space is available /// </returns> /// <exception cref="System.InvalidOperationException"> /// If the element cannot be added at this time due to capacity restrictions. /// </exception> /// <exception cref="ThreadInterruptedException"> /// if interrupted while waiting. /// </exception> public override bool Offer(T element, TimeSpan duration) { DateTime deadline = WaitTime.Deadline(duration); int tempCount; lock(_putLock) { for(; ; ) { if (_isBroken) return false; if (_activeCount < _capacity) { Insert(element); lock(this) { tempCount = _activeCount++; } if(tempCount + 1 < _capacity) Monitor.Pulse(_putLock); break; } if (duration.Ticks <= 0) return false; try { Monitor.Wait(_putLock, WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch(ThreadInterruptedException e) { Monitor.Pulse(_putLock); throw SystemExtensions.PreserveStackTrace(e); } } } if(tempCount == 0) SignalNotEmpty(); return true; } /// <summary> /// Inserts the specified element into this queue if it is possible to do /// so immediately without violating capacity restrictions. /// </summary> /// <remarks> /// When using a capacity-restricted queue, this method is generally /// preferable to <see cref="AbstractQueue{T}.Add(T)"/>, /// which can fail to insert an element only by throwing an exception. /// </remarks> /// <param name="element"> /// The element to add. /// </param> /// <returns> /// <c>true</c> if the element was added to this queue. /// </returns> public override bool Offer(T element) { if(_activeCount == _capacity || _isBroken) return false; int tempCount = -1; lock(_putLock) { if(_activeCount < _capacity && !_isBroken) { Insert(element); lock(this) { tempCount = _activeCount++; } if(tempCount + 1 < _capacity) Monitor.Pulse(_putLock); } } if(tempCount == 0) SignalNotEmpty(); return tempCount >= 0; } /// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until an element becomes available. /// </summary> /// <returns> the head of this queue</returns> /// <exception cref="QueueBrokenException"> /// If the queue is empty and already <see cref="IsBroken">closed</see>. /// </exception> public override T Take() { T x; if (!TryTake(out x)) throw new QueueBrokenException(); return x; } /// <summary> /// Retrieves and removes the head of this queue, waiting if necessary /// until an element becomes available. /// </summary> /// <remarks> /// <see cref="Break"/> the queue will cause a waiting <see cref="TryTake"/> /// to returned <c>false</c>. This is very useful to indicate that the /// producer is stopped so that the producer should stop waiting for /// element from queu. /// </remarks> /// <param name="element"> /// The head of this queue if successful. /// </param> /// <returns> /// <c>true</c> if succesfully and <c>false</c> if queue is empty and /// <see cref="IsBroken">closed</see>. /// </returns> public virtual bool TryTake(out T element) { T x; int tempCount; lock(_takeLock) { try { while(_activeCount == 0) { if (_isBroken) { element = default(T); return false; } Monitor.Wait(_takeLock); } } catch(ThreadInterruptedException e) { Monitor.Pulse(_takeLock); throw SystemExtensions.PreserveStackTrace(e); } x = Extract(); lock(this) { tempCount = _activeCount--; } if(tempCount > 1) Monitor.Pulse(_takeLock); } if(tempCount == _capacity) SignalNotFull(); element = x; return true; } /// <summary> /// Retrieves and removes the head of this queue, waiting up to the /// specified wait time if necessary for an element to become available. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <param name="duration">How long to wait before giving up.</param> /// <returns> /// <c>false</c> if the queue is still empty after waited for the time /// specified by the <paramref name="duration"/>. Otherwise <c>true</c>. /// </returns> public override bool Poll(TimeSpan duration, out T element) { DateTime deadline = WaitTime.Deadline(duration); T x; int c; lock(_takeLock) { for(; ; ) { if(_activeCount > 0) { x = Extract(); lock(this) { c = _activeCount--; } if(c > 1) Monitor.Pulse(_takeLock); break; } if (duration.Ticks <= 0 || _isBroken) { element = default(T); return false; } try { Monitor.Wait(_takeLock, WaitTime.Cap(duration)); duration = deadline.Subtract(DateTime.UtcNow); } catch(ThreadInterruptedException e) { Monitor.Pulse(_takeLock); throw SystemExtensions.PreserveStackTrace(e); } } } if(c == _capacity) SignalNotFull(); element = x; return true; } /// <summary> /// Retrieves and removes the head of this queue into out parameter /// <paramref name="element"/>. /// </summary> /// <param name="element"> /// Set to the head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <returns> /// <c>false</c> if the queue is empty. Otherwise <c>true</c>. /// </returns> public override bool Poll(out T element) { if(_activeCount == 0) { element = default(T); return false; } T x = default(T); int c = -1; lock(_takeLock) { if(_activeCount > 0) { x = Extract(); lock(this) { c = _activeCount--; } if(c > 1) Monitor.Pulse(_takeLock); } } if(c == _capacity) { SignalNotFull(); } element = x; return c >= 0; } /// <summary> /// Retrieves, but does not remove, the head of this queue into out /// parameter <paramref name="element"/>. /// </summary> /// <param name="element"> /// The head of this queue. <c>default(T)</c> if queue is empty. /// </param> /// <returns> /// <c>false</c> is the queue is empty. Otherwise <c>true</c>. /// </returns> public override bool Peek(out T element) { if(_activeCount == 0) { element = default(T); return false; } lock(_takeLock) { Node first = _head.Next; bool exists = first != null; element = exists ? first.Item : default(T); return exists; } } /// <summary> /// Removes a single instance of the specified element from this queue, /// if it is present. /// </summary> /// <remarks> /// If this queue contains one or more such elements. /// Returns <c>true</c> if this queue contained the specified element /// (or equivalently, if this queue changed as a result of the call). /// </remarks> /// <param name="objectToRemove">element to be removed from this queue, if present</param> /// <returns><c>true</c> if this queue changed as a result of the call</returns> public override bool Remove(T objectToRemove) { bool removed = false; lock(_putLock) { lock(_takeLock) { Node trail = _head; Node p = _head.Next; while(p != null) { if(Equals(objectToRemove, p.Item)) { removed = true; break; } trail = p; p = p.Next; } if(removed) { p.Item = default(T); trail.Next = p.Next; if(_last == p) _last = trail; lock(this) { if(_activeCount-- == _capacity) Monitor.PulseAll(_putLock); } } } } return removed; } /// <summary> /// Returns the number of additional elements that this queue can ideally /// (in the absence of memory or resource constraints) accept without /// blocking. This is always equal to the initial capacity of this queue /// minus the current <see cref="LinkedBlockingQueue{T}.Count"/> of this queue. /// </summary> /// <remarks> /// Note that you <b>cannot</b> always tell if an attempt to insert /// an element will succeed by inspecting <see cref="LinkedBlockingQueue{T}.RemainingCapacity"/> /// because it may be the case that another thread is about to /// insert or remove an element. /// </remarks> public override int RemainingCapacity { get { return _capacity == int.MaxValue ? int.MaxValue : _capacity - _activeCount; } } /// <summary> /// Does the real work for the <see cref="AbstractQueue{T}.Drain(System.Action{T})"/> /// and <see cref="AbstractQueue{T}.Drain(System.Action{T},Predicate{T})"/>. /// </summary> protected internal override int DoDrain(Action<T> action, Predicate<T> criteria) { if (criteria!=null) { return DoDrain(action, int.MaxValue, criteria); } Node first; lock(_putLock) { lock(_takeLock) { first = _head.Next; _head.Next = null; _last = _head; int cold; lock(this) { cold = _activeCount; _activeCount = 0; } if(cold == _capacity) Monitor.PulseAll(_putLock); } } // Transfer the elements outside of locks int n = 0; for(Node p = first; p != null; p = p.Next) { action(p.Item); p.Item = default(T); ++n; } return n; } /// <summary> /// Does the real work for all drain methods. Caller must /// guarantee the <paramref name="action"/> is not <c>null</c> and /// <paramref name="maxElements"/> is greater then zero (0). /// </summary> /// <seealso cref="IQueue{T}.Drain(System.Action{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int)"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, Predicate{T})"/> /// <seealso cref="IQueue{T}.Drain(System.Action{T}, int, Predicate{T})"/> internal protected override int DoDrain(Action<T> action, int maxElements, Predicate<T> criteria) { lock(_putLock) { lock(_takeLock) { int n = 0; Node p = _head; Node c = p.Next; while(c != null && n < maxElements) { if (criteria == null || criteria(c.Item)) { action(c.Item); c.Item = default(T); p.Next = c.Next; ++n; } else { p = c; } c = c.Next; } if(n != 0) { if(c == null) _last = p; int cold; lock(this) { cold = _activeCount; _activeCount -= n; } if(cold == _capacity) Monitor.PulseAll(_putLock); } return n; } } } /// <summary> /// Gets the capacity of this queue. /// </summary> public override int Capacity { get { return _capacity; } } /// <summary> /// Does the actual work of copying to array. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the /// destination of the elements copied from <see cref="ICollection{T}"/>. /// The <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in array at which copying begins. /// </param> /// <param name="ensureCapacity"> /// If is <c>true</c>, calls <see cref="AbstractCollection{T}.EnsureCapacity"/> /// </param> /// <returns> /// A new array of same runtime type as <paramref name="array"/> if /// <paramref name="array"/> is too small to hold all elements and /// <paramref name="ensureCapacity"/> is <c>false</c>. Otherwise /// the <paramref name="array"/> instance itself. /// </returns> protected override T[] DoCopyTo(T[] array, int arrayIndex, bool ensureCapacity) { lock(_putLock) { lock(_takeLock) { if (ensureCapacity) array = EnsureCapacity(array, _activeCount); for (Node p = _head.Next; p != null; p = p.Next) array[arrayIndex++] = p.Item; return array; } } } /// <summary> /// Gets the count of the queue. /// </summary> public override int Count { get { return _activeCount; } } /// <summary> /// test whether the queue contains <paramref name="item"/> /// </summary> /// <param name="item">the item whose containement should be checked</param> /// <returns><c>true</c> if item is in the queue, <c>false</c> otherwise</returns> public override bool Contains(T item) { lock (_putLock) { lock (_takeLock) { for (Node p = _head.Next; p!=null; p = p.Next) { if (Equals(item, p.Item)) return true; } } } return false; } #endregion /// <summary> /// Indicate if current queue is broken. A broken queue never blocks. /// </summary> /// <para> /// When a queue is broken, all blocking actions and subsequent put /// actions will return immediately with unsuccesful status or /// <see cref="QueueBrokenException"/> is thrown if method doesn't /// return any status. Subsequent get actions will continue to sucess /// until the queue becomes empty, then further get actions will return /// unsuccesful status or throws <see cref="QueueBrokenException"/>. /// </para> /// <para> /// Use <see cref="Break"/> or <see cref="Stop"/> to break a queue. /// </para> /// <para> /// Use <see cref="Clear"/> to restore the queue back to normal state. /// </para> /// <seealso cref="Break"/> /// <seealso cref="Stop"/> /// <seealso cref="Clear"/> public virtual bool IsBroken { get { return _isBroken; } } /// <summary> /// Breaks current queue. /// </summary> /// <remarks> /// <para> /// When a queue is broken, all blocking actions and subsequent put /// actions will return immediately with unsuccesful status or /// <see cref="QueueBrokenException"/> is thrown if method doesn't /// return any status. Subsequent get actions will continue to sucess /// until the queue becomes empty. /// </para> /// <para> /// <see cref="Break"/> allows remaining elements in the queue to /// be consumed by subsequent get actions. Use <see cref="Stop"/> /// to break and clear the queue in the same time, which effectively /// ensures any subsequent get action to fail. /// </para> /// <para> /// Use <see cref="Clear"/> to restore the queue back to normal state. /// </para> /// </remarks> /// <seealso cref="IsBroken"/> /// <seealso cref="Stop"/> /// <seealso cref="Clear"/> public virtual void Break() { if (_isBroken) return; lock (_putLock) { lock (_takeLock) { _isBroken = true; Monitor.PulseAll(_putLock); Monitor.PulseAll(_takeLock); } } } /// <summary> /// <see cref="Break"/>s and empties current queue. /// </summary> /// <remarks> /// <para> /// As soon as a queue is stopped, all blocking queue modification /// actions return immediately with unsuccesful status or /// <see cref="QueueBrokenException"/> is thrown if method doesn't /// return any status. So do any subsequent queue modification /// actions. /// </para> /// <para> /// Use <see cref="Break"/> to only affect put operations but allowing /// get operations to continue untile queue is empty. /// </para> /// <para> /// Use <see cref="Clear"/> to restore the queue back to normal state. /// </para> /// </remarks> /// <seealso cref="Break"/> /// <seealso cref="IsBroken"/> /// <seealso cref="Clear"/> public virtual void Stop() { EmptyQueue(true); } /// <summary> /// Returns a string representation of this colleciton. /// </summary> /// <returns>String representation of the elements of this collection.</returns> public override string ToString() { lock(_putLock) { lock(_takeLock) { return base.ToString(); } } } /// <summary> /// Removes all of the elements from this queue and reopen the queue if /// it was closed. /// </summary> /// <remarks> /// <p> /// The queue will be empty after this call returns. /// </p> /// </remarks> public override void Clear() { EmptyQueue(false); } #region IEnumerable Members /// <summary> /// Returns an <see cref="IEnumerator{T}"/> over the elements in this /// queue in proper sequence. /// </summary> /// <remarks> /// The returned <see cref="IEnumerator{T}"/> is a "weakly consistent" /// enumerator that will not throw <see cref="InvalidOperationException"/> /// when the queue is concurrently modified, and guarantees to traverse /// elements as they existed upon construction of the enumerator, and /// may (but is not guaranteed to) reflect any modifications subsequent /// to construction. /// </remarks> /// <returns> /// An enumerator over the elements in this queue in proper sequence. /// </returns> public override IEnumerator<T> GetEnumerator() { return new LinkedBlockingQueueEnumerator(this); } /// <summary> /// Internal enumerator class /// </summary> private class LinkedBlockingQueueEnumerator : AbstractEnumerator<T> { private readonly LinkedBlockingQueue<T> _queue; private Node _currentNode; private T _currentElement; internal LinkedBlockingQueueEnumerator(LinkedBlockingQueue<T> queue) { _queue = queue; lock(_queue._putLock) { lock(_queue._takeLock) { _currentNode = _queue._head; } } } protected override T FetchCurrent() { return _currentElement; } protected override bool GoNext() { lock (_queue._putLock) { lock (_queue._takeLock) { _currentNode = _currentNode.Next; if (_currentNode == null) return false; _currentElement = _currentNode.Item; return true; } } } protected override void DoReset() { lock(_queue._putLock) { lock(_queue._takeLock) { _currentNode = _queue._head; } } } } #endregion #region Private Methods private void EmptyQueue(bool @break) { lock (_putLock) { lock (_takeLock) { _head.Next = null; _last = _head; int c; lock (this) { c = _activeCount; _activeCount = 0; } bool pulsePut = (c == _capacity); if (_isBroken != @break) { _isBroken = @break; if(@break) { Monitor.PulseAll(_takeLock); pulsePut = true; } } if (pulsePut) Monitor.PulseAll(_putLock); } } } /// <summary> /// Signals a waiting take. Called only from put/offer (which do not /// otherwise ordinarily lock _takeLock.) /// </summary> private void SignalNotEmpty() { lock (_takeLock) { Monitor.Pulse(_takeLock); } } /// <summary> Signals a waiting put. Called only from take/poll.</summary> private void SignalNotFull() { lock (_putLock) { Monitor.Pulse(_putLock); } } /// <summary> /// Creates a node and links it at end of queue.</summary> /// <param name="x">the item to insert</param> private void Insert(T x) { _last = _last.Next = new Node(x); } /// <summary>Removes a node from head of queue,</summary> /// <returns>the node</returns> private T Extract() { Node first = _head.Next; _head = first; T x = first.Item; first.Item = default(T); return x; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ /* * Created on May 14, 2005 * */ namespace NPOI.SS.Formula.Eval { using System; /** * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * */ internal class ValueEvalToNumericXlator { public static int STRING_IS_PARSED = 0x0001; public static int BOOL_IS_PARSED = 0x0002; public static int BLANK_IS_PARSED = 0x0004; // => blanks are not ignored, Converted to 0 public static int REF_STRING_IS_PARSED = 0x0008; public static int REF_BOOL_IS_PARSED = 0x0010; public static int REF_BLANK_IS_PARSED = 0x0020; public static int STRING_IS_INVALID_VALUE = 0x0800; private int flags; public ValueEvalToNumericXlator(int flags) { this.flags = flags; } /** * returned value can be either A NumericValueEval, BlankEval or ErrorEval. * The params can be either NumberEval, BoolEval, StringEval, or * RefEval * @param eval */ public ValueEval AttemptXlateToNumeric(ValueEval eval) { ValueEval retval = null; if (eval == null) { retval = BlankEval.instance; } // most common case - least worries :) else if (eval is NumberEval) { retval = eval; } // booleval else if (eval is BoolEval) { retval = ((flags & BOOL_IS_PARSED) > 0) ? (NumericValueEval)eval : XlateBlankEval(BLANK_IS_PARSED); } // stringeval else if (eval is StringEval) { retval = XlateStringEval((StringEval)eval); // TODO: recursive call needed } // refeval else if (eval is RefEval) { retval = XlateRefEval((RefEval)eval); } // erroreval else if (eval is ErrorEval) { retval = eval; } else if (eval is BlankEval) { retval = XlateBlankEval(BLANK_IS_PARSED); } // probably AreaEval? then not acceptable. else { throw new Exception("Invalid ValueEval type passed for conversion: " + eval.GetType()); } return retval; } /** * no args are required since BlankEval has only one * instance. If flag is Set, a zero * valued numbereval is returned, else BlankEval.INSTANCE * is returned. */ private ValueEval XlateBlankEval(int flag) { return ((flags & flag) > 0) ? (ValueEval)NumberEval.ZERO : BlankEval.instance; } /** * uses the relevant flags to decode the supplied RefVal * @param eval */ private ValueEval XlateRefEval(RefEval reval) { ValueEval eval = reval.InnerValueEval; // most common case - least worries :) if (eval is NumberEval) { return eval; } if (eval is BoolEval) { return ((flags & REF_BOOL_IS_PARSED) > 0) ? (ValueEval)eval : BlankEval.instance; } if (eval is StringEval) { return XlateRefStringEval((StringEval)eval); } if (eval is ErrorEval) { return eval; } if (eval is BlankEval) { return XlateBlankEval(REF_BLANK_IS_PARSED); } throw new Exception("Invalid ValueEval type passed for conversion: (" + eval.GetType().Name + ")"); } /** * uses the relevant flags to decode the StringEval * @param eval */ private ValueEval XlateStringEval(StringEval eval) { if ((flags & STRING_IS_PARSED) > 0) { String s = eval.StringValue; double d = OperandResolver.ParseDouble(s); if (double.IsNaN(d)) { return ErrorEval.VALUE_INVALID; } return new NumberEval(d); } // strings are errors? if ((flags & STRING_IS_INVALID_VALUE) > 0) { return ErrorEval.VALUE_INVALID; } // ignore strings return XlateBlankEval(BLANK_IS_PARSED); } /** * uses the relevant flags to decode the StringEval * @param eval */ private ValueEval XlateRefStringEval(StringEval sve) { if ((flags & REF_STRING_IS_PARSED) > 0) { String s = sve.StringValue; double d = OperandResolver.ParseDouble(s); if (double.IsNaN(d)) { return ErrorEval.VALUE_INVALID; } return new NumberEval(d); } // strings are blanks return BlankEval.instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Reflection { public sealed partial class AmbiguousMatchException : System.Exception { public AmbiguousMatchException() { } public AmbiguousMatchException(string message) { } public AmbiguousMatchException(string message, System.Exception inner) { } } public abstract partial class Assembly { internal Assembly() { } public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } } public abstract System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo> DefinedTypes { get; } public virtual System.Collections.Generic.IEnumerable<System.Type> ExportedTypes { get { return default(System.Collections.Generic.IEnumerable<System.Type>); } } public virtual string FullName { get { return default(string); } } public virtual bool IsDynamic { get { return default(bool); } } public virtual System.Reflection.Module ManifestModule { get { return default(System.Reflection.Module); } } public abstract System.Collections.Generic.IEnumerable<System.Reflection.Module> Modules { get; } public override bool Equals(object o) { return default(bool); } public override int GetHashCode() { return default(int); } public virtual System.Reflection.ManifestResourceInfo GetManifestResourceInfo(string resourceName) { return default(System.Reflection.ManifestResourceInfo); } public virtual string[] GetManifestResourceNames() { return default(string[]); } public virtual System.IO.Stream GetManifestResourceStream(string name) { return default(System.IO.Stream); } public virtual System.Reflection.AssemblyName GetName() { return default(System.Reflection.AssemblyName); } public virtual System.Type GetType(string name) { return default(System.Type); } public virtual System.Type GetType(string name, bool throwOnError, bool ignoreCase) { return default(System.Type); } public static System.Reflection.Assembly Load(System.Reflection.AssemblyName assemblyRef) { return default(System.Reflection.Assembly); } public override string ToString() { return default(string); } } public enum AssemblyContentType { Default = 0, WindowsRuntime = 1, } public sealed partial class AssemblyName { public AssemblyName() { } public AssemblyName(string assemblyName) { } public System.Reflection.AssemblyContentType ContentType { get { return default(System.Reflection.AssemblyContentType); } set { } } public string CultureName { get { return default(string); } set { } } public System.Reflection.AssemblyNameFlags Flags { get { return default(System.Reflection.AssemblyNameFlags); } set { } } public string FullName { get { return default(string); } } public string Name { get { return default(string); } set { } } public System.Reflection.ProcessorArchitecture ProcessorArchitecture { get { return default(System.Reflection.ProcessorArchitecture); } set { } } public System.Version Version { get { return default(System.Version); } set { } } public byte[] GetPublicKey() { return default(byte[]); } public byte[] GetPublicKeyToken() { return default(byte[]); } public void SetPublicKey(byte[] publicKey) { } public void SetPublicKeyToken(byte[] publicKeyToken) { } public override string ToString() { return default(string); } } public abstract partial class ConstructorInfo : System.Reflection.MethodBase { public static readonly string ConstructorName; public static readonly string TypeConstructorName; internal ConstructorInfo() { } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public virtual object Invoke(object[] parameters) { return default(object); } } public partial class CustomAttributeData { internal CustomAttributeData() { } public virtual System.Type AttributeType { get { return default(System.Type); } } public virtual System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument> ConstructorArguments { get { return default(System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument>); } } public virtual System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument> NamedArguments { get { return default(System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument>); } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct CustomAttributeNamedArgument { public bool IsField { get { return default(bool); } } public string MemberName { get { return default(string); } } public System.Reflection.CustomAttributeTypedArgument TypedValue { get { return default(System.Reflection.CustomAttributeTypedArgument); } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct CustomAttributeTypedArgument { public System.Type ArgumentType { get { return default(System.Type); } } public object Value { get { return default(object); } } } public abstract partial class EventInfo : System.Reflection.MemberInfo { internal EventInfo() { } public virtual System.Reflection.MethodInfo AddMethod { get { return default(System.Reflection.MethodInfo); } } public abstract System.Reflection.EventAttributes Attributes { get; } public virtual System.Type EventHandlerType { get { return default(System.Type); } } public bool IsSpecialName { get { return default(bool); } } public virtual System.Reflection.MethodInfo RaiseMethod { get { return default(System.Reflection.MethodInfo); } } public virtual System.Reflection.MethodInfo RemoveMethod { get { return default(System.Reflection.MethodInfo); } } public virtual void AddEventHandler(object target, System.Delegate handler) { } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public virtual void RemoveEventHandler(object target, System.Delegate handler) { } } public abstract partial class FieldInfo : System.Reflection.MemberInfo { internal FieldInfo() { } public abstract System.Reflection.FieldAttributes Attributes { get; } public abstract System.Type FieldType { get; } public bool IsAssembly { get { return default(bool); } } public bool IsFamily { get { return default(bool); } } public bool IsFamilyAndAssembly { get { return default(bool); } } public bool IsFamilyOrAssembly { get { return default(bool); } } public bool IsInitOnly { get { return default(bool); } } public bool IsLiteral { get { return default(bool); } } public bool IsPrivate { get { return default(bool); } } public bool IsPublic { get { return default(bool); } } public bool IsSpecialName { get { return default(bool); } } public bool IsStatic { get { return default(bool); } } public override bool Equals(object obj) { return default(bool); } public static System.Reflection.FieldInfo GetFieldFromHandle(System.RuntimeFieldHandle handle) { return default(System.Reflection.FieldInfo); } public static System.Reflection.FieldInfo GetFieldFromHandle(System.RuntimeFieldHandle handle, System.RuntimeTypeHandle declaringType) { return default(System.Reflection.FieldInfo); } public override int GetHashCode() { return default(int); } public abstract object GetValue(object obj); public virtual void SetValue(object obj, object value) { } } public static partial class IntrospectionExtensions { public static System.Reflection.TypeInfo GetTypeInfo(this System.Type type) { return default(System.Reflection.TypeInfo); } } public partial interface IReflectableType { System.Reflection.TypeInfo GetTypeInfo(); } public partial class LocalVariableInfo { protected LocalVariableInfo() { } public virtual bool IsPinned { get { return default(bool); } } public virtual int LocalIndex { get { return default(int); } } public virtual System.Type LocalType { get { return default(System.Type); } } public override string ToString() { return default(string); } } public partial class ManifestResourceInfo { public ManifestResourceInfo(System.Reflection.Assembly containingAssembly, string containingFileName, System.Reflection.ResourceLocation resourceLocation) { } public virtual string FileName { get { return default(string); } } public virtual System.Reflection.Assembly ReferencedAssembly { get { return default(System.Reflection.Assembly); } } public virtual System.Reflection.ResourceLocation ResourceLocation { get { return default(System.Reflection.ResourceLocation); } } } public abstract partial class MemberInfo { internal MemberInfo() { } public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } } public abstract System.Type DeclaringType { get; } public virtual System.Reflection.Module Module { get { return default(System.Reflection.Module); } } public abstract string Name { get; } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } } public abstract partial class MethodBase : System.Reflection.MemberInfo { internal MethodBase() { } public abstract System.Reflection.MethodAttributes Attributes { get; } public virtual System.Reflection.CallingConventions CallingConvention { get { return default(System.Reflection.CallingConventions); } } public virtual bool ContainsGenericParameters { get { return default(bool); } } public bool IsAbstract { get { return default(bool); } } public bool IsAssembly { get { return default(bool); } } public bool IsConstructor { get { return default(bool); } } public bool IsFamily { get { return default(bool); } } public bool IsFamilyAndAssembly { get { return default(bool); } } public bool IsFamilyOrAssembly { get { return default(bool); } } public bool IsFinal { get { return default(bool); } } public virtual bool IsGenericMethod { get { return default(bool); } } public virtual bool IsGenericMethodDefinition { get { return default(bool); } } public bool IsHideBySig { get { return default(bool); } } public bool IsPrivate { get { return default(bool); } } public bool IsPublic { get { return default(bool); } } public bool IsSpecialName { get { return default(bool); } } public bool IsStatic { get { return default(bool); } } public bool IsVirtual { get { return default(bool); } } public abstract System.Reflection.MethodImplAttributes MethodImplementationFlags { get; } public override bool Equals(object obj) { return default(bool); } public virtual System.Type[] GetGenericArguments() { return default(System.Type[]); } public override int GetHashCode() { return default(int); } public static System.Reflection.MethodBase GetMethodFromHandle(System.RuntimeMethodHandle handle) { return default(System.Reflection.MethodBase); } public static System.Reflection.MethodBase GetMethodFromHandle(System.RuntimeMethodHandle handle, System.RuntimeTypeHandle declaringType) { return default(System.Reflection.MethodBase); } public abstract System.Reflection.ParameterInfo[] GetParameters(); public virtual object Invoke(object obj, object[] parameters) { return default(object); } } public abstract partial class MethodInfo : System.Reflection.MethodBase { internal MethodInfo() { } public virtual System.Reflection.ParameterInfo ReturnParameter { get { return default(System.Reflection.ParameterInfo); } } public virtual System.Type ReturnType { get { return default(System.Type); } } public virtual System.Delegate CreateDelegate(System.Type delegateType) { return default(System.Delegate); } public virtual System.Delegate CreateDelegate(System.Type delegateType, object target) { return default(System.Delegate); } public override bool Equals(object obj) { return default(bool); } public override System.Type[] GetGenericArguments() { return default(System.Type[]); } public virtual System.Reflection.MethodInfo GetGenericMethodDefinition() { return default(System.Reflection.MethodInfo); } public override int GetHashCode() { return default(int); } public virtual System.Reflection.MethodInfo MakeGenericMethod(params System.Type[] typeArguments) { return default(System.Reflection.MethodInfo); } } public abstract partial class Module { internal Module() { } public virtual System.Reflection.Assembly Assembly { get { return default(System.Reflection.Assembly); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } } public virtual string FullyQualifiedName { get { return default(string); } } public virtual string Name { get { return default(string); } } public override bool Equals(object o) { return default(bool); } public override int GetHashCode() { return default(int); } public virtual System.Type GetType(string className, bool throwOnError, bool ignoreCase) { return default(System.Type); } public override string ToString() { return default(string); } } public partial class ParameterInfo { internal ParameterInfo() { } public virtual System.Reflection.ParameterAttributes Attributes { get { return default(System.Reflection.ParameterAttributes); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData>); } } public virtual object DefaultValue { get { return default(object); } } public virtual bool HasDefaultValue { get { return default(bool); } } public bool IsIn { get { return default(bool); } } public bool IsOptional { get { return default(bool); } } public bool IsOut { get { return default(bool); } } public bool IsRetval { get { return default(bool); } } public virtual System.Reflection.MemberInfo Member { get { return default(System.Reflection.MemberInfo); } } public virtual string Name { get { return default(string); } } public virtual System.Type ParameterType { get { return default(System.Type); } } public virtual int Position { get { return default(int); } } } public abstract partial class PropertyInfo : System.Reflection.MemberInfo { internal PropertyInfo() { } public abstract System.Reflection.PropertyAttributes Attributes { get; } public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public virtual System.Reflection.MethodInfo GetMethod { get { return default(System.Reflection.MethodInfo); } } public bool IsSpecialName { get { return default(bool); } } public abstract System.Type PropertyType { get; } public virtual System.Reflection.MethodInfo SetMethod { get { return default(System.Reflection.MethodInfo); } } public override bool Equals(object obj) { return default(bool); } public virtual object GetConstantValue() { return default(object); } public override int GetHashCode() { return default(int); } public abstract System.Reflection.ParameterInfo[] GetIndexParameters(); public object GetValue(object obj) { return default(object); } public virtual object GetValue(object obj, object[] index) { return default(object); } public void SetValue(object obj, object value) { } public virtual void SetValue(object obj, object value, object[] index) { } } public abstract partial class ReflectionContext { protected ReflectionContext() { } public virtual System.Reflection.TypeInfo GetTypeForObject(object value) { return default(System.Reflection.TypeInfo); } public abstract System.Reflection.Assembly MapAssembly(System.Reflection.Assembly assembly); public abstract System.Reflection.TypeInfo MapType(System.Reflection.TypeInfo type); } public sealed partial class ReflectionTypeLoadException : System.Exception { public ReflectionTypeLoadException(System.Type[] classes, System.Exception[] exceptions) { } public ReflectionTypeLoadException(System.Type[] classes, System.Exception[] exceptions, string message) { } public System.Exception[] LoaderExceptions { get { return default(System.Exception[]); } } public System.Type[] Types { get { return default(System.Type[]); } } } [System.FlagsAttribute] public enum ResourceLocation { ContainedInAnotherAssembly = 2, ContainedInManifestFile = 4, Embedded = 1, } public sealed partial class TargetInvocationException : System.Exception { public TargetInvocationException(System.Exception inner) { } public TargetInvocationException(string message, System.Exception inner) { } } public sealed partial class TargetParameterCountException : System.Exception { public TargetParameterCountException() { } public TargetParameterCountException(string message) { } public TargetParameterCountException(string message, System.Exception inner) { } } public abstract partial class TypeInfo : System.Reflection.MemberInfo, System.Reflection.IReflectableType { internal TypeInfo() { } public virtual System.Collections.Generic.IEnumerable<System.Reflection.ConstructorInfo> DeclaredConstructors { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.ConstructorInfo>); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.EventInfo> DeclaredEvents { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.EventInfo>); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.FieldInfo> DeclaredFields { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.FieldInfo>); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.MemberInfo> DeclaredMembers { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.MemberInfo>); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo> DeclaredMethods { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo> DeclaredNestedTypes { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.TypeInfo>); } } public virtual System.Collections.Generic.IEnumerable<System.Reflection.PropertyInfo> DeclaredProperties { get { return default(System.Collections.Generic.IEnumerable<System.Reflection.PropertyInfo>); } } public virtual System.Type[] GenericTypeParameters { get { return default(System.Type[]); } } public virtual System.Collections.Generic.IEnumerable<System.Type> ImplementedInterfaces { get { return default(System.Collections.Generic.IEnumerable<System.Type>); } } public virtual System.Type AsType() { return default(System.Type); } public virtual System.Reflection.EventInfo GetDeclaredEvent(string name) { return default(System.Reflection.EventInfo); } public virtual System.Reflection.FieldInfo GetDeclaredField(string name) { return default(System.Reflection.FieldInfo); } public virtual System.Reflection.MethodInfo GetDeclaredMethod(string name) { return default(System.Reflection.MethodInfo); } public virtual System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo> GetDeclaredMethods(string name) { return default(System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>); } public virtual System.Reflection.TypeInfo GetDeclaredNestedType(string name) { return default(System.Reflection.TypeInfo); } public virtual System.Reflection.PropertyInfo GetDeclaredProperty(string name) { return default(System.Reflection.PropertyInfo); } public virtual bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { return default(bool); } System.Reflection.TypeInfo System.Reflection.IReflectableType.GetTypeInfo() { return default(System.Reflection.TypeInfo); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the LabSolicitudScreening class. /// </summary> [Serializable] public partial class LabSolicitudScreeningCollection : ActiveList<LabSolicitudScreening, LabSolicitudScreeningCollection> { public LabSolicitudScreeningCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>LabSolicitudScreeningCollection</returns> public LabSolicitudScreeningCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { LabSolicitudScreening o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the LAB_SolicitudScreening table. /// </summary> [Serializable] public partial class LabSolicitudScreening : ActiveRecord<LabSolicitudScreening>, IActiveRecord { #region .ctors and Default Settings public LabSolicitudScreening() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public LabSolicitudScreening(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public LabSolicitudScreening(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public LabSolicitudScreening(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("LAB_SolicitudScreening", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdSolicitudScreening = new TableSchema.TableColumn(schema); colvarIdSolicitudScreening.ColumnName = "idSolicitudScreening"; colvarIdSolicitudScreening.DataType = DbType.Int32; colvarIdSolicitudScreening.MaxLength = 0; colvarIdSolicitudScreening.AutoIncrement = true; colvarIdSolicitudScreening.IsNullable = false; colvarIdSolicitudScreening.IsPrimaryKey = true; colvarIdSolicitudScreening.IsForeignKey = false; colvarIdSolicitudScreening.IsReadOnly = false; colvarIdSolicitudScreening.DefaultSetting = @""; colvarIdSolicitudScreening.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdSolicitudScreening); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = false; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @""; colvarIdPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarIdEfectorSolicitante = new TableSchema.TableColumn(schema); colvarIdEfectorSolicitante.ColumnName = "idEfectorSolicitante"; colvarIdEfectorSolicitante.DataType = DbType.Int32; colvarIdEfectorSolicitante.MaxLength = 0; colvarIdEfectorSolicitante.AutoIncrement = false; colvarIdEfectorSolicitante.IsNullable = false; colvarIdEfectorSolicitante.IsPrimaryKey = false; colvarIdEfectorSolicitante.IsForeignKey = true; colvarIdEfectorSolicitante.IsReadOnly = false; colvarIdEfectorSolicitante.DefaultSetting = @""; colvarIdEfectorSolicitante.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdEfectorSolicitante); TableSchema.TableColumn colvarNumeroTarjeta = new TableSchema.TableColumn(schema); colvarNumeroTarjeta.ColumnName = "numeroTarjeta"; colvarNumeroTarjeta.DataType = DbType.Int32; colvarNumeroTarjeta.MaxLength = 0; colvarNumeroTarjeta.AutoIncrement = false; colvarNumeroTarjeta.IsNullable = false; colvarNumeroTarjeta.IsPrimaryKey = false; colvarNumeroTarjeta.IsForeignKey = false; colvarNumeroTarjeta.IsReadOnly = false; colvarNumeroTarjeta.DefaultSetting = @"((0))"; colvarNumeroTarjeta.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumeroTarjeta); TableSchema.TableColumn colvarMedicoSolicitante = new TableSchema.TableColumn(schema); colvarMedicoSolicitante.ColumnName = "medicoSolicitante"; colvarMedicoSolicitante.DataType = DbType.String; colvarMedicoSolicitante.MaxLength = 500; colvarMedicoSolicitante.AutoIncrement = false; colvarMedicoSolicitante.IsNullable = false; colvarMedicoSolicitante.IsPrimaryKey = false; colvarMedicoSolicitante.IsForeignKey = false; colvarMedicoSolicitante.IsReadOnly = false; colvarMedicoSolicitante.DefaultSetting = @""; colvarMedicoSolicitante.ForeignKeyTableName = ""; schema.Columns.Add(colvarMedicoSolicitante); TableSchema.TableColumn colvarApellidoMaterno = new TableSchema.TableColumn(schema); colvarApellidoMaterno.ColumnName = "apellidoMaterno"; colvarApellidoMaterno.DataType = DbType.String; colvarApellidoMaterno.MaxLength = 500; colvarApellidoMaterno.AutoIncrement = false; colvarApellidoMaterno.IsNullable = false; colvarApellidoMaterno.IsPrimaryKey = false; colvarApellidoMaterno.IsForeignKey = false; colvarApellidoMaterno.IsReadOnly = false; colvarApellidoMaterno.DefaultSetting = @""; colvarApellidoMaterno.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellidoMaterno); TableSchema.TableColumn colvarApellidoPaterno = new TableSchema.TableColumn(schema); colvarApellidoPaterno.ColumnName = "apellidoPaterno"; colvarApellidoPaterno.DataType = DbType.String; colvarApellidoPaterno.MaxLength = 500; colvarApellidoPaterno.AutoIncrement = false; colvarApellidoPaterno.IsNullable = false; colvarApellidoPaterno.IsPrimaryKey = false; colvarApellidoPaterno.IsForeignKey = false; colvarApellidoPaterno.IsReadOnly = false; colvarApellidoPaterno.DefaultSetting = @""; colvarApellidoPaterno.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellidoPaterno); TableSchema.TableColumn colvarHoraNacimiento = new TableSchema.TableColumn(schema); colvarHoraNacimiento.ColumnName = "horaNacimiento"; colvarHoraNacimiento.DataType = DbType.String; colvarHoraNacimiento.MaxLength = 50; colvarHoraNacimiento.AutoIncrement = false; colvarHoraNacimiento.IsNullable = false; colvarHoraNacimiento.IsPrimaryKey = false; colvarHoraNacimiento.IsForeignKey = false; colvarHoraNacimiento.IsReadOnly = false; colvarHoraNacimiento.DefaultSetting = @""; colvarHoraNacimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarHoraNacimiento); TableSchema.TableColumn colvarEdadGestacional = new TableSchema.TableColumn(schema); colvarEdadGestacional.ColumnName = "edadGestacional"; colvarEdadGestacional.DataType = DbType.Int32; colvarEdadGestacional.MaxLength = 0; colvarEdadGestacional.AutoIncrement = false; colvarEdadGestacional.IsNullable = false; colvarEdadGestacional.IsPrimaryKey = false; colvarEdadGestacional.IsForeignKey = false; colvarEdadGestacional.IsReadOnly = false; colvarEdadGestacional.DefaultSetting = @""; colvarEdadGestacional.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdadGestacional); TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema); colvarPeso.ColumnName = "peso"; colvarPeso.DataType = DbType.Decimal; colvarPeso.MaxLength = 0; colvarPeso.AutoIncrement = false; colvarPeso.IsNullable = false; colvarPeso.IsPrimaryKey = false; colvarPeso.IsForeignKey = false; colvarPeso.IsReadOnly = false; colvarPeso.DefaultSetting = @""; colvarPeso.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeso); TableSchema.TableColumn colvarPrimeraMuestra = new TableSchema.TableColumn(schema); colvarPrimeraMuestra.ColumnName = "primeraMuestra"; colvarPrimeraMuestra.DataType = DbType.Boolean; colvarPrimeraMuestra.MaxLength = 0; colvarPrimeraMuestra.AutoIncrement = false; colvarPrimeraMuestra.IsNullable = false; colvarPrimeraMuestra.IsPrimaryKey = false; colvarPrimeraMuestra.IsForeignKey = false; colvarPrimeraMuestra.IsReadOnly = false; colvarPrimeraMuestra.DefaultSetting = @"((1))"; colvarPrimeraMuestra.ForeignKeyTableName = ""; schema.Columns.Add(colvarPrimeraMuestra); TableSchema.TableColumn colvarIdMotivoRepeticion = new TableSchema.TableColumn(schema); colvarIdMotivoRepeticion.ColumnName = "idMotivoRepeticion"; colvarIdMotivoRepeticion.DataType = DbType.Int32; colvarIdMotivoRepeticion.MaxLength = 0; colvarIdMotivoRepeticion.AutoIncrement = false; colvarIdMotivoRepeticion.IsNullable = false; colvarIdMotivoRepeticion.IsPrimaryKey = false; colvarIdMotivoRepeticion.IsForeignKey = false; colvarIdMotivoRepeticion.IsReadOnly = false; colvarIdMotivoRepeticion.DefaultSetting = @"((0))"; colvarIdMotivoRepeticion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMotivoRepeticion); TableSchema.TableColumn colvarFechaExtraccion = new TableSchema.TableColumn(schema); colvarFechaExtraccion.ColumnName = "fechaExtraccion"; colvarFechaExtraccion.DataType = DbType.DateTime; colvarFechaExtraccion.MaxLength = 0; colvarFechaExtraccion.AutoIncrement = false; colvarFechaExtraccion.IsNullable = false; colvarFechaExtraccion.IsPrimaryKey = false; colvarFechaExtraccion.IsForeignKey = false; colvarFechaExtraccion.IsReadOnly = false; colvarFechaExtraccion.DefaultSetting = @""; colvarFechaExtraccion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaExtraccion); TableSchema.TableColumn colvarHoraExtraccion = new TableSchema.TableColumn(schema); colvarHoraExtraccion.ColumnName = "horaExtraccion"; colvarHoraExtraccion.DataType = DbType.String; colvarHoraExtraccion.MaxLength = 50; colvarHoraExtraccion.AutoIncrement = false; colvarHoraExtraccion.IsNullable = false; colvarHoraExtraccion.IsPrimaryKey = false; colvarHoraExtraccion.IsForeignKey = false; colvarHoraExtraccion.IsReadOnly = false; colvarHoraExtraccion.DefaultSetting = @""; colvarHoraExtraccion.ForeignKeyTableName = ""; schema.Columns.Add(colvarHoraExtraccion); TableSchema.TableColumn colvarIngestaLeche24Horas = new TableSchema.TableColumn(schema); colvarIngestaLeche24Horas.ColumnName = "ingestaLeche24Horas"; colvarIngestaLeche24Horas.DataType = DbType.Boolean; colvarIngestaLeche24Horas.MaxLength = 0; colvarIngestaLeche24Horas.AutoIncrement = false; colvarIngestaLeche24Horas.IsNullable = false; colvarIngestaLeche24Horas.IsPrimaryKey = false; colvarIngestaLeche24Horas.IsForeignKey = false; colvarIngestaLeche24Horas.IsReadOnly = false; colvarIngestaLeche24Horas.DefaultSetting = @"((0))"; colvarIngestaLeche24Horas.ForeignKeyTableName = ""; schema.Columns.Add(colvarIngestaLeche24Horas); TableSchema.TableColumn colvarTipoAlimentacion = new TableSchema.TableColumn(schema); colvarTipoAlimentacion.ColumnName = "tipoAlimentacion"; colvarTipoAlimentacion.DataType = DbType.Int32; colvarTipoAlimentacion.MaxLength = 0; colvarTipoAlimentacion.AutoIncrement = false; colvarTipoAlimentacion.IsNullable = false; colvarTipoAlimentacion.IsPrimaryKey = false; colvarTipoAlimentacion.IsForeignKey = false; colvarTipoAlimentacion.IsReadOnly = false; colvarTipoAlimentacion.DefaultSetting = @"((0))"; colvarTipoAlimentacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoAlimentacion); TableSchema.TableColumn colvarAntibiotico = new TableSchema.TableColumn(schema); colvarAntibiotico.ColumnName = "antibiotico"; colvarAntibiotico.DataType = DbType.Boolean; colvarAntibiotico.MaxLength = 0; colvarAntibiotico.AutoIncrement = false; colvarAntibiotico.IsNullable = false; colvarAntibiotico.IsPrimaryKey = false; colvarAntibiotico.IsForeignKey = false; colvarAntibiotico.IsReadOnly = false; colvarAntibiotico.DefaultSetting = @"((0))"; colvarAntibiotico.ForeignKeyTableName = ""; schema.Columns.Add(colvarAntibiotico); TableSchema.TableColumn colvarTransfusion = new TableSchema.TableColumn(schema); colvarTransfusion.ColumnName = "transfusion"; colvarTransfusion.DataType = DbType.Boolean; colvarTransfusion.MaxLength = 0; colvarTransfusion.AutoIncrement = false; colvarTransfusion.IsNullable = false; colvarTransfusion.IsPrimaryKey = false; colvarTransfusion.IsForeignKey = false; colvarTransfusion.IsReadOnly = false; colvarTransfusion.DefaultSetting = @"((0))"; colvarTransfusion.ForeignKeyTableName = ""; schema.Columns.Add(colvarTransfusion); TableSchema.TableColumn colvarCorticoides = new TableSchema.TableColumn(schema); colvarCorticoides.ColumnName = "corticoides"; colvarCorticoides.DataType = DbType.Boolean; colvarCorticoides.MaxLength = 0; colvarCorticoides.AutoIncrement = false; colvarCorticoides.IsNullable = false; colvarCorticoides.IsPrimaryKey = false; colvarCorticoides.IsForeignKey = false; colvarCorticoides.IsReadOnly = false; colvarCorticoides.DefaultSetting = @"((0))"; colvarCorticoides.ForeignKeyTableName = ""; schema.Columns.Add(colvarCorticoides); TableSchema.TableColumn colvarDopamina = new TableSchema.TableColumn(schema); colvarDopamina.ColumnName = "dopamina"; colvarDopamina.DataType = DbType.Boolean; colvarDopamina.MaxLength = 0; colvarDopamina.AutoIncrement = false; colvarDopamina.IsNullable = false; colvarDopamina.IsPrimaryKey = false; colvarDopamina.IsForeignKey = false; colvarDopamina.IsReadOnly = false; colvarDopamina.DefaultSetting = @"((0))"; colvarDopamina.ForeignKeyTableName = ""; schema.Columns.Add(colvarDopamina); TableSchema.TableColumn colvarEnfermedadTiroideaMaterna = new TableSchema.TableColumn(schema); colvarEnfermedadTiroideaMaterna.ColumnName = "enfermedadTiroideaMaterna"; colvarEnfermedadTiroideaMaterna.DataType = DbType.Boolean; colvarEnfermedadTiroideaMaterna.MaxLength = 0; colvarEnfermedadTiroideaMaterna.AutoIncrement = false; colvarEnfermedadTiroideaMaterna.IsNullable = false; colvarEnfermedadTiroideaMaterna.IsPrimaryKey = false; colvarEnfermedadTiroideaMaterna.IsForeignKey = false; colvarEnfermedadTiroideaMaterna.IsReadOnly = false; colvarEnfermedadTiroideaMaterna.DefaultSetting = @"((0))"; colvarEnfermedadTiroideaMaterna.ForeignKeyTableName = ""; schema.Columns.Add(colvarEnfermedadTiroideaMaterna); TableSchema.TableColumn colvarAntecedentesMaternos = new TableSchema.TableColumn(schema); colvarAntecedentesMaternos.ColumnName = "antecedentesMaternos"; colvarAntecedentesMaternos.DataType = DbType.String; colvarAntecedentesMaternos.MaxLength = -1; colvarAntecedentesMaternos.AutoIncrement = false; colvarAntecedentesMaternos.IsNullable = false; colvarAntecedentesMaternos.IsPrimaryKey = false; colvarAntecedentesMaternos.IsForeignKey = false; colvarAntecedentesMaternos.IsReadOnly = false; colvarAntecedentesMaternos.DefaultSetting = @""; colvarAntecedentesMaternos.ForeignKeyTableName = ""; schema.Columns.Add(colvarAntecedentesMaternos); TableSchema.TableColumn colvarCorticoidesMaterno = new TableSchema.TableColumn(schema); colvarCorticoidesMaterno.ColumnName = "corticoidesMaterno"; colvarCorticoidesMaterno.DataType = DbType.Boolean; colvarCorticoidesMaterno.MaxLength = 0; colvarCorticoidesMaterno.AutoIncrement = false; colvarCorticoidesMaterno.IsNullable = false; colvarCorticoidesMaterno.IsPrimaryKey = false; colvarCorticoidesMaterno.IsForeignKey = false; colvarCorticoidesMaterno.IsReadOnly = false; colvarCorticoidesMaterno.DefaultSetting = @"((0))"; colvarCorticoidesMaterno.ForeignKeyTableName = ""; schema.Columns.Add(colvarCorticoidesMaterno); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "observaciones"; colvarObservaciones.DataType = DbType.String; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = false; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); TableSchema.TableColumn colvarObservacionesResultados = new TableSchema.TableColumn(schema); colvarObservacionesResultados.ColumnName = "observacionesResultados"; colvarObservacionesResultados.DataType = DbType.String; colvarObservacionesResultados.MaxLength = -1; colvarObservacionesResultados.AutoIncrement = false; colvarObservacionesResultados.IsNullable = false; colvarObservacionesResultados.IsPrimaryKey = false; colvarObservacionesResultados.IsForeignKey = false; colvarObservacionesResultados.IsReadOnly = false; colvarObservacionesResultados.DefaultSetting = @""; colvarObservacionesResultados.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservacionesResultados); TableSchema.TableColumn colvarEstado = new TableSchema.TableColumn(schema); colvarEstado.ColumnName = "estado"; colvarEstado.DataType = DbType.Int32; colvarEstado.MaxLength = 0; colvarEstado.AutoIncrement = false; colvarEstado.IsNullable = false; colvarEstado.IsPrimaryKey = false; colvarEstado.IsForeignKey = false; colvarEstado.IsReadOnly = false; colvarEstado.DefaultSetting = @"((0))"; colvarEstado.ForeignKeyTableName = ""; schema.Columns.Add(colvarEstado); TableSchema.TableColumn colvarIdUsuarioRegistro = new TableSchema.TableColumn(schema); colvarIdUsuarioRegistro.ColumnName = "idUsuarioRegistro"; colvarIdUsuarioRegistro.DataType = DbType.Int32; colvarIdUsuarioRegistro.MaxLength = 0; colvarIdUsuarioRegistro.AutoIncrement = false; colvarIdUsuarioRegistro.IsNullable = false; colvarIdUsuarioRegistro.IsPrimaryKey = false; colvarIdUsuarioRegistro.IsForeignKey = false; colvarIdUsuarioRegistro.IsReadOnly = false; colvarIdUsuarioRegistro.DefaultSetting = @""; colvarIdUsuarioRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioRegistro); TableSchema.TableColumn colvarFechaRegistro = new TableSchema.TableColumn(schema); colvarFechaRegistro.ColumnName = "fechaRegistro"; colvarFechaRegistro.DataType = DbType.DateTime; colvarFechaRegistro.MaxLength = 0; colvarFechaRegistro.AutoIncrement = false; colvarFechaRegistro.IsNullable = false; colvarFechaRegistro.IsPrimaryKey = false; colvarFechaRegistro.IsForeignKey = false; colvarFechaRegistro.IsReadOnly = false; colvarFechaRegistro.DefaultSetting = @""; colvarFechaRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRegistro); TableSchema.TableColumn colvarIdUsuarioEnvio = new TableSchema.TableColumn(schema); colvarIdUsuarioEnvio.ColumnName = "idUsuarioEnvio"; colvarIdUsuarioEnvio.DataType = DbType.AnsiString; colvarIdUsuarioEnvio.MaxLength = 50; colvarIdUsuarioEnvio.AutoIncrement = false; colvarIdUsuarioEnvio.IsNullable = false; colvarIdUsuarioEnvio.IsPrimaryKey = false; colvarIdUsuarioEnvio.IsForeignKey = false; colvarIdUsuarioEnvio.IsReadOnly = false; colvarIdUsuarioEnvio.DefaultSetting = @""; colvarIdUsuarioEnvio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioEnvio); TableSchema.TableColumn colvarFechaEnvio = new TableSchema.TableColumn(schema); colvarFechaEnvio.ColumnName = "fechaEnvio"; colvarFechaEnvio.DataType = DbType.DateTime; colvarFechaEnvio.MaxLength = 0; colvarFechaEnvio.AutoIncrement = false; colvarFechaEnvio.IsNullable = false; colvarFechaEnvio.IsPrimaryKey = false; colvarFechaEnvio.IsForeignKey = false; colvarFechaEnvio.IsReadOnly = false; colvarFechaEnvio.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaEnvio.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaEnvio); TableSchema.TableColumn colvarIdUsuarioRecibe = new TableSchema.TableColumn(schema); colvarIdUsuarioRecibe.ColumnName = "idUsuarioRecibe"; colvarIdUsuarioRecibe.DataType = DbType.AnsiString; colvarIdUsuarioRecibe.MaxLength = 50; colvarIdUsuarioRecibe.AutoIncrement = false; colvarIdUsuarioRecibe.IsNullable = false; colvarIdUsuarioRecibe.IsPrimaryKey = false; colvarIdUsuarioRecibe.IsForeignKey = false; colvarIdUsuarioRecibe.IsReadOnly = false; colvarIdUsuarioRecibe.DefaultSetting = @""; colvarIdUsuarioRecibe.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioRecibe); TableSchema.TableColumn colvarFechaRecibe = new TableSchema.TableColumn(schema); colvarFechaRecibe.ColumnName = "fechaRecibe"; colvarFechaRecibe.DataType = DbType.DateTime; colvarFechaRecibe.MaxLength = 0; colvarFechaRecibe.AutoIncrement = false; colvarFechaRecibe.IsNullable = false; colvarFechaRecibe.IsPrimaryKey = false; colvarFechaRecibe.IsForeignKey = false; colvarFechaRecibe.IsReadOnly = false; colvarFechaRecibe.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaRecibe.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRecibe); TableSchema.TableColumn colvarIdUsuarioValida = new TableSchema.TableColumn(schema); colvarIdUsuarioValida.ColumnName = "idUsuarioValida"; colvarIdUsuarioValida.DataType = DbType.AnsiString; colvarIdUsuarioValida.MaxLength = 50; colvarIdUsuarioValida.AutoIncrement = false; colvarIdUsuarioValida.IsNullable = false; colvarIdUsuarioValida.IsPrimaryKey = false; colvarIdUsuarioValida.IsForeignKey = false; colvarIdUsuarioValida.IsReadOnly = false; colvarIdUsuarioValida.DefaultSetting = @""; colvarIdUsuarioValida.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioValida); TableSchema.TableColumn colvarFechaValida = new TableSchema.TableColumn(schema); colvarFechaValida.ColumnName = "fechaValida"; colvarFechaValida.DataType = DbType.DateTime; colvarFechaValida.MaxLength = 0; colvarFechaValida.AutoIncrement = false; colvarFechaValida.IsNullable = false; colvarFechaValida.IsPrimaryKey = false; colvarFechaValida.IsForeignKey = false; colvarFechaValida.IsReadOnly = false; colvarFechaValida.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaValida.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaValida); TableSchema.TableColumn colvarIdLugarControl = new TableSchema.TableColumn(schema); colvarIdLugarControl.ColumnName = "idLugarControl"; colvarIdLugarControl.DataType = DbType.Int32; colvarIdLugarControl.MaxLength = 0; colvarIdLugarControl.AutoIncrement = false; colvarIdLugarControl.IsNullable = false; colvarIdLugarControl.IsPrimaryKey = false; colvarIdLugarControl.IsForeignKey = true; colvarIdLugarControl.IsReadOnly = false; colvarIdLugarControl.DefaultSetting = @""; colvarIdLugarControl.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdLugarControl); TableSchema.TableColumn colvarIdEfectorModifica = new TableSchema.TableColumn(schema); colvarIdEfectorModifica.ColumnName = "idEfectorModifica"; colvarIdEfectorModifica.DataType = DbType.Int32; colvarIdEfectorModifica.MaxLength = 0; colvarIdEfectorModifica.AutoIncrement = false; colvarIdEfectorModifica.IsNullable = true; colvarIdEfectorModifica.IsPrimaryKey = false; colvarIdEfectorModifica.IsForeignKey = false; colvarIdEfectorModifica.IsReadOnly = false; colvarIdEfectorModifica.DefaultSetting = @""; colvarIdEfectorModifica.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfectorModifica); TableSchema.TableColumn colvarComentario = new TableSchema.TableColumn(schema); colvarComentario.ColumnName = "Comentario"; colvarComentario.DataType = DbType.AnsiString; colvarComentario.MaxLength = 4000; colvarComentario.AutoIncrement = false; colvarComentario.IsNullable = true; colvarComentario.IsPrimaryKey = false; colvarComentario.IsForeignKey = false; colvarComentario.IsReadOnly = false; colvarComentario.DefaultSetting = @""; colvarComentario.ForeignKeyTableName = ""; schema.Columns.Add(colvarComentario); TableSchema.TableColumn colvarMotivo = new TableSchema.TableColumn(schema); colvarMotivo.ColumnName = "Motivo"; colvarMotivo.DataType = DbType.AnsiString; colvarMotivo.MaxLength = 4000; colvarMotivo.AutoIncrement = false; colvarMotivo.IsNullable = true; colvarMotivo.IsPrimaryKey = false; colvarMotivo.IsForeignKey = false; colvarMotivo.IsReadOnly = false; colvarMotivo.DefaultSetting = @""; colvarMotivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarMotivo); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("LAB_SolicitudScreening",schema); } } #endregion #region Props [XmlAttribute("IdSolicitudScreening")] [Bindable(true)] public int IdSolicitudScreening { get { return GetColumnValue<int>(Columns.IdSolicitudScreening); } set { SetColumnValue(Columns.IdSolicitudScreening, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("IdEfectorSolicitante")] [Bindable(true)] public int IdEfectorSolicitante { get { return GetColumnValue<int>(Columns.IdEfectorSolicitante); } set { SetColumnValue(Columns.IdEfectorSolicitante, value); } } [XmlAttribute("NumeroTarjeta")] [Bindable(true)] public int NumeroTarjeta { get { return GetColumnValue<int>(Columns.NumeroTarjeta); } set { SetColumnValue(Columns.NumeroTarjeta, value); } } [XmlAttribute("MedicoSolicitante")] [Bindable(true)] public string MedicoSolicitante { get { return GetColumnValue<string>(Columns.MedicoSolicitante); } set { SetColumnValue(Columns.MedicoSolicitante, value); } } [XmlAttribute("ApellidoMaterno")] [Bindable(true)] public string ApellidoMaterno { get { return GetColumnValue<string>(Columns.ApellidoMaterno); } set { SetColumnValue(Columns.ApellidoMaterno, value); } } [XmlAttribute("ApellidoPaterno")] [Bindable(true)] public string ApellidoPaterno { get { return GetColumnValue<string>(Columns.ApellidoPaterno); } set { SetColumnValue(Columns.ApellidoPaterno, value); } } [XmlAttribute("HoraNacimiento")] [Bindable(true)] public string HoraNacimiento { get { return GetColumnValue<string>(Columns.HoraNacimiento); } set { SetColumnValue(Columns.HoraNacimiento, value); } } [XmlAttribute("EdadGestacional")] [Bindable(true)] public int EdadGestacional { get { return GetColumnValue<int>(Columns.EdadGestacional); } set { SetColumnValue(Columns.EdadGestacional, value); } } [XmlAttribute("Peso")] [Bindable(true)] public decimal Peso { get { return GetColumnValue<decimal>(Columns.Peso); } set { SetColumnValue(Columns.Peso, value); } } [XmlAttribute("PrimeraMuestra")] [Bindable(true)] public bool PrimeraMuestra { get { return GetColumnValue<bool>(Columns.PrimeraMuestra); } set { SetColumnValue(Columns.PrimeraMuestra, value); } } [XmlAttribute("IdMotivoRepeticion")] [Bindable(true)] public int IdMotivoRepeticion { get { return GetColumnValue<int>(Columns.IdMotivoRepeticion); } set { SetColumnValue(Columns.IdMotivoRepeticion, value); } } [XmlAttribute("FechaExtraccion")] [Bindable(true)] public DateTime FechaExtraccion { get { return GetColumnValue<DateTime>(Columns.FechaExtraccion); } set { SetColumnValue(Columns.FechaExtraccion, value); } } [XmlAttribute("HoraExtraccion")] [Bindable(true)] public string HoraExtraccion { get { return GetColumnValue<string>(Columns.HoraExtraccion); } set { SetColumnValue(Columns.HoraExtraccion, value); } } [XmlAttribute("IngestaLeche24Horas")] [Bindable(true)] public bool IngestaLeche24Horas { get { return GetColumnValue<bool>(Columns.IngestaLeche24Horas); } set { SetColumnValue(Columns.IngestaLeche24Horas, value); } } [XmlAttribute("TipoAlimentacion")] [Bindable(true)] public int TipoAlimentacion { get { return GetColumnValue<int>(Columns.TipoAlimentacion); } set { SetColumnValue(Columns.TipoAlimentacion, value); } } [XmlAttribute("Antibiotico")] [Bindable(true)] public bool Antibiotico { get { return GetColumnValue<bool>(Columns.Antibiotico); } set { SetColumnValue(Columns.Antibiotico, value); } } [XmlAttribute("Transfusion")] [Bindable(true)] public bool Transfusion { get { return GetColumnValue<bool>(Columns.Transfusion); } set { SetColumnValue(Columns.Transfusion, value); } } [XmlAttribute("Corticoides")] [Bindable(true)] public bool Corticoides { get { return GetColumnValue<bool>(Columns.Corticoides); } set { SetColumnValue(Columns.Corticoides, value); } } [XmlAttribute("Dopamina")] [Bindable(true)] public bool Dopamina { get { return GetColumnValue<bool>(Columns.Dopamina); } set { SetColumnValue(Columns.Dopamina, value); } } [XmlAttribute("EnfermedadTiroideaMaterna")] [Bindable(true)] public bool EnfermedadTiroideaMaterna { get { return GetColumnValue<bool>(Columns.EnfermedadTiroideaMaterna); } set { SetColumnValue(Columns.EnfermedadTiroideaMaterna, value); } } [XmlAttribute("AntecedentesMaternos")] [Bindable(true)] public string AntecedentesMaternos { get { return GetColumnValue<string>(Columns.AntecedentesMaternos); } set { SetColumnValue(Columns.AntecedentesMaternos, value); } } [XmlAttribute("CorticoidesMaterno")] [Bindable(true)] public bool CorticoidesMaterno { get { return GetColumnValue<bool>(Columns.CorticoidesMaterno); } set { SetColumnValue(Columns.CorticoidesMaterno, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } [XmlAttribute("ObservacionesResultados")] [Bindable(true)] public string ObservacionesResultados { get { return GetColumnValue<string>(Columns.ObservacionesResultados); } set { SetColumnValue(Columns.ObservacionesResultados, value); } } [XmlAttribute("Estado")] [Bindable(true)] public int Estado { get { return GetColumnValue<int>(Columns.Estado); } set { SetColumnValue(Columns.Estado, value); } } [XmlAttribute("IdUsuarioRegistro")] [Bindable(true)] public int IdUsuarioRegistro { get { return GetColumnValue<int>(Columns.IdUsuarioRegistro); } set { SetColumnValue(Columns.IdUsuarioRegistro, value); } } [XmlAttribute("FechaRegistro")] [Bindable(true)] public DateTime FechaRegistro { get { return GetColumnValue<DateTime>(Columns.FechaRegistro); } set { SetColumnValue(Columns.FechaRegistro, value); } } [XmlAttribute("IdUsuarioEnvio")] [Bindable(true)] public string IdUsuarioEnvio { get { return GetColumnValue<string>(Columns.IdUsuarioEnvio); } set { SetColumnValue(Columns.IdUsuarioEnvio, value); } } [XmlAttribute("FechaEnvio")] [Bindable(true)] public DateTime FechaEnvio { get { return GetColumnValue<DateTime>(Columns.FechaEnvio); } set { SetColumnValue(Columns.FechaEnvio, value); } } [XmlAttribute("IdUsuarioRecibe")] [Bindable(true)] public string IdUsuarioRecibe { get { return GetColumnValue<string>(Columns.IdUsuarioRecibe); } set { SetColumnValue(Columns.IdUsuarioRecibe, value); } } [XmlAttribute("FechaRecibe")] [Bindable(true)] public DateTime FechaRecibe { get { return GetColumnValue<DateTime>(Columns.FechaRecibe); } set { SetColumnValue(Columns.FechaRecibe, value); } } [XmlAttribute("IdUsuarioValida")] [Bindable(true)] public string IdUsuarioValida { get { return GetColumnValue<string>(Columns.IdUsuarioValida); } set { SetColumnValue(Columns.IdUsuarioValida, value); } } [XmlAttribute("FechaValida")] [Bindable(true)] public DateTime FechaValida { get { return GetColumnValue<DateTime>(Columns.FechaValida); } set { SetColumnValue(Columns.FechaValida, value); } } [XmlAttribute("IdLugarControl")] [Bindable(true)] public int IdLugarControl { get { return GetColumnValue<int>(Columns.IdLugarControl); } set { SetColumnValue(Columns.IdLugarControl, value); } } [XmlAttribute("IdEfectorModifica")] [Bindable(true)] public int? IdEfectorModifica { get { return GetColumnValue<int?>(Columns.IdEfectorModifica); } set { SetColumnValue(Columns.IdEfectorModifica, value); } } [XmlAttribute("Comentario")] [Bindable(true)] public string Comentario { get { return GetColumnValue<string>(Columns.Comentario); } set { SetColumnValue(Columns.Comentario, value); } } [XmlAttribute("Motivo")] [Bindable(true)] public string Motivo { get { return GetColumnValue<string>(Columns.Motivo); } set { SetColumnValue(Columns.Motivo, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.LabProtocoloScreeningDetalleCollection colLabProtocoloScreeningDetalleRecords; public DalSic.LabProtocoloScreeningDetalleCollection LabProtocoloScreeningDetalleRecords { get { if(colLabProtocoloScreeningDetalleRecords == null) { colLabProtocoloScreeningDetalleRecords = new DalSic.LabProtocoloScreeningDetalleCollection().Where(LabProtocoloScreeningDetalle.Columns.IdSolicitudScreening, IdSolicitudScreening).Load(); colLabProtocoloScreeningDetalleRecords.ListChanged += new ListChangedEventHandler(colLabProtocoloScreeningDetalleRecords_ListChanged); } return colLabProtocoloScreeningDetalleRecords; } set { colLabProtocoloScreeningDetalleRecords = value; colLabProtocoloScreeningDetalleRecords.ListChanged += new ListChangedEventHandler(colLabProtocoloScreeningDetalleRecords_ListChanged); } } void colLabProtocoloScreeningDetalleRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colLabProtocoloScreeningDetalleRecords[e.NewIndex].IdSolicitudScreening = IdSolicitudScreening; } } private DalSic.LabAlarmaScreeningCollection colLabAlarmaScreeningRecords; public DalSic.LabAlarmaScreeningCollection LabAlarmaScreeningRecords { get { if(colLabAlarmaScreeningRecords == null) { colLabAlarmaScreeningRecords = new DalSic.LabAlarmaScreeningCollection().Where(LabAlarmaScreening.Columns.IdSolicitudScreening, IdSolicitudScreening).Load(); colLabAlarmaScreeningRecords.ListChanged += new ListChangedEventHandler(colLabAlarmaScreeningRecords_ListChanged); } return colLabAlarmaScreeningRecords; } set { colLabAlarmaScreeningRecords = value; colLabAlarmaScreeningRecords.ListChanged += new ListChangedEventHandler(colLabAlarmaScreeningRecords_ListChanged); } } void colLabAlarmaScreeningRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colLabAlarmaScreeningRecords[e.NewIndex].IdSolicitudScreening = IdSolicitudScreening; } } private DalSic.LabDetalleSolicitudScreeningCollection colLabDetalleSolicitudScreeningRecords; public DalSic.LabDetalleSolicitudScreeningCollection LabDetalleSolicitudScreeningRecords { get { if(colLabDetalleSolicitudScreeningRecords == null) { colLabDetalleSolicitudScreeningRecords = new DalSic.LabDetalleSolicitudScreeningCollection().Where(LabDetalleSolicitudScreening.Columns.IdSolicitudScreening, IdSolicitudScreening).Load(); colLabDetalleSolicitudScreeningRecords.ListChanged += new ListChangedEventHandler(colLabDetalleSolicitudScreeningRecords_ListChanged); } return colLabDetalleSolicitudScreeningRecords; } set { colLabDetalleSolicitudScreeningRecords = value; colLabDetalleSolicitudScreeningRecords.ListChanged += new ListChangedEventHandler(colLabDetalleSolicitudScreeningRecords_ListChanged); } } void colLabDetalleSolicitudScreeningRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colLabDetalleSolicitudScreeningRecords[e.NewIndex].IdSolicitudScreening = IdSolicitudScreening; } } private DalSic.LabSolicitudScreeningRepeticionCollection colLabSolicitudScreeningRepeticionRecords; public DalSic.LabSolicitudScreeningRepeticionCollection LabSolicitudScreeningRepeticionRecords { get { if(colLabSolicitudScreeningRepeticionRecords == null) { colLabSolicitudScreeningRepeticionRecords = new DalSic.LabSolicitudScreeningRepeticionCollection().Where(LabSolicitudScreeningRepeticion.Columns.IdSolicitudScreening, IdSolicitudScreening).Load(); colLabSolicitudScreeningRepeticionRecords.ListChanged += new ListChangedEventHandler(colLabSolicitudScreeningRepeticionRecords_ListChanged); } return colLabSolicitudScreeningRepeticionRecords; } set { colLabSolicitudScreeningRepeticionRecords = value; colLabSolicitudScreeningRepeticionRecords.ListChanged += new ListChangedEventHandler(colLabSolicitudScreeningRepeticionRecords_ListChanged); } } void colLabSolicitudScreeningRepeticionRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colLabSolicitudScreeningRepeticionRecords[e.NewIndex].IdSolicitudScreening = IdSolicitudScreening; } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysEfector ActiveRecord object related to this LabSolicitudScreening /// /// </summary> public DalSic.SysEfector SysEfector { get { return DalSic.SysEfector.FetchByID(this.IdEfectorSolicitante); } set { SetColumnValue("idEfectorSolicitante", value.IdEfector); } } /// <summary> /// Returns a SysEfector ActiveRecord object related to this LabSolicitudScreening /// /// </summary> public DalSic.SysEfector SysEfectorToIdLugarControl { get { return DalSic.SysEfector.FetchByID(this.IdLugarControl); } set { SetColumnValue("idLugarControl", value.IdEfector); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdPaciente,int varIdEfectorSolicitante,int varNumeroTarjeta,string varMedicoSolicitante,string varApellidoMaterno,string varApellidoPaterno,string varHoraNacimiento,int varEdadGestacional,decimal varPeso,bool varPrimeraMuestra,int varIdMotivoRepeticion,DateTime varFechaExtraccion,string varHoraExtraccion,bool varIngestaLeche24Horas,int varTipoAlimentacion,bool varAntibiotico,bool varTransfusion,bool varCorticoides,bool varDopamina,bool varEnfermedadTiroideaMaterna,string varAntecedentesMaternos,bool varCorticoidesMaterno,string varObservaciones,string varObservacionesResultados,int varEstado,int varIdUsuarioRegistro,DateTime varFechaRegistro,string varIdUsuarioEnvio,DateTime varFechaEnvio,string varIdUsuarioRecibe,DateTime varFechaRecibe,string varIdUsuarioValida,DateTime varFechaValida,int varIdLugarControl,int? varIdEfectorModifica,string varComentario,string varMotivo) { LabSolicitudScreening item = new LabSolicitudScreening(); item.IdPaciente = varIdPaciente; item.IdEfectorSolicitante = varIdEfectorSolicitante; item.NumeroTarjeta = varNumeroTarjeta; item.MedicoSolicitante = varMedicoSolicitante; item.ApellidoMaterno = varApellidoMaterno; item.ApellidoPaterno = varApellidoPaterno; item.HoraNacimiento = varHoraNacimiento; item.EdadGestacional = varEdadGestacional; item.Peso = varPeso; item.PrimeraMuestra = varPrimeraMuestra; item.IdMotivoRepeticion = varIdMotivoRepeticion; item.FechaExtraccion = varFechaExtraccion; item.HoraExtraccion = varHoraExtraccion; item.IngestaLeche24Horas = varIngestaLeche24Horas; item.TipoAlimentacion = varTipoAlimentacion; item.Antibiotico = varAntibiotico; item.Transfusion = varTransfusion; item.Corticoides = varCorticoides; item.Dopamina = varDopamina; item.EnfermedadTiroideaMaterna = varEnfermedadTiroideaMaterna; item.AntecedentesMaternos = varAntecedentesMaternos; item.CorticoidesMaterno = varCorticoidesMaterno; item.Observaciones = varObservaciones; item.ObservacionesResultados = varObservacionesResultados; item.Estado = varEstado; item.IdUsuarioRegistro = varIdUsuarioRegistro; item.FechaRegistro = varFechaRegistro; item.IdUsuarioEnvio = varIdUsuarioEnvio; item.FechaEnvio = varFechaEnvio; item.IdUsuarioRecibe = varIdUsuarioRecibe; item.FechaRecibe = varFechaRecibe; item.IdUsuarioValida = varIdUsuarioValida; item.FechaValida = varFechaValida; item.IdLugarControl = varIdLugarControl; item.IdEfectorModifica = varIdEfectorModifica; item.Comentario = varComentario; item.Motivo = varMotivo; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdSolicitudScreening,int varIdPaciente,int varIdEfectorSolicitante,int varNumeroTarjeta,string varMedicoSolicitante,string varApellidoMaterno,string varApellidoPaterno,string varHoraNacimiento,int varEdadGestacional,decimal varPeso,bool varPrimeraMuestra,int varIdMotivoRepeticion,DateTime varFechaExtraccion,string varHoraExtraccion,bool varIngestaLeche24Horas,int varTipoAlimentacion,bool varAntibiotico,bool varTransfusion,bool varCorticoides,bool varDopamina,bool varEnfermedadTiroideaMaterna,string varAntecedentesMaternos,bool varCorticoidesMaterno,string varObservaciones,string varObservacionesResultados,int varEstado,int varIdUsuarioRegistro,DateTime varFechaRegistro,string varIdUsuarioEnvio,DateTime varFechaEnvio,string varIdUsuarioRecibe,DateTime varFechaRecibe,string varIdUsuarioValida,DateTime varFechaValida,int varIdLugarControl,int? varIdEfectorModifica,string varComentario,string varMotivo) { LabSolicitudScreening item = new LabSolicitudScreening(); item.IdSolicitudScreening = varIdSolicitudScreening; item.IdPaciente = varIdPaciente; item.IdEfectorSolicitante = varIdEfectorSolicitante; item.NumeroTarjeta = varNumeroTarjeta; item.MedicoSolicitante = varMedicoSolicitante; item.ApellidoMaterno = varApellidoMaterno; item.ApellidoPaterno = varApellidoPaterno; item.HoraNacimiento = varHoraNacimiento; item.EdadGestacional = varEdadGestacional; item.Peso = varPeso; item.PrimeraMuestra = varPrimeraMuestra; item.IdMotivoRepeticion = varIdMotivoRepeticion; item.FechaExtraccion = varFechaExtraccion; item.HoraExtraccion = varHoraExtraccion; item.IngestaLeche24Horas = varIngestaLeche24Horas; item.TipoAlimentacion = varTipoAlimentacion; item.Antibiotico = varAntibiotico; item.Transfusion = varTransfusion; item.Corticoides = varCorticoides; item.Dopamina = varDopamina; item.EnfermedadTiroideaMaterna = varEnfermedadTiroideaMaterna; item.AntecedentesMaternos = varAntecedentesMaternos; item.CorticoidesMaterno = varCorticoidesMaterno; item.Observaciones = varObservaciones; item.ObservacionesResultados = varObservacionesResultados; item.Estado = varEstado; item.IdUsuarioRegistro = varIdUsuarioRegistro; item.FechaRegistro = varFechaRegistro; item.IdUsuarioEnvio = varIdUsuarioEnvio; item.FechaEnvio = varFechaEnvio; item.IdUsuarioRecibe = varIdUsuarioRecibe; item.FechaRecibe = varFechaRecibe; item.IdUsuarioValida = varIdUsuarioValida; item.FechaValida = varFechaValida; item.IdLugarControl = varIdLugarControl; item.IdEfectorModifica = varIdEfectorModifica; item.Comentario = varComentario; item.Motivo = varMotivo; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdSolicitudScreeningColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdEfectorSolicitanteColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NumeroTarjetaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn MedicoSolicitanteColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn ApellidoMaternoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn ApellidoPaternoColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn HoraNacimientoColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn EdadGestacionalColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn PesoColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn PrimeraMuestraColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn IdMotivoRepeticionColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn FechaExtraccionColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn HoraExtraccionColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn IngestaLeche24HorasColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn TipoAlimentacionColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn AntibioticoColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn TransfusionColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn CorticoidesColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn DopaminaColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn EnfermedadTiroideaMaternaColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn AntecedentesMaternosColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn CorticoidesMaternoColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn ObservacionesResultadosColumn { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn EstadoColumn { get { return Schema.Columns[25]; } } public static TableSchema.TableColumn IdUsuarioRegistroColumn { get { return Schema.Columns[26]; } } public static TableSchema.TableColumn FechaRegistroColumn { get { return Schema.Columns[27]; } } public static TableSchema.TableColumn IdUsuarioEnvioColumn { get { return Schema.Columns[28]; } } public static TableSchema.TableColumn FechaEnvioColumn { get { return Schema.Columns[29]; } } public static TableSchema.TableColumn IdUsuarioRecibeColumn { get { return Schema.Columns[30]; } } public static TableSchema.TableColumn FechaRecibeColumn { get { return Schema.Columns[31]; } } public static TableSchema.TableColumn IdUsuarioValidaColumn { get { return Schema.Columns[32]; } } public static TableSchema.TableColumn FechaValidaColumn { get { return Schema.Columns[33]; } } public static TableSchema.TableColumn IdLugarControlColumn { get { return Schema.Columns[34]; } } public static TableSchema.TableColumn IdEfectorModificaColumn { get { return Schema.Columns[35]; } } public static TableSchema.TableColumn ComentarioColumn { get { return Schema.Columns[36]; } } public static TableSchema.TableColumn MotivoColumn { get { return Schema.Columns[37]; } } #endregion #region Columns Struct public struct Columns { public static string IdSolicitudScreening = @"idSolicitudScreening"; public static string IdPaciente = @"idPaciente"; public static string IdEfectorSolicitante = @"idEfectorSolicitante"; public static string NumeroTarjeta = @"numeroTarjeta"; public static string MedicoSolicitante = @"medicoSolicitante"; public static string ApellidoMaterno = @"apellidoMaterno"; public static string ApellidoPaterno = @"apellidoPaterno"; public static string HoraNacimiento = @"horaNacimiento"; public static string EdadGestacional = @"edadGestacional"; public static string Peso = @"peso"; public static string PrimeraMuestra = @"primeraMuestra"; public static string IdMotivoRepeticion = @"idMotivoRepeticion"; public static string FechaExtraccion = @"fechaExtraccion"; public static string HoraExtraccion = @"horaExtraccion"; public static string IngestaLeche24Horas = @"ingestaLeche24Horas"; public static string TipoAlimentacion = @"tipoAlimentacion"; public static string Antibiotico = @"antibiotico"; public static string Transfusion = @"transfusion"; public static string Corticoides = @"corticoides"; public static string Dopamina = @"dopamina"; public static string EnfermedadTiroideaMaterna = @"enfermedadTiroideaMaterna"; public static string AntecedentesMaternos = @"antecedentesMaternos"; public static string CorticoidesMaterno = @"corticoidesMaterno"; public static string Observaciones = @"observaciones"; public static string ObservacionesResultados = @"observacionesResultados"; public static string Estado = @"estado"; public static string IdUsuarioRegistro = @"idUsuarioRegistro"; public static string FechaRegistro = @"fechaRegistro"; public static string IdUsuarioEnvio = @"idUsuarioEnvio"; public static string FechaEnvio = @"fechaEnvio"; public static string IdUsuarioRecibe = @"idUsuarioRecibe"; public static string FechaRecibe = @"fechaRecibe"; public static string IdUsuarioValida = @"idUsuarioValida"; public static string FechaValida = @"fechaValida"; public static string IdLugarControl = @"idLugarControl"; public static string IdEfectorModifica = @"idEfectorModifica"; public static string Comentario = @"Comentario"; public static string Motivo = @"Motivo"; } #endregion #region Update PK Collections public void SetPKValues() { if (colLabProtocoloScreeningDetalleRecords != null) { foreach (DalSic.LabProtocoloScreeningDetalle item in colLabProtocoloScreeningDetalleRecords) { if (item.IdSolicitudScreening != IdSolicitudScreening) { item.IdSolicitudScreening = IdSolicitudScreening; } } } if (colLabAlarmaScreeningRecords != null) { foreach (DalSic.LabAlarmaScreening item in colLabAlarmaScreeningRecords) { if (item.IdSolicitudScreening != IdSolicitudScreening) { item.IdSolicitudScreening = IdSolicitudScreening; } } } if (colLabDetalleSolicitudScreeningRecords != null) { foreach (DalSic.LabDetalleSolicitudScreening item in colLabDetalleSolicitudScreeningRecords) { if (item.IdSolicitudScreening != IdSolicitudScreening) { item.IdSolicitudScreening = IdSolicitudScreening; } } } if (colLabSolicitudScreeningRepeticionRecords != null) { foreach (DalSic.LabSolicitudScreeningRepeticion item in colLabSolicitudScreeningRepeticionRecords) { if (item.IdSolicitudScreening != IdSolicitudScreening) { item.IdSolicitudScreening = IdSolicitudScreening; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colLabProtocoloScreeningDetalleRecords != null) { colLabProtocoloScreeningDetalleRecords.SaveAll(); } if (colLabAlarmaScreeningRecords != null) { colLabAlarmaScreeningRecords.SaveAll(); } if (colLabDetalleSolicitudScreeningRecords != null) { colLabDetalleSolicitudScreeningRecords.SaveAll(); } if (colLabSolicitudScreeningRepeticionRecords != null) { colLabSolicitudScreeningRepeticionRecords.SaveAll(); } } #endregion } }
#region License /* * HttpServer.cs * * A simple HTTP server that allows to accept the WebSocket connection requests. * * The MIT License * * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contributors /* * Contributors: * - Juan Manuel Lallana <juan.manuel.lallana@gmail.com> * - Liryna <liryna.stark@gmail.com> * - Rohan Singh <rohan-singh@hotmail.com> */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Provides a simple HTTP server that allows to accept the WebSocket connection requests. /// </summary> /// <remarks> /// The HttpServer class can provide multiple WebSocket services. /// </remarks> public class HttpServer { #region Private Fields private System.Net.IPAddress _address; private string _hostname; private HttpListener _listener; private Logger _logger; private int _port; private Thread _receiveThread; private string _rootPath; private bool _secure; private WebSocketServiceManager _services; private volatile ServerState _state; private object _sync; private bool _windows; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming requests on port 80. /// </remarks> public HttpServer () { init ("*", System.Net.IPAddress.Any, 80, false); } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming requests on /// <paramref name="port"/>. /// </para> /// <para> /// If <paramref name="port"/> is 443, that instance provides a secure connection. /// </para> /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public HttpServer (int port) : this (port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified HTTP URL. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming requests on /// the host name and port in <paramref name="url"/>. /// </para> /// <para> /// If <paramref name="url"/> doesn't include a port, either port 80 or 443 is used on /// which to listen. It's determined by the scheme (http or https) in <paramref name="url"/>. /// (Port 80 if the scheme is http.) /// </para> /// </remarks> /// <param name="url"> /// A <see cref="string"/> that represents the HTTP URL of the server. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="url"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="url"/> is invalid. /// </para> /// </exception> public HttpServer (string url) { if (url == null) throw new ArgumentNullException ("url"); if (url.Length == 0) throw new ArgumentException ("An empty string.", "url"); Uri uri; string msg; if (!tryCreateUri (url, out uri, out msg)) throw new ArgumentException (msg, "url"); var host = uri.DnsSafeHost; var addr = host.ToIPAddress (); if (!addr.IsLocal ()) throw new ArgumentException ("The host part isn't a local host name: " + url, "url"); init (host, addr, uri.Port, uri.Scheme == "https"); } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified <paramref name="port"/> and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming requests on /// <paramref name="port"/>. /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public HttpServer (int port, bool secure) { if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init ("*", System.Net.IPAddress.Any, port, secure); } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified <paramref name="address"/> and <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// An instance initialized by this constructor listens for the incoming requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </para> /// <para> /// If <paramref name="port"/> is 443, that instance provides a secure connection. /// </para> /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public HttpServer (System.Net.IPAddress address, int port) : this (address, port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class with /// the specified <paramref name="address"/>, <paramref name="port"/>, /// and <paramref name="secure"/>. /// </summary> /// <remarks> /// An instance initialized by this constructor listens for the incoming requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the port number on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> isn't a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> isn't between 1 and 65535 inclusive. /// </exception> public HttpServer (System.Net.IPAddress address, int port, bool secure) { if (address == null) throw new ArgumentNullException ("address"); if (!address.IsLocal ()) throw new ArgumentException ("Not a local IP address: " + address, "address"); if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Not between 1 and 65535 inclusive: " + port); init (null, address, port, secure); } #endregion #region Public Properties /// <summary> /// Gets the local IP address of the server. /// </summary> /// <value> /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server. /// </value> public System.Net.IPAddress Address { get { return _address; } } /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <value> /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values, /// indicates the scheme used to authenticate the clients. The default value is /// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// </value> public AuthenticationSchemes AuthenticationSchemes { get { return _listener.AuthenticationSchemes; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _listener.AuthenticationSchemes = value; } } /// <summary> /// Gets a value indicating whether the server has started. /// </summary> /// <value> /// <c>true</c> if the server has started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _state == ServerState.Start; } } /// <summary> /// Gets a value indicating whether the server provides a secure connection. /// </summary> /// <value> /// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>. /// </value> public bool IsSecure { get { return _secure; } } /// <summary> /// Gets or sets a value indicating whether the server cleans up /// the inactive sessions in the WebSocket services periodically. /// </summary> /// <value> /// <c>true</c> if the server cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. The default value is <c>true</c>. /// </value> public bool KeepClean { get { return _services.KeepClean; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _services.KeepClean = value; } } /// <summary> /// Gets the logging functions. /// </summary> /// <remarks> /// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it, /// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum /// values. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging functions. /// </value> public Logger Log { get { return _logger; } } /// <summary> /// Gets the port on which to listen for incoming requests. /// </summary> /// <value> /// An <see cref="int"/> that represents the port number on which to listen. /// </value> public int Port { get { return _port; } } /// <summary> /// Gets or sets the name of the realm associated with the server. /// </summary> /// <remarks> /// If this property is <see langword="null"/> or empty, <c>"SECRET AREA"</c> will be used as /// the name of the realm. /// </remarks> /// <value> /// A <see cref="string"/> that represents the name of the realm. The default value is /// <see langword="null"/>. /// </value> public string Realm { get { return _listener.Realm; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _listener.Realm = value; } } /// <summary> /// Gets or sets a value indicating whether the server is allowed to be bound to /// an address that is already in use. /// </summary> /// <remarks> /// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state, /// you should set this property to <c>true</c>. /// </remarks> /// <value> /// <c>true</c> if the server is allowed to be bound to an address that is already in use; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> public bool ReuseAddress { get { return _listener.ReuseAddress; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _listener.ReuseAddress = value; } } /// <summary> /// Gets or sets the document root path of the server. /// </summary> /// <value> /// A <see cref="string"/> that represents the document root path of the server. /// The default value is <c>"./Public"</c>. /// </value> public string RootPath { get { return _rootPath != null && _rootPath.Length > 0 ? _rootPath : (_rootPath = "./Public"); } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _rootPath = value; } } /// <summary> /// Gets or sets the SSL configuration used to authenticate the server and /// optionally the client for secure connection. /// </summary> /// <value> /// A <see cref="ServerSslConfiguration"/> that represents the configuration used to /// authenticate the server and optionally the client for secure connection. /// </value> public ServerSslConfiguration SslConfiguration { get { return _listener.SslConfiguration; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _listener.SslConfiguration = value; } } /// <summary> /// Gets or sets the delegate called to find the credentials for an identity used to /// authenticate a client. /// </summary> /// <value> /// A <c>Func&lt;<see cref="IIdentity"/>, <see cref="NetworkCredential"/>&gt;</c> delegate that /// references the method(s) used to find the credentials. The default value is a function that /// only returns <see langword="null"/>. /// </value> public Func<IIdentity, NetworkCredential> UserCredentialsFinder { get { return _listener.UserCredentialsFinder; } set { var msg = _state.CheckIfAvailable (true, false, false); if (msg != null) { _logger.Error (msg); return; } _listener.UserCredentialsFinder = value; } } /// <summary> /// Gets or sets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. The default value is /// the same as 1 second. /// </value> public TimeSpan WaitTime { get { return _services.WaitTime; } set { var msg = _state.CheckIfAvailable (true, false, false) ?? value.CheckIfValidWaitTime (); if (msg != null) { _logger.Error (msg); return; } _services.WaitTime = value; } } /// <summary> /// Gets the access to the WebSocket services provided by the server. /// </summary> /// <value> /// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services. /// </value> public WebSocketServiceManager WebSocketServices { get { return _services; } } #endregion #region Public Events /// <summary> /// Occurs when the server receives an HTTP CONNECT request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnConnect; /// <summary> /// Occurs when the server receives an HTTP DELETE request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnDelete; /// <summary> /// Occurs when the server receives an HTTP GET request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnGet; /// <summary> /// Occurs when the server receives an HTTP HEAD request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnHead; /// <summary> /// Occurs when the server receives an HTTP OPTIONS request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnOptions; /// <summary> /// Occurs when the server receives an HTTP PATCH request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnPatch; /// <summary> /// Occurs when the server receives an HTTP POST request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnPost; /// <summary> /// Occurs when the server receives an HTTP PUT request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnPut; /// <summary> /// Occurs when the server receives an HTTP TRACE request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnTrace; #endregion #region Private Methods private void abort () { lock (_sync) { if (!IsListening) return; _state = ServerState.ShuttingDown; } _services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false); _listener.Abort (); _state = ServerState.Stop; } private string checkIfCertificateExists () { if (!_secure) return null; var usr = _listener.SslConfiguration.ServerCertificate != null; var port = EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath); if (usr && port) { _logger.Warn ("The server certificate associated with the port number already exists."); return null; } return !(usr || port) ? "The secure connection requires a server certificate." : null; } private void init (string hostname, System.Net.IPAddress address, int port, bool secure) { _hostname = hostname ?? address.ToString (); _address = address; _port = port; _secure = secure; _listener = new HttpListener (); _listener.Prefixes.Add ( String.Format ("http{0}://{1}:{2}/", secure ? "s" : "", _hostname, port)); _logger = _listener.Log; _services = new WebSocketServiceManager (_logger); _sync = new object (); var os = Environment.OSVersion; _windows = os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX; } private void processRequest (HttpListenerContext context) { var method = context.Request.HttpMethod; var evt = method == "GET" ? OnGet : method == "HEAD" ? OnHead : method == "POST" ? OnPost : method == "PUT" ? OnPut : method == "DELETE" ? OnDelete : method == "OPTIONS" ? OnOptions : method == "TRACE" ? OnTrace : method == "CONNECT" ? OnConnect : method == "PATCH" ? OnPatch : null; if (evt != null) evt (this, new HttpRequestEventArgs (context)); else context.Response.StatusCode = (int) HttpStatusCode.NotImplemented; context.Response.Close (); } private void processRequest (HttpListenerWebSocketContext context) { WebSocketServiceHost host; if (!_services.InternalTryGetServiceHost (context.RequestUri.AbsolutePath, out host)) { context.Close (HttpStatusCode.NotImplemented); return; } host.StartSession (context); } private void receiveRequest () { while (true) { try { var ctx = _listener.GetContext (); ThreadPool.QueueUserWorkItem ( state => { try { if (ctx.Request.IsUpgradeTo ("websocket")) { processRequest (ctx.AcceptWebSocket (null)); return; } processRequest (ctx); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); ctx.Connection.Close (true); } }); } catch (HttpListenerException ex) { _logger.Warn ("Receiving has been stopped.\n reason: " + ex.Message); break; } catch (Exception ex) { _logger.Fatal (ex.ToString ()); break; } } if (IsListening) abort (); } private void startReceiving () { _listener.Start (); _receiveThread = new Thread (new ThreadStart (receiveRequest)); _receiveThread.IsBackground = true; _receiveThread.Start (); } private void stopReceiving (int millisecondsTimeout) { _listener.Close (); _receiveThread.Join (millisecondsTimeout); } private static bool tryCreateUri (string uriString, out Uri result, out string message) { result = null; var uri = uriString.ToUri (); if (uri == null) { message = "An invalid URI string: " + uriString; return false; } if (!uri.IsAbsoluteUri) { message = "Not an absolute URI: " + uriString; return false; } var schm = uri.Scheme; if (!(schm == "http" || schm == "https")) { message = "The scheme part isn't 'http' or 'https': " + uriString; return false; } if (uri.PathAndQuery != "/") { message = "Includes the path or query component: " + uriString; return false; } if (uri.Fragment.Length > 0) { message = "Includes the fragment component: " + uriString; return false; } if (uri.Port == 0) { message = "The port part is zero: " + uriString; return false; } result = uri; message = String.Empty; return true; } #endregion #region Public Methods /// <summary> /// Adds the WebSocket service with the specified behavior, <paramref name="path"/>, /// and <paramref name="initializer"/>. /// </summary> /// <remarks> /// <para> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </para> /// <para> /// <paramref name="initializer"/> returns an initialized specified typed /// <see cref="WebSocketBehavior"/> instance. /// </para> /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to add. /// </param> /// <param name="initializer"> /// A <c>Func&lt;T&gt;</c> delegate that references the method used to initialize /// a new specified typed <see cref="WebSocketBehavior"/> instance (a new /// <see cref="IWebSocketSession"/> instance). /// </param> /// <typeparam name="TBehavior"> /// The type of the behavior of the service to add. The TBehavior must inherit /// the <see cref="WebSocketBehavior"/> class. /// </typeparam> public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer) where TBehavior : WebSocketBehavior { var msg = path.CheckIfValidServicePath () ?? (initializer == null ? "'initializer' is null." : null); if (msg != null) { _logger.Error (msg); return; } _services.Add<TBehavior> (path, initializer); } /// <summary> /// Adds a WebSocket service with the specified behavior and <paramref name="path"/>. /// </summary> /// <remarks> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to add. /// </param> /// <typeparam name="TBehaviorWithNew"> /// The type of the behavior of the service to add. The TBehaviorWithNew must inherit /// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless /// constructor. /// </typeparam> public void AddWebSocketService<TBehaviorWithNew> (string path) where TBehaviorWithNew : WebSocketBehavior, new () { AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ()); } /// <summary> /// Gets the contents of the file with the specified <paramref name="path"/>. /// </summary> /// <returns> /// An array of <see cref="byte"/> that receives the contents of the file, /// or <see langword="null"/> if it doesn't exist. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents the virtual path to the file to find. /// </param> public byte[] GetFile (string path) { path = RootPath + path; if (_windows) path = path.Replace ("/", "\\"); return File.Exists (path) ? File.ReadAllBytes (path) : null; } /// <summary> /// Removes the WebSocket service with the specified <paramref name="path"/>. /// </summary> /// <remarks> /// This method converts <paramref name="path"/> to URL-decoded string, /// and removes <c>'/'</c> from tail end of <paramref name="path"/>. /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to find. /// </param> public bool RemoveWebSocketService (string path) { var msg = path.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); return false; } return _services.Remove (path); } /// <summary> /// Starts receiving the HTTP requests. /// </summary> public void Start () { lock (_sync) { var msg = _state.CheckIfAvailable (true, false, false) ?? checkIfCertificateExists (); if (msg != null) { _logger.Error (msg); return; } _services.Start (); startReceiving (); _state = ServerState.Start; } } /// <summary> /// Stops receiving the HTTP requests. /// </summary> public void Stop () { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } _services.Stop (new CloseEventArgs (), true, true); stopReceiving (5000); _state = ServerState.Stop; } /// <summary> /// Stops receiving the HTTP requests with the specified <see cref="ushort"/> and /// <see cref="string"/> used to stop the WebSocket services. /// </summary> /// <param name="code"> /// A <see cref="ushort"/> that represents the status code indicating the reason for the stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the stop. /// </param> public void Stop (ushort code, string reason) { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckCloseParameters (code, reason, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } if (code == (ushort) CloseStatusCode.NoStatus) { _services.Stop (new CloseEventArgs (), true, true); } else { var send = !code.IsReserved (); _services.Stop (new CloseEventArgs (code, reason), send, send); } stopReceiving (5000); _state = ServerState.Stop; } /// <summary> /// Stops receiving the HTTP requests with the specified <see cref="CloseStatusCode"/> and /// <see cref="string"/> used to stop the WebSocket services. /// </summary> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating /// the reason for the stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the stop. /// </param> public void Stop (CloseStatusCode code, string reason) { lock (_sync) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckCloseParameters (code, reason, false); if (msg != null) { _logger.Error (msg); return; } _state = ServerState.ShuttingDown; } if (code == CloseStatusCode.NoStatus) { _services.Stop (new CloseEventArgs (), true, true); } else { var send = !code.IsReserved (); _services.Stop (new CloseEventArgs (code, reason), send, send); } stopReceiving (5000); _state = ServerState.Stop; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace DI08.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using OpenKh.Common; using OpenKh.Imaging; using OpenKh.Kh2; using System; using System.Drawing; using System.IO; using System.Linq; using Xunit; namespace OpenKh.Tests.kh2 { public class ImgdTests { private const string FilePath = "kh2/res/image-8bit-128-128.imd"; private const string FacFilePath = "kh2/res/image.fac"; [Fact] public void IsValidTest() { using (var stream = new MemoryStream()) { stream.WriteByte(0x49); stream.WriteByte(0x4d); stream.WriteByte(0x47); stream.WriteByte(0x44); stream.SetLength(0x40); stream.Position = 0; Assert.True(Imgd.IsValid(stream)); } } [Fact] public void ReadHeaderTest() => File.OpenRead(FilePath).Using(stream => { var image = Imgd.Read(stream); Assert.Equal(128, image.Size.Width); Assert.Equal(128, image.Size.Height); Assert.Equal(PixelFormat.Indexed8, image.PixelFormat); }); [Theory] [InlineData("4bit-128-128")] [InlineData("4bit-256-128")] [InlineData("4bit-256-512")] [InlineData("4bit-512-128")] [InlineData("4bit-512-512")] [InlineData("8bit-128-128")] [InlineData("8bit-128-64")] [InlineData("8bit-256-128")] [InlineData("8bit-256-256")] [InlineData("8bit-32-32")] [InlineData("8bit-48-48")] [InlineData("8bit-512-256")] [InlineData("8bit-512-512")] [InlineData("8bit-64-64")] [InlineData("32bit-512-512")] public void IsWritingBackCorrectly(string baseName) => File.OpenRead($"kh2/res/image-{baseName}.imd").Using(stream => { var expectedData = new byte[stream.Length]; stream.Read(expectedData, 0, expectedData.Length); var image = Imgd.Read(new MemoryStream(expectedData)); using (var dstStream = new MemoryStream(expectedData.Length)) { image.Write(dstStream); dstStream.Position = 0; var actualData = new byte[dstStream.Length]; dstStream.Read(actualData, 0, actualData.Length); Assert.Equal(expectedData.Length, actualData.Length); Assert.Equal(expectedData, actualData); } }); [Theory] [InlineData("4bit-128-128")] [InlineData("4bit-256-128")] [InlineData("4bit-256-512")] [InlineData("4bit-512-128")] [InlineData("4bit-512-512")] [InlineData("8bit-128-128")] [InlineData("8bit-128-64")] [InlineData("8bit-256-128")] [InlineData("8bit-256-256")] [InlineData("8bit-32-32")] [InlineData("8bit-48-48")] [InlineData("8bit-512-256")] [InlineData("8bit-512-512")] [InlineData("8bit-64-64")] public void IsCreatingCorrectlyTest(string baseName) => File.OpenRead($"kh2/res/image-{baseName}.imd").Using(stream => { var expectedData = new byte[stream.Length]; stream.Read(expectedData, 0, expectedData.Length); var image = Imgd.Read(new MemoryStream(expectedData)); using (var dstStream = new MemoryStream(expectedData.Length)) { var newImage = Imgd.Create( image.Size, image.PixelFormat, image.GetData(), image.GetClut(), image.IsSwizzled); Assert.Equal(image.GetClut(), newImage.GetClut()); Assert.Equal(image.GetData(), newImage.GetData()); newImage.Write(dstStream); dstStream.Position = 0; var actualData = new byte[dstStream.Length]; dstStream.Read(actualData, 0, actualData.Length); Assert.Equal(expectedData.Length, actualData.Length); Assert.Equal(expectedData, actualData); } }); [Theory] [InlineData(FilePath, false)] [InlineData(FacFilePath, true)] public void IsFac(string fileName, bool expected) => Assert.Equal(expected, File.OpenRead(fileName).Using(stream => Imgd.IsFac(stream))); [Fact] public void ReadAndWriteFac() => File.OpenRead(FacFilePath) .Using(x => Helpers.AssertStream(x, inStream => { var images = Imgd.ReadAsFac(inStream).ToList(); Assert.Equal(3, images.Count); var outStream = new MemoryStream(); Imgd.WriteAsFac(outStream, images); return outStream; })); void CreateImgdAndComparePixelData( byte[] pixelData, Func<byte[], Imgd> imgdFactory ) { var imgd = imgdFactory(pixelData); var temp = new MemoryStream(); imgd.Write(temp); temp.Position = 0; var loaded = Imgd.Read(temp); Assert.Equal( pixelData, loaded.GetData() ); } [Fact] public void TestPixelOrder4() => CreateImgdAndComparePixelData( new byte[] { 0x12, 0x34, }, pixelData => Imgd.Create( new System.Drawing.Size(2, 2), PixelFormat.Indexed4, pixelData, new byte[4 * 16], false ) ); [Fact] public void TestPixelOrder4Swizzled() => CreateImgdAndComparePixelData( new byte[] { 0x12, 0x34, } .Concat(new byte[128 * 128 / 2 - 2]) .ToArray(), pixelData => Imgd.Create( new System.Drawing.Size(128, 128), PixelFormat.Indexed4, pixelData, new byte[4 * 16], true ) ); [Fact] public void TestPixelOrder8() => CreateImgdAndComparePixelData( new byte[] { 0x12, 0x34, 0x56, 0x78, }, pixelData => Imgd.Create( new System.Drawing.Size(2, 2), PixelFormat.Indexed8, pixelData, new byte[4 * 256], false ) ); [Fact] public void TestPixelOrder8Swizzled() => CreateImgdAndComparePixelData( new byte[] { 0x12, 0x34, 0x56, 0x78, } .Concat(new byte[128 * 64 - 4]) .ToArray(), pixelData => Imgd.Create( new System.Drawing.Size(128, 64), PixelFormat.Indexed8, pixelData, new byte[4 * 256], true ) ); [Fact] public void ReadRgba8888PixelOrder() { var imgd = File.OpenRead($"kh2/res/2x2x32.imd").Using(Imgd.Read); Assert.Equal(new Size(2, 2), imgd.Size); Assert.Equal(PixelFormat.Rgba8888, imgd.PixelFormat); Assert.Equal( new byte[] { // GetData(): B, G, R, A 0xFF, 0x7F, 0x27, 0xFF, 0x22, 0xB1, 0x4C, 0xFF, 0x00, 0xA2, 0xE8, 0xFF, 0xFF, 0xF2, 0x00, 0xFF, }, imgd.GetData() ); Assert.Equal( new byte[] { // Data: R, G, B, A 0x27, 0x7F, 0xFF, 0xFF, 0x4C, 0xB1, 0x22, 0xFF, 0xE8, 0xA2, 0x00, 0xFF, 0x00, 0xF2, 0xFF, 0xFF, }, imgd.Data ); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.HtmlTextWriter.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI { public partial class HtmlTextWriter : TextWriter { #region Methods and constructors public virtual new void AddAttribute(HtmlTextWriterAttribute key, string value, bool fEncode) { } protected virtual new void AddAttribute(string name, string value, HtmlTextWriterAttribute key) { } public virtual new void AddAttribute(HtmlTextWriterAttribute key, string value) { } public virtual new void AddAttribute(string name, string value) { } public virtual new void AddAttribute(string name, string value, bool fEndode) { } public virtual new void AddStyleAttribute(HtmlTextWriterStyle key, string value) { } public virtual new void AddStyleAttribute(string name, string value) { } protected virtual new void AddStyleAttribute(string name, string value, HtmlTextWriterStyle key) { } public virtual new void BeginRender() { } public override void Close() { } protected string EncodeAttributeValue(string value, bool fEncode) { return default(string); } protected virtual new string EncodeAttributeValue(HtmlTextWriterAttribute attrKey, string value) { return default(string); } protected string EncodeUrl(string url) { return default(string); } public virtual new void EndRender() { } public virtual new void EnterStyle(System.Web.UI.WebControls.Style style) { } public virtual new void EnterStyle(System.Web.UI.WebControls.Style style, HtmlTextWriterTag tag) { } public virtual new void ExitStyle(System.Web.UI.WebControls.Style style, HtmlTextWriterTag tag) { } public virtual new void ExitStyle(System.Web.UI.WebControls.Style style) { } protected virtual new void FilterAttributes() { } public override void Flush() { } protected HtmlTextWriterAttribute GetAttributeKey(string attrName) { return default(HtmlTextWriterAttribute); } protected string GetAttributeName(HtmlTextWriterAttribute attrKey) { return default(string); } protected HtmlTextWriterStyle GetStyleKey(string styleName) { return default(HtmlTextWriterStyle); } protected string GetStyleName(HtmlTextWriterStyle styleKey) { return default(string); } protected virtual new HtmlTextWriterTag GetTagKey(string tagName) { return default(HtmlTextWriterTag); } protected virtual new string GetTagName(HtmlTextWriterTag tagKey) { return default(string); } public HtmlTextWriter(TextWriter writer) { } public HtmlTextWriter(TextWriter writer, string tabString) { } protected bool IsAttributeDefined(HtmlTextWriterAttribute key, out string value) { value = default(string); return default(bool); } protected bool IsAttributeDefined(HtmlTextWriterAttribute key) { return default(bool); } protected bool IsStyleAttributeDefined(HtmlTextWriterStyle key, out string value) { value = default(string); return default(bool); } protected bool IsStyleAttributeDefined(HtmlTextWriterStyle key) { return default(bool); } public virtual new bool IsValidFormAttribute(string attribute) { return default(bool); } protected virtual new bool OnAttributeRender(string name, string value, HtmlTextWriterAttribute key) { return default(bool); } protected virtual new bool OnStyleAttributeRender(string name, string value, HtmlTextWriterStyle key) { return default(bool); } protected virtual new bool OnTagRender(string name, HtmlTextWriterTag key) { return default(bool); } protected virtual new void OutputTabs() { } protected string PopEndTag() { return default(string); } protected void PushEndTag(string endTag) { } protected static void RegisterAttribute(string name, HtmlTextWriterAttribute key) { } protected static void RegisterStyle(string name, HtmlTextWriterStyle key) { } protected static void RegisterTag(string name, HtmlTextWriterTag key) { } protected virtual new string RenderAfterContent() { return default(string); } protected virtual new string RenderAfterTag() { return default(string); } protected virtual new string RenderBeforeContent() { return default(string); } protected virtual new string RenderBeforeTag() { return default(string); } public virtual new void RenderBeginTag(HtmlTextWriterTag tagKey) { } public virtual new void RenderBeginTag(string tagName) { } public virtual new void RenderEndTag() { } public override void Write(string format, Object arg0, Object arg1) { } public override void Write(string format, Object arg0) { } public override void Write(Object value) { } public override void Write(float value) { } public override void Write(long value) { } public override void Write(int value) { } public override void Write(string format, Object[] arg) { } public override void Write(char[] buffer, int index, int count) { } public override void Write(char[] buffer) { } public override void Write(char value) { } public override void Write(bool value) { } public override void Write(double value) { } public override void Write(string s) { } public virtual new void WriteAttribute(string name, string value, bool fEncode) { } public virtual new void WriteAttribute(string name, string value) { } public virtual new void WriteBeginTag(string tagName) { } public virtual new void WriteBreak() { } public virtual new void WriteEncodedText(string text) { } public virtual new void WriteEncodedUrl(string url) { } public virtual new void WriteEncodedUrlParameter(string urlText) { } public virtual new void WriteEndTag(string tagName) { } public virtual new void WriteFullBeginTag(string tagName) { } public override void WriteLine(Object value) { } public override void WriteLine(long value) { } public override void WriteLine(int value) { } public override void WriteLine(string format, Object arg0) { } public override void WriteLine(string format, Object[] arg) { } public override void WriteLine(string format, Object arg0, Object arg1) { } public override void WriteLine(uint value) { } public override void WriteLine(bool value) { } public override void WriteLine(char value) { } public override void WriteLine(string s) { } public override void WriteLine() { } public override void WriteLine(double value) { } public override void WriteLine(float value) { } public override void WriteLine(char[] buffer) { } public override void WriteLine(char[] buffer, int index, int count) { } public void WriteLineNoTabs(string s) { } public virtual new void WriteStyleAttribute(string name, string value) { } public virtual new void WriteStyleAttribute(string name, string value, bool fEncode) { } protected void WriteUrlEncodedString(string text, bool argument) { } #endregion #region Properties and indexers public override Encoding Encoding { get { return default(Encoding); } } public int Indent { get { return default(int); } set { } } public TextWriter InnerWriter { get { return default(TextWriter); } set { } } public override string NewLine { get { return default(string); } set { } } protected HtmlTextWriterTag TagKey { get { return default(HtmlTextWriterTag); } set { } } protected string TagName { get { return default(string); } set { } } #endregion #region Fields public static string DefaultTabString; public static char DoubleQuoteChar; public static string EndTagLeftChars; public static char EqualsChar; public static string EqualsDoubleQuoteString; public static string SelfClosingChars; public static string SelfClosingTagEnd; public static char SemicolonChar; public static char SingleQuoteChar; public static char SlashChar; public static char SpaceChar; public static char StyleEqualsChar; public static char TagLeftChar; public static char TagRightChar; #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBAsyncTests : CSharpTestBase { [Fact] [WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")] [WorkItem(631350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631350")] [WorkItem(643501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/643501")] [WorkItem(689616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/689616")] public void TestAsyncDebug() { var text = @" using System; using System.Threading; using System.Threading.Tasks; class DynamicMembers { public Func<Task<int>> Prop { get; set; } } class TestCase { public static int Count = 0; public async void Run() { DynamicMembers dc2 = new DynamicMembers(); dc2.Prop = async () => { await Task.Delay(10000); return 3; }; var rez2 = await dc2.Prop(); if (rez2 == 3) Count++; Driver.Result = TestCase.Count - 1; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static int Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); return Driver.Result; } }"; var compilation = CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll).VerifyDiagnostics(); var v = CompileAndVerify(compilation); v.VerifyIL("TestCase.<Run>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 301 (0x12d) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter<int> V_1, int V_2, TestCase.<Run>d__1 V_3, bool V_4, System.Exception V_5) ~IL_0000: ldarg.0 IL_0001: ldfld ""int TestCase.<Run>d__1.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_008b -IL_000e: nop -IL_000f: ldarg.0 IL_0010: newobj ""DynamicMembers..ctor()"" IL_0015: stfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1"" -IL_001a: ldarg.0 IL_001b: ldfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1"" IL_0020: ldsfld ""System.Func<System.Threading.Tasks.Task<int>> TestCase.<>c.<>9__1_0"" IL_0025: dup IL_0026: brtrue.s IL_003f IL_0028: pop IL_0029: ldsfld ""TestCase.<>c TestCase.<>c.<>9"" IL_002e: ldftn ""System.Threading.Tasks.Task<int> TestCase.<>c.<Run>b__1_0()"" IL_0034: newobj ""System.Func<System.Threading.Tasks.Task<int>>..ctor(object, System.IntPtr)"" IL_0039: dup IL_003a: stsfld ""System.Func<System.Threading.Tasks.Task<int>> TestCase.<>c.<>9__1_0"" IL_003f: callvirt ""void DynamicMembers.Prop.set"" IL_0044: nop -IL_0045: ldarg.0 IL_0046: ldfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1"" IL_004b: callvirt ""System.Func<System.Threading.Tasks.Task<int>> DynamicMembers.Prop.get"" IL_0050: callvirt ""System.Threading.Tasks.Task<int> System.Func<System.Threading.Tasks.Task<int>>.Invoke()"" IL_0055: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_005a: stloc.1 ~IL_005b: ldloca.s V_1 IL_005d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0062: brtrue.s IL_00a7 IL_0064: ldarg.0 IL_0065: ldc.i4.0 IL_0066: dup IL_0067: stloc.0 IL_0068: stfld ""int TestCase.<Run>d__1.<>1__state"" <IL_006d: ldarg.0 IL_006e: ldloc.1 IL_006f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1"" IL_0074: ldarg.0 IL_0075: stloc.3 IL_0076: ldarg.0 IL_0077: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder"" IL_007c: ldloca.s V_1 IL_007e: ldloca.s V_3 IL_0080: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, TestCase.<Run>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref TestCase.<Run>d__1)"" IL_0085: nop IL_0086: leave IL_012c >IL_008b: ldarg.0 IL_008c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1"" IL_0091: stloc.1 IL_0092: ldarg.0 IL_0093: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1"" IL_0098: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_009e: ldarg.0 IL_009f: ldc.i4.m1 IL_00a0: dup IL_00a1: stloc.0 IL_00a2: stfld ""int TestCase.<Run>d__1.<>1__state"" IL_00a7: ldloca.s V_1 IL_00a9: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ae: stloc.2 IL_00af: ldloca.s V_1 IL_00b1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00b7: ldarg.0 IL_00b8: ldloc.2 IL_00b9: stfld ""int TestCase.<Run>d__1.<>s__3"" IL_00be: ldarg.0 IL_00bf: ldarg.0 IL_00c0: ldfld ""int TestCase.<Run>d__1.<>s__3"" IL_00c5: stfld ""int TestCase.<Run>d__1.<rez2>5__2"" -IL_00ca: ldarg.0 IL_00cb: ldfld ""int TestCase.<Run>d__1.<rez2>5__2"" IL_00d0: ldc.i4.3 IL_00d1: ceq IL_00d3: stloc.s V_4 ~IL_00d5: ldloc.s V_4 IL_00d7: brfalse.s IL_00e5 -IL_00d9: ldsfld ""int TestCase.Count"" IL_00de: ldc.i4.1 IL_00df: add IL_00e0: stsfld ""int TestCase.Count"" -IL_00e5: ldsfld ""int TestCase.Count"" IL_00ea: ldc.i4.1 IL_00eb: sub IL_00ec: stsfld ""int Driver.Result"" -IL_00f1: ldsfld ""System.Threading.AutoResetEvent Driver.CompletedSignal"" IL_00f6: callvirt ""bool System.Threading.EventWaitHandle.Set()"" IL_00fb: pop IL_00fc: leave.s IL_0118 } catch System.Exception { ~$IL_00fe: stloc.s V_5 IL_0100: ldarg.0 IL_0101: ldc.i4.s -2 IL_0103: stfld ""int TestCase.<Run>d__1.<>1__state"" IL_0108: ldarg.0 IL_0109: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder"" IL_010e: ldloc.s V_5 IL_0110: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0115: nop IL_0116: leave.s IL_012c } -IL_0118: ldarg.0 IL_0119: ldc.i4.s -2 IL_011b: stfld ""int TestCase.<Run>d__1.<>1__state"" ~IL_0120: ldarg.0 IL_0121: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder"" IL_0126: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_012b: nop IL_012c: ret }", sequencePoints: "TestCase+<Run>d__1.MoveNext"); v.VerifyPdb(@"<symbols> <methods> <method containingType=""DynamicMembers"" name=""get_Prop""> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""39"" /> </sequencePoints> </method> <method containingType=""DynamicMembers"" name=""set_Prop"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""40"" endLine=""8"" endColumn=""44"" /> </sequencePoints> </method> <method containingType=""TestCase"" name=""Run""> <customDebugInfo> <forwardIterator name=""&lt;Run&gt;d__1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""26"" /> <slot kind=""0"" offset=""139"" /> <slot kind=""28"" offset=""146"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset=""86"" /> </encLambdaMap> </customDebugInfo> </method> <method containingType=""TestCase"" name="".cctor""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""33"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> <namespace name=""System.Threading"" /> <namespace name=""System.Threading.Tasks"" /> </scope> </method> <method containingType=""Driver"" name=""Main""> <customDebugInfo> <forward declaringType=""TestCase"" methodName="".cctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""30"" startColumn=""5"" endLine=""30"" endColumn=""6"" /> <entry offset=""0x1"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""32"" /> <entry offset=""0x7"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""17"" /> <entry offset=""0xe"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""35"" /> <entry offset=""0x19"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""30"" /> <entry offset=""0x21"" startLine=""36"" startColumn=""5"" endLine=""36"" endColumn=""6"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x23""> <local name=""t"" il_index=""0"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" /> </scope> </method> <method containingType=""Driver"" name="".cctor""> <customDebugInfo> <forward declaringType=""TestCase"" methodName="".cctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""35"" /> <entry offset=""0x6"" startLine=""28"" startColumn=""5"" endLine=""28"" endColumn=""78"" /> </sequencePoints> </method> <method containingType=""TestCase+&lt;&gt;c"" name=""&lt;Run&gt;b__1_0""> <customDebugInfo> <forwardIterator name=""&lt;&lt;Run&gt;b__1_0&gt;d"" /> </customDebugInfo> </method> <method containingType=""TestCase+&lt;Run&gt;d__1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""TestCase"" methodName="".cctor"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x12c"" /> <slot startOffset=""0x0"" endOffset=""0x12c"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""146"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""1"" offset=""173"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" /> <entry offset=""0xf"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""51"" /> <entry offset=""0x1a"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""71"" /> <entry offset=""0x45"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""37"" /> <entry offset=""0x5b"" hidden=""true"" /> <entry offset=""0xca"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""23"" /> <entry offset=""0xd5"" hidden=""true"" /> <entry offset=""0xd9"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""32"" /> <entry offset=""0xe5"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""44"" /> <entry offset=""0xf1"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""38"" /> <entry offset=""0xfe"" hidden=""true"" /> <entry offset=""0x118"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" /> <entry offset=""0x120"" hidden=""true"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xfe"" /> <kickoffMethod declaringType=""TestCase"" methodName=""Run"" /> <await yield=""0x6d"" resume=""0x8b"" declaringType=""TestCase+&lt;Run&gt;d__1"" methodName=""MoveNext"" /> </asyncInfo> </method> <method containingType=""TestCase+&lt;&gt;c+&lt;&lt;Run&gt;b__1_0&gt;d"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""TestCase"" methodName="".cctor"" /> <encLocalSlotMap> <slot kind=""27"" offset=""86"" /> <slot kind=""20"" offset=""86"" /> <slot kind=""33"" offset=""88"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xe"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""33"" /> <entry offset=""0xf"" startLine=""16"" startColumn=""34"" endLine=""16"" endColumn=""58"" /> <entry offset=""0x1f"" hidden=""true"" /> <entry offset=""0x78"" startLine=""16"" startColumn=""59"" endLine=""16"" endColumn=""68"" /> <entry offset=""0x7c"" hidden=""true"" /> <entry offset=""0x96"" startLine=""16"" startColumn=""69"" endLine=""16"" endColumn=""70"" /> <entry offset=""0x9e"" hidden=""true"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""TestCase+&lt;&gt;c"" methodName=""&lt;Run&gt;b__1_0"" /> <await yield=""0x31"" resume=""0x4c"" declaringType=""TestCase+&lt;&gt;c+&lt;&lt;Run&gt;b__1_0&gt;d"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] [WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")] public void TestAsyncDebug2() { var text = @" using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { private static Random random = new Random(); static void Main(string[] args) { new Program().QBar(); } async void QBar() { await ZBar(); } async Task<List<int>> ZBar() { var addedInts = new List<int>(); foreach (var z in new[] {1, 2, 3}) { var newInt = await GetNextInt(random); addedInts.Add(newInt); } return addedInts; } private Task<int> GetNextInt(Random random) { return Task.FromResult(random.Next()); } } }"; var compilation = CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll).VerifyDiagnostics(); compilation.VerifyPdb(@" <symbols> <methods> <method containingType=""ConsoleApplication1.Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> <namespace usingCount=""3"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" /> <entry offset=""0x1"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" /> <entry offset=""0xc"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Threading.Tasks"" /> </scope> </method> <method containingType=""ConsoleApplication1.Program"" name=""QBar""> <customDebugInfo> <forwardIterator name=""&lt;QBar&gt;d__2"" /> </customDebugInfo> </method> <method containingType=""ConsoleApplication1.Program"" name=""ZBar""> <customDebugInfo> <forwardIterator name=""&lt;ZBar&gt;d__3"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""6"" offset=""61"" /> <slot kind=""8"" offset=""61"" /> <slot kind=""0"" offset=""61"" /> <slot kind=""0"" offset=""132"" /> <slot kind=""28"" offset=""141"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""ConsoleApplication1.Program"" name=""GetNextInt"" parameterNames=""random""> <customDebugInfo> <forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" /> <entry offset=""0x1"" startLine=""31"" startColumn=""13"" endLine=""31"" endColumn=""51"" /> <entry offset=""0xf"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" /> </sequencePoints> </method> <method containingType=""ConsoleApplication1.Program"" name="".cctor""> <customDebugInfo> <forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""53"" /> </sequencePoints> </method> <method containingType=""ConsoleApplication1.Program+&lt;QBar&gt;d__2"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""15"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xe"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" /> <entry offset=""0xf"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""26"" /> <entry offset=""0x20"" hidden=""true"" /> <entry offset=""0x7b"" hidden=""true"" /> <entry offset=""0x93"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" /> <entry offset=""0x9b"" hidden=""true"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0x7b"" /> <kickoffMethod declaringType=""ConsoleApplication1.Program"" methodName=""QBar"" /> <await yield=""0x32"" resume=""0x4d"" declaringType=""ConsoleApplication1.Program+&lt;QBar&gt;d__2"" methodName=""MoveNext"" /> </asyncInfo> </method> <method containingType=""ConsoleApplication1.Program+&lt;ZBar&gt;d__3"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x14e"" /> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0x41"" endOffset=""0xed"" /> <slot startOffset=""0x54"" endOffset=""0xed"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""20"" offset=""0"" /> <slot kind=""33"" offset=""141"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0x11"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" /> <entry offset=""0x12"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""45"" /> <entry offset=""0x1d"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""20"" /> <entry offset=""0x1e"" startLine=""22"" startColumn=""31"" endLine=""22"" endColumn=""46"" /> <entry offset=""0x3c"" hidden=""true"" /> <entry offset=""0x41"" startLine=""22"" startColumn=""22"" endLine=""22"" endColumn=""27"" /> <entry offset=""0x54"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" /> <entry offset=""0x55"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""55"" /> <entry offset=""0x6b"" hidden=""true"" /> <entry offset=""0xdb"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""39"" /> <entry offset=""0xed"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" /> <entry offset=""0xee"" hidden=""true"" /> <entry offset=""0xfc"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""30"" /> <entry offset=""0x116"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""30"" /> <entry offset=""0x11f"" hidden=""true"" /> <entry offset=""0x139"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" /> <entry offset=""0x141"" hidden=""true"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""ConsoleApplication1.Program"" methodName=""ZBar"" /> <await yield=""0x7d"" resume=""0x9c"" declaringType=""ConsoleApplication1.Program+&lt;ZBar&gt;d__3"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] [WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")] [WorkItem(690180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690180")] public void TestAsyncDebug3() { var text = @" class TestCase { static async void Await(dynamic d) { int rez = await d; } }"; var compilation = CreateCompilationWithMscorlib45( text, options: TestOptions.DebugDll, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }) .VerifyDiagnostics(); compilation.VerifyPdb(@" <symbols> <methods> <method containingType=""TestCase"" name=""Await"" parameterNames=""d""> <customDebugInfo> <forwardIterator name=""&lt;Await&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""28"" offset=""21"" /> <slot kind=""28"" offset=""21"" ordinal=""1"" /> <slot kind=""28"" offset=""21"" ordinal=""2"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""TestCase+&lt;Await&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x261"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""21"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0x11"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" /> <entry offset=""0x12"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""27"" /> <entry offset=""0xae"" hidden=""true"" /> <entry offset=""0x233"" hidden=""true"" /> <entry offset=""0x24d"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" /> <entry offset=""0x255"" hidden=""true"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0x233"" /> <kickoffMethod declaringType=""TestCase"" methodName=""Await"" parameterNames=""d"" /> <await yield=""0x148"" resume=""0x190"" declaringType=""TestCase+&lt;Await&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void TestAsyncDebug4() { var text = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await Task.Delay(1); return 1; } }"; var v = CompileAndVerify(CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll)); v.VerifyIL("C.F", @" { // Code size 52 (0x34) .maxstack 2 .locals init (C.<F>d__0 V_0, System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> V_1) IL_0000: newobj ""C.<F>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldc.i4.m1 IL_0013: stfld ""int C.<F>d__0.<>1__state"" IL_0018: ldloc.0 IL_0019: ldfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_001e: stloc.1 IL_001f: ldloca.s V_1 IL_0021: ldloca.s V_0 IL_0023: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<C.<F>d__0>(ref C.<F>d__0)"" IL_0028: ldloc.0 IL_0029: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_002e: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_0033: ret }", sequencePoints: "C.F"); v.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 168 (0xa8) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0048 -IL_000e: nop -IL_000f: ldc.i4.1 IL_0010: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)"" IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_001a: stloc.2 ~IL_001b: ldloca.s V_2 IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0022: brtrue.s IL_0064 IL_0024: ldarg.0 IL_0025: ldc.i4.0 IL_0026: dup IL_0027: stloc.0 IL_0028: stfld ""int C.<F>d__0.<>1__state"" <IL_002d: ldarg.0 IL_002e: ldloc.2 IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0034: ldarg.0 IL_0035: stloc.3 IL_0036: ldarg.0 IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_003c: ldloca.s V_2 IL_003e: ldloca.s V_3 IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)"" IL_0045: nop IL_0046: leave.s IL_00a7 >IL_0048: ldarg.0 IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_004e: stloc.2 IL_004f: ldarg.0 IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1"" IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_005b: ldarg.0 IL_005c: ldc.i4.m1 IL_005d: dup IL_005e: stloc.0 IL_005f: stfld ""int C.<F>d__0.<>1__state"" IL_0064: ldloca.s V_2 IL_0066: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_006b: nop IL_006c: ldloca.s V_2 IL_006e: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" -IL_0074: ldc.i4.1 IL_0075: stloc.1 IL_0076: leave.s IL_0092 } catch System.Exception { ~IL_0078: stloc.s V_4 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int C.<F>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0088: ldloc.s V_4 IL_008a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_008f: nop IL_0090: leave.s IL_00a7 } -IL_0092: ldarg.0 IL_0093: ldc.i4.s -2 IL_0095: stfld ""int C.<F>d__0.<>1__state"" ~IL_009a: ldarg.0 IL_009b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00a0: ldloc.1 IL_00a1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00a6: nop IL_00a7: ret } ", sequencePoints: "C+<F>d__0.MoveNext"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DisplayClass_InBetweenSuspensionPoints_Release() { string source = @" using System; using System.Threading.Tasks; class C { static async Task M(int b) { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); await M(x1 + x2 + x3); } } "; // TODO: Currently we don't have means necessary to pass information about the display // class being pushed on evaluation stack, so that EE could find the locals. // Thus the locals are not available in EE. var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xa"" hidden=""true"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x17"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x25"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x36"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""31"" /> <entry offset=""0x55"" hidden=""true"" /> <entry offset=""0xab"" hidden=""true"" /> <entry offset=""0xc2"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" /> <entry offset=""0xca"" hidden=""true"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd6""> <scope startOffset=""0xa"" endOffset=""0xab""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""1"" il_start=""0xa"" il_end=""0xab"" attributes=""0"" /> </scope> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" /> <await yield=""0x67"" resume=""0x7e"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M"" parameterNames=""b""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DisplayClass_InBetweenSuspensionPoints_Debug() { string source = @" using System; using System.Threading.Tasks; class C { static async Task M(int b) { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); await M(x1 + x2 + x3); // possible EnC edit: // Console.WriteLine(x1); } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "b", "<>8__1", // display class "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x10d"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""129"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0x11"" hidden=""true"" /> <entry offset=""0x1c"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0x1d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x35"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x41"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x58"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""31"" /> <entry offset=""0x86"" hidden=""true"" /> <entry offset=""0xe1"" hidden=""true"" /> <entry offset=""0xf9"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" /> <entry offset=""0x101"" hidden=""true"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" /> <await yield=""0x98"" resume=""0xb3"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M"" parameterNames=""b""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DisplayClass_AcrossSuspensionPoints_Release() { string source = @" using System; using System.Threading.Tasks; class C { static async Task M(int b) { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); await Task.Delay(0); Console.WriteLine(x1); } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<>8__1", // display class "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0xeb"" /> </hoistedLocalScopes> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xa"" hidden=""true"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x2d"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x39"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x4f"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""29"" /> <entry offset=""0x5b"" hidden=""true"" /> <entry offset=""0xaf"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""31"" /> <entry offset=""0xc1"" hidden=""true"" /> <entry offset=""0xd8"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" /> <entry offset=""0xe0"" hidden=""true"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" /> <await yield=""0x6d"" resume=""0x84"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M"" parameterNames=""b""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DisplayClass_AcrossSuspensionPoints_Debug() { string source = @" using System; using System.Threading.Tasks; class C { static async Task M(int b) { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); await Task.Delay(0); Console.WriteLine(x1); } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "b", "<>8__1", // display class "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0xfc"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""129"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0x11"" hidden=""true"" /> <entry offset=""0x1c"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0x1d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" /> <entry offset=""0x35"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" /> <entry offset=""0x41"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" /> <entry offset=""0x58"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""29"" /> <entry offset=""0x64"" hidden=""true"" /> <entry offset=""0xbd"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""31"" /> <entry offset=""0xd0"" hidden=""true"" /> <entry offset=""0xe8"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" /> <entry offset=""0xf0"" hidden=""true"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" /> <await yield=""0x76"" resume=""0x91"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M"" parameterNames=""b""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [Fact] public void DynamicLocal_AcrossSuspensionPoints_Debug() { string source = @" using System.Threading.Tasks; class C { static async Task M() { dynamic d = 1; await Task.Delay(0); d.ToString(); } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<d>5__1", "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); // CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching // any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic. v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x109"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""35"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" /> <entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" /> <entry offset=""0x27"" hidden=""true"" /> <entry offset=""0x83"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" /> <entry offset=""0xdd"" hidden=""true"" /> <entry offset=""0xf5"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" /> <entry offset=""0xfd"" hidden=""true"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10a""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" /> <await yield=""0x39"" resume=""0x57"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols> "); } [WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")] [WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337")] [WorkItem(1070519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070519")] [Fact] public void DynamicLocal_InBetweenSuspensionPoints_Release() { string source = @" using System.Threading.Tasks; class C { static async Task M() { dynamic d = 1; d.ToString(); await Task.Delay(0); } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xd"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" /> <entry offset=""0x14"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" /> <entry offset=""0x64"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" /> <entry offset=""0x70"" hidden=""true"" /> <entry offset=""0xc6"" hidden=""true"" /> <entry offset=""0xdd"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" /> <entry offset=""0xe5"" hidden=""true"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xf1""> <namespace name=""System.Threading.Tasks"" /> <scope startOffset=""0xd"" endOffset=""0xc6""> <local name=""d"" il_index=""1"" il_start=""0xd"" il_end=""0xc6"" attributes=""0"" /> </scope> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" /> <await yield=""0x82"" resume=""0x99"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> </customDebugInfo> </method> </methods> </symbols> "); } [WorkItem(1070519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070519")] [Fact] public void DynamicLocal_InBetweenSuspensionPoints_Debug() { string source = @" using System.Threading.Tasks; class C { static async Task M() { dynamic d = 1; d.ToString(); await Task.Delay(0); // Possible EnC edit: // System.Console.WriteLine(d); } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<d>5__1", "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x109"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""33"" offset=""58"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0x11"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" /> <entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" /> <entry offset=""0x76"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" /> <entry offset=""0x82"" hidden=""true"" /> <entry offset=""0xdd"" hidden=""true"" /> <entry offset=""0xf5"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" /> <entry offset=""0xfd"" hidden=""true"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10a""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""M"" /> <await yield=""0x94"" resume=""0xaf"" declaringType=""C+&lt;M&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols> "); } [Fact] public void VariableScopeNotContainingSuspensionPoint() { string source = @" using System; using System.Threading.Tasks; class C { static async Task M() { { int x = 1; Console.WriteLine(x); } { await Task.Delay(0); } } } "; // We need to hoist x even though its scope doesn't contain await. // The scopes may be merged by an EnC edit: // // { // int x = 1; // Console.WriteLine(x); // await Task.Delay(0); // Console.WriteLine(x); // } var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<x>5__1", "<>u__1", // awaiter }, module.GetFieldNames("C.<M>d__0")); }); } [Fact] public void AwaitInFinally() { string source = @" using System; using System.Threading.Tasks; class C { static async Task<int> G() { int x = 42; try { } finally { x = await G(); } return x; } }"; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<x>5__1", "<>s__2", "<>s__3", "<>s__4", "<>u__1", // awaiter }, module.GetFieldNames("C.<G>d__0")); }); v.VerifyPdb("C.G", @" <symbols> <methods> <method containingType=""C"" name=""G""> <customDebugInfo> <forwardIterator name=""&lt;G&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""22"" offset=""34"" /> <slot kind=""23"" offset=""34"" /> <slot kind=""28"" offset=""105"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); v.VerifyIL("C.<G>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 286 (0x11e) .maxstack 3 .locals init (int V_0, int V_1, object V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, int V_4, C.<G>d__0 V_5, System.Exception V_6) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<G>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0070 -IL_000e: nop -IL_000f: ldarg.0 IL_0010: ldc.i4.s 42 IL_0012: stfld ""int C.<G>d__0.<x>5__1"" ~IL_0017: ldarg.0 IL_0018: ldnull IL_0019: stfld ""object C.<G>d__0.<>s__2"" IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: stfld ""int C.<G>d__0.<>s__3"" .try { -IL_0025: nop -IL_0026: nop ~IL_0027: leave.s IL_0033 } catch object { ~IL_0029: stloc.2 IL_002a: ldarg.0 IL_002b: ldloc.2 IL_002c: stfld ""object C.<G>d__0.<>s__2"" IL_0031: leave.s IL_0033 } -IL_0033: nop -IL_0034: call ""System.Threading.Tasks.Task<int> C.G()"" IL_0039: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_003e: stloc.3 ~IL_003f: ldloca.s V_3 IL_0041: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0046: brtrue.s IL_008c IL_0048: ldarg.0 IL_0049: ldc.i4.0 IL_004a: dup IL_004b: stloc.0 IL_004c: stfld ""int C.<G>d__0.<>1__state"" <IL_0051: ldarg.0 IL_0052: ldloc.3 IL_0053: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1"" IL_0058: ldarg.0 IL_0059: stloc.s V_5 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder"" IL_0061: ldloca.s V_3 IL_0063: ldloca.s V_5 IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<G>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<G>d__0)"" IL_006a: nop IL_006b: leave IL_011d >IL_0070: ldarg.0 IL_0071: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1"" IL_0076: stloc.3 IL_0077: ldarg.0 IL_0078: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1"" IL_007d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0083: ldarg.0 IL_0084: ldc.i4.m1 IL_0085: dup IL_0086: stloc.0 IL_0087: stfld ""int C.<G>d__0.<>1__state"" IL_008c: ldloca.s V_3 IL_008e: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0093: stloc.s V_4 IL_0095: ldloca.s V_3 IL_0097: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_009d: ldarg.0 IL_009e: ldloc.s V_4 IL_00a0: stfld ""int C.<G>d__0.<>s__4"" IL_00a5: ldarg.0 IL_00a6: ldarg.0 IL_00a7: ldfld ""int C.<G>d__0.<>s__4"" IL_00ac: stfld ""int C.<G>d__0.<x>5__1"" -IL_00b1: nop ~IL_00b2: ldarg.0 IL_00b3: ldfld ""object C.<G>d__0.<>s__2"" IL_00b8: stloc.2 IL_00b9: ldloc.2 IL_00ba: brfalse.s IL_00d7 IL_00bc: ldloc.2 IL_00bd: isinst ""System.Exception"" IL_00c2: stloc.s V_6 IL_00c4: ldloc.s V_6 IL_00c6: brtrue.s IL_00ca IL_00c8: ldloc.2 IL_00c9: throw IL_00ca: ldloc.s V_6 IL_00cc: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_00d1: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_00d6: nop IL_00d7: ldarg.0 IL_00d8: ldfld ""int C.<G>d__0.<>s__3"" IL_00dd: pop IL_00de: ldarg.0 IL_00df: ldnull IL_00e0: stfld ""object C.<G>d__0.<>s__2"" -IL_00e5: ldarg.0 IL_00e6: ldfld ""int C.<G>d__0.<x>5__1"" IL_00eb: stloc.1 IL_00ec: leave.s IL_0108 } catch System.Exception { ~IL_00ee: stloc.s V_6 IL_00f0: ldarg.0 IL_00f1: ldc.i4.s -2 IL_00f3: stfld ""int C.<G>d__0.<>1__state"" IL_00f8: ldarg.0 IL_00f9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder"" IL_00fe: ldloc.s V_6 IL_0100: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0105: nop IL_0106: leave.s IL_011d } -IL_0108: ldarg.0 IL_0109: ldc.i4.s -2 IL_010b: stfld ""int C.<G>d__0.<>1__state"" ~IL_0110: ldarg.0 IL_0111: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder"" IL_0116: ldloc.1 IL_0117: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_011c: nop IL_011d: ret }", sequencePoints: "C+<G>d__0.MoveNext"); v.VerifyPdb("C+<G>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;G&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x11d"" /> <slot startOffset=""0x29"" endOffset=""0x32"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""20"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""33"" offset=""105"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" /> <entry offset=""0x7"" hidden=""true"" /> <entry offset=""0xe"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" /> <entry offset=""0x17"" hidden=""true"" /> <entry offset=""0x25"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" /> <entry offset=""0x26"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" /> <entry offset=""0x27"" hidden=""true"" /> <entry offset=""0x29"" hidden=""true"" /> <entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" /> <entry offset=""0x34"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""27"" /> <entry offset=""0x3f"" hidden=""true"" /> <entry offset=""0xb1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" /> <entry offset=""0xb2"" hidden=""true"" /> <entry offset=""0xe5"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""18"" /> <entry offset=""0xee"" hidden=""true"" /> <entry offset=""0x108"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" /> <entry offset=""0x110"" hidden=""true"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x11e""> <namespace name=""System"" /> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""G"" /> <await yield=""0x51"" resume=""0x70"" declaringType=""C+&lt;G&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] public void HoistedSpilledVariables() { string source = @" using System; using System.Threading.Tasks; class C { int[] a = new int[] { 1, 2 }; static async Task<int> G() { int z0 = H(ref new C().a[F(1)], F(2), ref new C().a[F(3)], await G()); int z1 = H(ref new C().a[F(1)], F(2), ref new C().a[F(3)], await G()); return z0 + z1; } static int H(ref int a, int b, ref int c, int d) => 1; static int F(int a) => a; }"; var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<z0>5__1", "<z1>5__2", "<>s__3", "<>s__4", "<>s__5", "<>s__6", "<>s__7", "<>s__8", "<>s__9", "<>s__10", "<>u__1", // awaiter "<>s__11", // ref-spills "<>s__12", "<>s__13", "<>s__14", }, module.GetFieldNames("C.<G>d__1")); }); v.VerifyPdb("C.G", @" <symbols> <methods> <method containingType=""C"" name=""G""> <customDebugInfo> <forwardIterator name=""&lt;G&gt;d__1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""95"" /> <slot kind=""28"" offset=""70"" /> <slot kind=""28"" offset=""70"" ordinal=""1"" /> <slot kind=""28"" offset=""150"" /> <slot kind=""28"" offset=""150"" ordinal=""1"" /> <slot kind=""29"" offset=""70"" /> <slot kind=""29"" offset=""70"" ordinal=""1"" /> <slot kind=""29"" offset=""70"" ordinal=""2"" /> <slot kind=""29"" offset=""70"" ordinal=""3"" /> <slot kind=""29"" offset=""150"" /> <slot kind=""29"" offset=""150"" ordinal=""1"" /> <slot kind=""29"" offset=""150"" ordinal=""2"" /> <slot kind=""29"" offset=""150"" ordinal=""3"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.CognitiveServices.Vision.Face { using Microsoft.CognitiveServices; using Microsoft.CognitiveServices.Vision; using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Person operations. /// </summary> public partial interface IPerson { /// <summary> /// Create a new person in a specified person group. /// </summary> /// <param name='personGroupId'> /// Specifying the target person group to create the person. /// </param> /// <param name='name'> /// Display name of the target person. The maximum length is 128. /// </param> /// <param name='userData'> /// Optional fields for user-provided data attached to a person. Size /// limit is 16KB. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<CreatePersonResult>> CreateWithHttpMessagesAsync(string personGroupId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all persons in a person group, and retrieve person information /// (including personId, name, userData and persistedFaceIds of /// registered faces of the person). /// </summary> /// <param name='personGroupId'> /// personGroupId of the target person group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<IList<PersonResult>>> ListWithHttpMessagesAsync(string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an existing person from a person group. Persisted face /// images of the person will also be deleted. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the person. /// </param> /// <param name='personId'> /// The target personId to delete. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string personGroupId, string personId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieve a person's information, including registered persisted /// faces, name and userData. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the target person. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<PersonResult>> GetWithHttpMessagesAsync(string personGroupId, string personId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update name or userData of a person. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// personId of the target person. /// </param> /// <param name='name'> /// Display name of the target person. The maximum length is 128. /// </param> /// <param name='userData'> /// Optional fields for user-provided data attached to a person. Size /// limit is 16KB. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string personGroupId, string personId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete a face from a person. Relative image for the persisted face /// will also be deleted. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the person that the target persisted face belong to. /// </param> /// <param name='persistedFaceId'> /// The persisted face to remove. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> DeleteFaceWithHttpMessagesAsync(string personGroupId, string personId, string persistedFaceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieve information about a persisted face (specified by /// persistedFaceId, personId and its belonging personGroupId). /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the target person that the face belongs to. /// </param> /// <param name='persistedFaceId'> /// The persistedFaceId of the target persisted face of the person. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<PersonFaceResult>> GetFaceWithHttpMessagesAsync(string personGroupId, string personId, string persistedFaceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update a person persisted face's userData field. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// personId of the target person. /// </param> /// <param name='persistedFaceId'> /// persistedFaceId of target face, which is persisted and will not /// expire. /// </param> /// <param name='userData'> /// User-provided data attached to the face. The size limit is 1KB /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> UpdateFaceWithHttpMessagesAsync(string personGroupId, string personId, string persistedFaceId, string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Add a representative face to a person for identification. The input /// face is specified as an image with a targetFace rectangle. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Target person that the face is added to. /// </param> /// <param name='userData'> /// User-specified data about the target face to add for any purpose. /// The maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added to a person /// in the format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the /// image, targetFace is required to specify which face to add. No /// targetFace means there is only one face detected in the entire /// image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> AddFaceWithHttpMessagesAsync(string personGroupId, string personId, string userData = default(string), string targetFace = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Add a representative face to a person for identification. The input /// face is specified as an image with a targetFace rectangle. /// </summary> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Target person that the face is added to. /// </param> /// <param name='userData'> /// User-specified data about the target face to add for any purpose. /// The maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added to a /// person, in the format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the /// image, targetFace is required to specify which face to add. No /// targetFace means there is only one face detected in the entire /// image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> AddFaceFromStreamWithHttpMessagesAsync(string personGroupId, string personId, string userData = default(string), string targetFace = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedIntentsClientSnippets { /// <summary>Snippet for ListIntents</summary> public void ListIntentsRequestObject() { // Snippet: ListIntents(ListIntentsRequest, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) ListIntentsRequest request = new ListIntentsRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "", IntentView = IntentView.Unspecified, }; // Make the request PagedEnumerable<ListIntentsResponse, Intent> response = intentsClient.ListIntents(request); // Iterate over all response items, lazily performing RPCs as required foreach (Intent item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListIntentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Intent item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Intent> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Intent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListIntentsAsync</summary> public async Task ListIntentsRequestObjectAsync() { // Snippet: ListIntentsAsync(ListIntentsRequest, CallSettings) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) ListIntentsRequest request = new ListIntentsRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), LanguageCode = "", IntentView = IntentView.Unspecified, }; // Make the request PagedAsyncEnumerable<ListIntentsResponse, Intent> response = intentsClient.ListIntentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Intent item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListIntentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Intent item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Intent> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Intent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListIntents</summary> public void ListIntents() { // Snippet: ListIntents(string, string, int?, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request PagedEnumerable<ListIntentsResponse, Intent> response = intentsClient.ListIntents(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Intent item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListIntentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Intent item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Intent> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Intent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListIntentsAsync</summary> public async Task ListIntentsAsync() { // Snippet: ListIntentsAsync(string, string, int?, CallSettings) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; // Make the request PagedAsyncEnumerable<ListIntentsResponse, Intent> response = intentsClient.ListIntentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Intent item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListIntentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Intent item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Intent> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Intent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListIntents</summary> public void ListIntentsResourceNames() { // Snippet: ListIntents(AgentName, string, int?, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request PagedEnumerable<ListIntentsResponse, Intent> response = intentsClient.ListIntents(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Intent item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListIntentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Intent item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Intent> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Intent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListIntentsAsync</summary> public async Task ListIntentsResourceNamesAsync() { // Snippet: ListIntentsAsync(AgentName, string, int?, CallSettings) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); // Make the request PagedAsyncEnumerable<ListIntentsResponse, Intent> response = intentsClient.ListIntentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Intent item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListIntentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Intent item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Intent> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Intent item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetIntent</summary> public void GetIntentRequestObject() { // Snippet: GetIntent(GetIntentRequest, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), LanguageCode = "", }; // Make the request Intent response = intentsClient.GetIntent(request); // End snippet } /// <summary>Snippet for GetIntentAsync</summary> public async Task GetIntentRequestObjectAsync() { // Snippet: GetIntentAsync(GetIntentRequest, CallSettings) // Additional: GetIntentAsync(GetIntentRequest, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) GetIntentRequest request = new GetIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), LanguageCode = "", }; // Make the request Intent response = await intentsClient.GetIntentAsync(request); // End snippet } /// <summary>Snippet for GetIntent</summary> public void GetIntent() { // Snippet: GetIntent(string, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/intents/[INTENT]"; // Make the request Intent response = intentsClient.GetIntent(name); // End snippet } /// <summary>Snippet for GetIntentAsync</summary> public async Task GetIntentAsync() { // Snippet: GetIntentAsync(string, CallSettings) // Additional: GetIntentAsync(string, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/intents/[INTENT]"; // Make the request Intent response = await intentsClient.GetIntentAsync(name); // End snippet } /// <summary>Snippet for GetIntent</summary> public void GetIntentResourceNames() { // Snippet: GetIntent(IntentName, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) IntentName name = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"); // Make the request Intent response = intentsClient.GetIntent(name); // End snippet } /// <summary>Snippet for GetIntentAsync</summary> public async Task GetIntentResourceNamesAsync() { // Snippet: GetIntentAsync(IntentName, CallSettings) // Additional: GetIntentAsync(IntentName, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) IntentName name = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"); // Make the request Intent response = await intentsClient.GetIntentAsync(name); // End snippet } /// <summary>Snippet for CreateIntent</summary> public void CreateIntentRequestObject() { // Snippet: CreateIntent(CreateIntentRequest, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), LanguageCode = "", }; // Make the request Intent response = intentsClient.CreateIntent(request); // End snippet } /// <summary>Snippet for CreateIntentAsync</summary> public async Task CreateIntentRequestObjectAsync() { // Snippet: CreateIntentAsync(CreateIntentRequest, CallSettings) // Additional: CreateIntentAsync(CreateIntentRequest, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) CreateIntentRequest request = new CreateIntentRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), Intent = new Intent(), LanguageCode = "", }; // Make the request Intent response = await intentsClient.CreateIntentAsync(request); // End snippet } /// <summary>Snippet for CreateIntent</summary> public void CreateIntent() { // Snippet: CreateIntent(string, Intent, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; Intent intent = new Intent(); // Make the request Intent response = intentsClient.CreateIntent(parent, intent); // End snippet } /// <summary>Snippet for CreateIntentAsync</summary> public async Task CreateIntentAsync() { // Snippet: CreateIntentAsync(string, Intent, CallSettings) // Additional: CreateIntentAsync(string, Intent, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]"; Intent intent = new Intent(); // Make the request Intent response = await intentsClient.CreateIntentAsync(parent, intent); // End snippet } /// <summary>Snippet for CreateIntent</summary> public void CreateIntentResourceNames() { // Snippet: CreateIntent(AgentName, Intent, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); Intent intent = new Intent(); // Make the request Intent response = intentsClient.CreateIntent(parent, intent); // End snippet } /// <summary>Snippet for CreateIntentAsync</summary> public async Task CreateIntentResourceNamesAsync() { // Snippet: CreateIntentAsync(AgentName, Intent, CallSettings) // Additional: CreateIntentAsync(AgentName, Intent, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"); Intent intent = new Intent(); // Make the request Intent response = await intentsClient.CreateIntentAsync(parent, intent); // End snippet } /// <summary>Snippet for UpdateIntent</summary> public void UpdateIntentRequestObject() { // Snippet: UpdateIntent(UpdateIntentRequest, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) UpdateIntentRequest request = new UpdateIntentRequest { Intent = new Intent(), LanguageCode = "", UpdateMask = new FieldMask(), }; // Make the request Intent response = intentsClient.UpdateIntent(request); // End snippet } /// <summary>Snippet for UpdateIntentAsync</summary> public async Task UpdateIntentRequestObjectAsync() { // Snippet: UpdateIntentAsync(UpdateIntentRequest, CallSettings) // Additional: UpdateIntentAsync(UpdateIntentRequest, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) UpdateIntentRequest request = new UpdateIntentRequest { Intent = new Intent(), LanguageCode = "", UpdateMask = new FieldMask(), }; // Make the request Intent response = await intentsClient.UpdateIntentAsync(request); // End snippet } /// <summary>Snippet for UpdateIntent</summary> public void UpdateIntent() { // Snippet: UpdateIntent(Intent, FieldMask, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) Intent intent = new Intent(); FieldMask updateMask = new FieldMask(); // Make the request Intent response = intentsClient.UpdateIntent(intent, updateMask); // End snippet } /// <summary>Snippet for UpdateIntentAsync</summary> public async Task UpdateIntentAsync() { // Snippet: UpdateIntentAsync(Intent, FieldMask, CallSettings) // Additional: UpdateIntentAsync(Intent, FieldMask, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) Intent intent = new Intent(); FieldMask updateMask = new FieldMask(); // Make the request Intent response = await intentsClient.UpdateIntentAsync(intent, updateMask); // End snippet } /// <summary>Snippet for DeleteIntent</summary> public void DeleteIntentRequestObject() { // Snippet: DeleteIntent(DeleteIntentRequest, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; // Make the request intentsClient.DeleteIntent(request); // End snippet } /// <summary>Snippet for DeleteIntentAsync</summary> public async Task DeleteIntentRequestObjectAsync() { // Snippet: DeleteIntentAsync(DeleteIntentRequest, CallSettings) // Additional: DeleteIntentAsync(DeleteIntentRequest, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) DeleteIntentRequest request = new DeleteIntentRequest { IntentName = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"), }; // Make the request await intentsClient.DeleteIntentAsync(request); // End snippet } /// <summary>Snippet for DeleteIntent</summary> public void DeleteIntent() { // Snippet: DeleteIntent(string, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/intents/[INTENT]"; // Make the request intentsClient.DeleteIntent(name); // End snippet } /// <summary>Snippet for DeleteIntentAsync</summary> public async Task DeleteIntentAsync() { // Snippet: DeleteIntentAsync(string, CallSettings) // Additional: DeleteIntentAsync(string, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/intents/[INTENT]"; // Make the request await intentsClient.DeleteIntentAsync(name); // End snippet } /// <summary>Snippet for DeleteIntent</summary> public void DeleteIntentResourceNames() { // Snippet: DeleteIntent(IntentName, CallSettings) // Create client IntentsClient intentsClient = IntentsClient.Create(); // Initialize request argument(s) IntentName name = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"); // Make the request intentsClient.DeleteIntent(name); // End snippet } /// <summary>Snippet for DeleteIntentAsync</summary> public async Task DeleteIntentResourceNamesAsync() { // Snippet: DeleteIntentAsync(IntentName, CallSettings) // Additional: DeleteIntentAsync(IntentName, CancellationToken) // Create client IntentsClient intentsClient = await IntentsClient.CreateAsync(); // Initialize request argument(s) IntentName name = IntentName.FromProjectLocationAgentIntent("[PROJECT]", "[LOCATION]", "[AGENT]", "[INTENT]"); // Make the request await intentsClient.DeleteIntentAsync(name); // End snippet } } }
// ----------------------------------------------------------------------- // <copyright file="ScalableImageSource.Generated.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // <auto-generated> // This code was generated by a tool. DO NOT EDIT // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ----------------------------------------------------------------------- #region StyleCop Suppression - generated code using System; using System.ComponentModel; using System.Windows; using System.Windows.Media; namespace Microsoft.Management.UI.Internal { /// <summary> /// Represents the source of an image that can render as a vector or as a bitmap. /// </summary> [Localizability(LocalizationCategory.None)] partial class ScalableImageSource { // // AccessibleName dependency property // /// <summary> /// Identifies the AccessibleName dependency property. /// </summary> public static readonly DependencyProperty AccessibleNameProperty = DependencyProperty.Register( "AccessibleName", typeof(string), typeof(ScalableImageSource), new PropertyMetadata( null, AccessibleNameProperty_PropertyChanged) ); /// <summary> /// Gets or sets the accessible name of the image. This is used by accessibility clients to describe the image, and must be localized. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the accessible name of the image. This is used by accessibility clients to describe the image, and must be localized.")] [Localizability(LocalizationCategory.Text, Modifiability=Modifiability.Modifiable, Readability=Readability.Readable)] public string AccessibleName { get { return (string) GetValue(AccessibleNameProperty); } set { SetValue(AccessibleNameProperty,value); } } static private void AccessibleNameProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScalableImageSource obj = (ScalableImageSource) o; obj.OnAccessibleNameChanged( new PropertyChangedEventArgs<string>((string)e.OldValue, (string)e.NewValue) ); } /// <summary> /// Occurs when AccessibleName property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<string>> AccessibleNameChanged; /// <summary> /// Called when AccessibleName property changes. /// </summary> protected virtual void OnAccessibleNameChanged(PropertyChangedEventArgs<string> e) { OnAccessibleNameChangedImplementation(e); RaisePropertyChangedEvent(AccessibleNameChanged, e); } partial void OnAccessibleNameChangedImplementation(PropertyChangedEventArgs<string> e); // // Brush dependency property // /// <summary> /// Identifies the Brush dependency property. /// </summary> public static readonly DependencyProperty BrushProperty = DependencyProperty.Register( "Brush", typeof(Brush), typeof(ScalableImageSource), new PropertyMetadata( null, BrushProperty_PropertyChanged) ); /// <summary> /// Gets or sets the source used to render the image as a vector.If this is set, the Image property will be ignored. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the source used to render the image as a vector.If this is set, the Image property will be ignored.")] [Localizability(LocalizationCategory.None)] public Brush Brush { get { return (Brush) GetValue(BrushProperty); } set { SetValue(BrushProperty,value); } } static private void BrushProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScalableImageSource obj = (ScalableImageSource) o; obj.OnBrushChanged( new PropertyChangedEventArgs<Brush>((Brush)e.OldValue, (Brush)e.NewValue) ); } /// <summary> /// Occurs when Brush property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<Brush>> BrushChanged; /// <summary> /// Called when Brush property changes. /// </summary> protected virtual void OnBrushChanged(PropertyChangedEventArgs<Brush> e) { OnBrushChangedImplementation(e); RaisePropertyChangedEvent(BrushChanged, e); } partial void OnBrushChangedImplementation(PropertyChangedEventArgs<Brush> e); // // Image dependency property // /// <summary> /// Identifies the Image dependency property. /// </summary> public static readonly DependencyProperty ImageProperty = DependencyProperty.Register( "Image", typeof(ImageSource), typeof(ScalableImageSource), new PropertyMetadata( null, ImageProperty_PropertyChanged) ); /// <summary> /// Gets or sets the source used to render the image as a bitmap. If the Brush property is set, this will be ignored. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the source used to render the image as a bitmap. If the Brush property is set, this will be ignored.")] [Localizability(LocalizationCategory.None)] public ImageSource Image { get { return (ImageSource) GetValue(ImageProperty); } set { SetValue(ImageProperty,value); } } static private void ImageProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScalableImageSource obj = (ScalableImageSource) o; obj.OnImageChanged( new PropertyChangedEventArgs<ImageSource>((ImageSource)e.OldValue, (ImageSource)e.NewValue) ); } /// <summary> /// Occurs when Image property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<ImageSource>> ImageChanged; /// <summary> /// Called when Image property changes. /// </summary> protected virtual void OnImageChanged(PropertyChangedEventArgs<ImageSource> e) { OnImageChangedImplementation(e); RaisePropertyChangedEvent(ImageChanged, e); } partial void OnImageChangedImplementation(PropertyChangedEventArgs<ImageSource> e); // // Size dependency property // /// <summary> /// Identifies the Size dependency property. /// </summary> public static readonly DependencyProperty SizeProperty = DependencyProperty.Register( "Size", typeof(Size), typeof(ScalableImageSource), new PropertyMetadata( new Size(Double.NaN, Double.NaN), SizeProperty_PropertyChanged) ); /// <summary> /// Gets or sets the suggested size of the image. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the suggested size of the image.")] [Localizability(LocalizationCategory.None)] public Size Size { get { return (Size) GetValue(SizeProperty); } set { SetValue(SizeProperty,value); } } static private void SizeProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ScalableImageSource obj = (ScalableImageSource) o; obj.OnSizeChanged( new PropertyChangedEventArgs<Size>((Size)e.OldValue, (Size)e.NewValue) ); } /// <summary> /// Occurs when Size property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<Size>> SizeChanged; /// <summary> /// Called when Size property changes. /// </summary> protected virtual void OnSizeChanged(PropertyChangedEventArgs<Size> e) { OnSizeChangedImplementation(e); RaisePropertyChangedEvent(SizeChanged, e); } partial void OnSizeChangedImplementation(PropertyChangedEventArgs<Size> e); /// <summary> /// Called when a property changes. /// </summary> private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e) { if(eh != null) { eh(this,e); } } } } #endregion
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using Xunit; namespace Test { [Trait("category", "outerloop")] public partial class ParallelQueryCombinationTests { [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Cast_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>()) { Assert.True(i.HasValue); seen.Add(i.Value); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Cast_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void DefaultIfEmpty_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty()) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void DefaultIfEmpty_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Distinct_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Distinct_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); Assert.All(query.ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Except_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Except_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); Assert.All(query.ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor)) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList()) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_ElementSelector_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y)) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_ElementSelector_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList()) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Intersect_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Intersect_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); Assert.All(query.ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OfType_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>()) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OfType_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Index_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { indices.Add(index); return -x; })) { seen.Add(i); } seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Index_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { indices.Add(index); return -x; }).ToList(), x => seen.Add(x)); seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); })) { seen.Add(i); } seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => seen.Add(x)); seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_ResultSelector_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_ResultSelector_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_ResultSelector_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x)) { seen.Add(i); } seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_ResultSelector_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x)); seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Skip_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2)) { seen.Add(i); count++; } Assert.Equal((DefaultSize - 1) / 2 + 1, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Skip_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; }); Assert.Equal((DefaultSize - 1) / 2 + 1, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Take_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2)) { seen.Add(i); count++; } Assert.Equal(DefaultSize / 2, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Take_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; }); Assert.Equal(DefaultSize / 2, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ToArray_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Indexed_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => x < DefaultStart + DefaultSize / 2)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Indexed_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Zip_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item) .Zip(operation.Item(0, DefaultSize, source.Item), (x, y) => x); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Zip_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(0, DefaultSize, source.Item) .Zip(operation.Item(DefaultStart, DefaultSize, source.Item), (x, y) => y); Assert.All(query.ToList(), x => seen.Add(x)); seen.AssertComplete(); } } }
using System; using System.Threading; using GoogleApi.Entities.Common; using GoogleApi.Entities.Common.Enums; using GoogleApi.Entities.Maps.Common; using GoogleApi.Entities.Maps.Common.Enums; using GoogleApi.Entities.Maps.DistanceMatrix.Request; using NUnit.Framework; namespace GoogleApi.Test.Maps.DistanceMatrix { [TestFixture] public class DistanceMatrixTests : BaseTest { [Test] public void DistanceMatrixTest() { var origin1 = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var origin2 = new Address("1 Broadway Ave, Manhattan, NY, USA"); var destination1 = new Address("185 Broadway Ave, Manhattan, NY, USA"); var destination2 = new Address("200 Bedford Ave, Brooklyn, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin1), new LocationEx(origin2) }, Destinations = new[] { new LocationEx(destination1), new LocationEx(destination2) } }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenAddressTest() { var origin = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var destination = new Address("185 Broadway Ave, Manhattan, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenCoordinateTest() { var origin = new CoordinateEx(55.7237480, 12.4208282); var destination = new CoordinateEx(55.72672682, 12.407996582); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenCoordinateAndHeadingTest() { var origin = new CoordinateEx(55.7237480, 12.4208282) { Heading = 90 }; var destination = new CoordinateEx(55.72672682, 12.407996582) { Heading = 90 }; var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenCoordinateAndUseSideOfRoadTest() { var origin = new CoordinateEx(55.7237480, 12.4208282) { UseSideOfRoad = true }; var destination = new CoordinateEx(55.72672682, 12.407996582) { UseSideOfRoad = true }; var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenPlaceIdTest() { var origin = new Place("ChIJaSLMpEVQUkYRL4xNOWBfwhQ"); var destination = new Place("ChIJuc03_GlQUkYRlLku0KsLdJw"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenAvoidWayTest() { var origin = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var destination = new Address("185 Broadway Ave, Manhattan, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) }, Avoid = AvoidWay.Highways }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenTravelModeDrivingAndDepartureTimeTest() { var origin = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var destination = new Address("185 Broadway Ave, Manhattan, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) }, TravelMode = TravelMode.Driving, DepartureTime = DateTime.UtcNow.AddHours(1) }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenTravelModeTransitAndArrivalTimeTest() { var origin = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var destination = new Address("185 Broadway Ave, Manhattan, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) }, TravelMode = TravelMode.Driving, ArrivalTime = DateTime.UtcNow.AddHours(1), TransitRoutingPreference = TransitRoutingPreference.Fewer_Transfers }; var result = GoogleMaps.DistanceMatrix.Query(request); Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenAsyncTest() { var origin = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var destination = new Address("185 Broadway Ave, Manhattan, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var result = GoogleMaps.DistanceMatrix.QueryAsync(request).Result; Assert.IsNotNull(result); Assert.AreEqual(Status.Ok, result.Status); } [Test] public void DistanceMatrixWhenAsyncAndCancelledTest() { var origin = new Address("285 Bedford Ave, Brooklyn, NY, USA"); var destination = new Address("185 Broadway Ave, Manhattan, NY, USA"); var request = new DistanceMatrixRequest { Key = this.ApiKey, Origins = new[] { new LocationEx(origin) }, Destinations = new[] { new LocationEx(destination) } }; var cancellationTokenSource = new CancellationTokenSource(); var task = GoogleMaps.DistanceMatrix.QueryAsync(request, cancellationTokenSource.Token); cancellationTokenSource.Cancel(); var exception = Assert.Throws<OperationCanceledException>(() => task.Wait(cancellationTokenSource.Token)); Assert.IsNotNull(exception); Assert.AreEqual(exception.Message, "The operation was canceled."); } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Cassandra { /// <summary> /// Keeps metadata on the connected cluster, including known nodes and schema /// definitions. /// </summary> public class Metadata : IDisposable { private const string SelectKeyspaces = "SELECT * FROM system.schema_keyspaces"; private const string SelectSingleKeyspace = "SELECT * FROM system.schema_keyspaces WHERE keyspace_name = '{0}'"; private const string SelectSchemaVersionPeers = "SELECT schema_version FROM system.peers"; private const string SelectSchemaVersionLocal = "SELECT schema_version FROM system.local"; private static readonly Logger Logger = new Logger(typeof(ControlConnection)); private volatile TokenMap _tokenMap; private volatile ConcurrentDictionary<string, KeyspaceMetadata> _keyspaces = new ConcurrentDictionary<string,KeyspaceMetadata>(1, 0); private readonly Configuration _config; public event HostsEventHandler HostsEvent; public event SchemaChangedEventHandler SchemaChangedEvent; /// <summary> /// Returns the name of currently connected cluster. /// </summary> /// <returns>the Cassandra name of currently connected cluster.</returns> public String ClusterName { get; internal set; } /// <summary> /// Control connection to be used to execute the queries to retrieve the metadata /// </summary> internal ControlConnection ControlConnection { get; set; } internal string Partitioner { get; set; } internal Hosts Hosts { get; private set; } internal Metadata(Configuration config) { _config = config; Hosts = new Hosts(config.Policies.ReconnectionPolicy); Hosts.Down += OnHostDown; Hosts.Up += OnHostUp; } public void Dispose() { ShutDown(); } public Host GetHost(IPEndPoint address) { Host host; if (Hosts.TryGet(address, out host)) return host; return null; } internal Host AddHost(IPEndPoint address) { return Hosts.Add(address); } internal void RemoveHost(IPEndPoint address) { Hosts.RemoveIfExists(address); } internal void FireSchemaChangedEvent(SchemaChangedEventArgs.Kind what, string keyspace, string table, object sender = null) { if (SchemaChangedEvent != null) { SchemaChangedEvent(sender ?? this, new SchemaChangedEventArgs {Keyspace = keyspace, What = what, Table = table}); } } internal void SetDownHost(IPEndPoint address, object sender = null) { Hosts.SetDownIfExists(address); } private void OnHostDown(Host h, DateTimeOffset nextUpTime) { if (HostsEvent != null) { HostsEvent(this, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Down }); } } private void OnHostUp(Host h) { if (HostsEvent != null) { HostsEvent(h, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Up }); } } internal void BringUpHost(IPEndPoint address, object sender = null) { //Add the host if not already present var host = Hosts.Add(address); //Bring it UP host.BringUpIfDown(); } /// <summary> /// Returns all known hosts of this cluster. /// </summary> /// <returns>collection of all known hosts of this cluster.</returns> public ICollection<Host> AllHosts() { return Hosts.ToCollection(); } public IEnumerable<IPEndPoint> AllReplicas() { return Hosts.AllEndPointsToCollection(); } internal void RebuildTokenMap() { Logger.Info("Rebuilding token map"); if (Partitioner == null) { throw new DriverInternalError("Partitioner can not be null"); } _tokenMap = TokenMap.Build(Partitioner, Hosts.ToCollection(), _keyspaces.Values); } /// <summary> /// Get the replicas for a given partition key and keyspace /// </summary> public ICollection<Host> GetReplicas(string keyspaceName, byte[] partitionKey) { if (_tokenMap == null) { return new Host[0]; } return _tokenMap.GetReplicas(keyspaceName, _tokenMap.Factory.Hash(partitionKey)); } public ICollection<Host> GetReplicas(byte[] partitionKey) { return GetReplicas(null, partitionKey); } /// <summary> /// Returns metadata of specified keyspace. /// </summary> /// <param name="keyspace"> the name of the keyspace for which metadata should be /// returned. </param> /// <returns>the metadata of the requested keyspace or <c>null</c> if /// <c>* keyspace</c> is not a known keyspace.</returns> public KeyspaceMetadata GetKeyspace(string keyspace) { //Use local cache KeyspaceMetadata ksInfo; _keyspaces.TryGetValue(keyspace, out ksInfo); return ksInfo; } /// <summary> /// Returns a collection of all defined keyspaces names. /// </summary> /// <returns>a collection of all defined keyspaces names.</returns> public ICollection<string> GetKeyspaces() { //Use local cache return _keyspaces.Keys; } /// <summary> /// Returns names of all tables which are defined within specified keyspace. /// </summary> /// <param name="keyspace">the name of the keyspace for which all tables metadata should be /// returned.</param> /// <returns>an ICollection of the metadata for the tables defined in this /// keyspace.</returns> public ICollection<string> GetTables(string keyspace) { KeyspaceMetadata ksMetadata; if (!_keyspaces.TryGetValue(keyspace, out ksMetadata)) { return new string[0]; } return ksMetadata.GetTablesNames(); } /// <summary> /// Returns TableMetadata for specified table in specified keyspace. /// </summary> /// <param name="keyspace">name of the keyspace within specified table is definied.</param> /// <param name="tableName">name of table for which metadata should be returned.</param> /// <returns>a TableMetadata for the specified table in the specified keyspace.</returns> public TableMetadata GetTable(string keyspace, string tableName) { KeyspaceMetadata ksMetadata; if (!_keyspaces.TryGetValue(keyspace, out ksMetadata)) { return null; } return ksMetadata.GetTableMetadata(tableName); } /// <summary> /// Gets the definition associated with a User Defined Type from Cassandra /// </summary> public UdtColumnInfo GetUdtDefinition(string keyspace, string typeName) { KeyspaceMetadata ksMetadata; if (!_keyspaces.TryGetValue(keyspace, out ksMetadata)) { return null; } return ksMetadata.GetUdtDefinition(typeName); } /// <summary> /// Updates the keyspace and token information /// </summary> public bool RefreshSchema(string keyspace = null, string table = null) { if (table == null) { //Refresh all the keyspaces and tables information RefreshKeyspaces(true); return true; } var ks = GetKeyspace(keyspace); if (ks == null) { return false; } ks.ClearTableMetadata(table); return true; } /// <summary> /// Retrieves the keyspaces, stores the information in the internal state and rebuilds the token map /// </summary> internal void RefreshKeyspaces(bool retry) { Logger.Info("Retrieving keyspaces metadata"); //Use the control connection to get the keyspace var rs = ControlConnection.Query(SelectKeyspaces, retry); //parse the info var keyspaces = rs.Select(ParseKeyspaceRow).ToDictionary(ks => ks.Name); //Assign to local state _keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(keyspaces); RebuildTokenMap(); } private KeyspaceMetadata ParseKeyspaceRow(Row row) { return new KeyspaceMetadata( ControlConnection, row.GetValue<string>("keyspace_name"), row.GetValue<bool>("durable_writes"), row.GetValue<string>("strategy_class"), Utils.ConvertStringToMapInt(row.GetValue<string>("strategy_options"))); } public void ShutDown(int timeoutMs = Timeout.Infinite) { //it is really not required to be called, left as it is part of the public API //dereference the control connection ControlConnection = null; } internal bool RemoveKeyspace(string name) { Logger.Verbose("Removing keyspace metadata: " + name); KeyspaceMetadata ks; FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this); var removed = _keyspaces.TryRemove(name, out ks); if (removed) { RebuildTokenMap(); FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this); } return removed; } internal void RefreshSingleKeyspace(bool added, string name) { Logger.Verbose("Updating keyspace metadata: " + name); var row = ControlConnection.Query(String.Format(SelectSingleKeyspace, name), true).FirstOrDefault(); if (row == null) { return; } var ksMetadata = ParseKeyspaceRow(row); _keyspaces.AddOrUpdate(name, ksMetadata, (k, v) => ksMetadata); var eventKind = added ? SchemaChangedEventArgs.Kind.Created : SchemaChangedEventArgs.Kind.Updated; RebuildTokenMap(); FireSchemaChangedEvent(eventKind, name, null, this); } internal void RefreshTable(string keyspaceName, string tableName) { KeyspaceMetadata ksMetadata; if (_keyspaces.TryGetValue(keyspaceName, out ksMetadata)) { ksMetadata.ClearTableMetadata(tableName); } } /// <summary> /// Waits until that the schema version in all nodes is the same or the waiting time passed. /// This method blocks the calling thread. /// </summary> internal void WaitForSchemaAgreement(Connection connection) { if (Hosts.Count == 1) { //If there is just one node, the schema is up to date in all nodes :) return; } var start = DateTime.Now; var waitSeconds = _config.ProtocolOptions.MaxSchemaAgreementWaitSeconds; Logger.Info("Waiting for schema agreement"); try { var totalVersions = 0; while (DateTime.Now.Subtract(start).TotalSeconds < waitSeconds) { var schemaVersionLocalQuery = new QueryRequest(connection.ProtocolVersion, SelectSchemaVersionLocal, false, QueryProtocolOptions.Default); var schemaVersionPeersQuery = new QueryRequest(connection.ProtocolVersion, SelectSchemaVersionPeers, false, QueryProtocolOptions.Default); var queries = new [] { connection.Send(schemaVersionLocalQuery), connection.Send(schemaVersionPeersQuery) }; // ReSharper disable once CoVariantArrayConversion Task.WaitAll(queries, _config.ClientOptions.QueryAbortTimeout); var versions = new HashSet<Guid> { ControlConnection.GetRowSet(queries[0].Result).First().GetValue<Guid>("schema_version") }; var peerVersions = ControlConnection.GetRowSet(queries[1].Result).Select(r => r.GetValue<Guid>("schema_version")); foreach (var v in peerVersions) { versions.Add(v); } totalVersions = versions.Count; if (versions.Count == 1) { return; } Thread.Sleep(500); } Logger.Info(String.Format("Waited for schema agreement, still {0} schema versions in the cluster.", totalVersions)); } catch (Exception ex) { //Exceptions are not fatal Logger.Error("There was an exception while trying to retrieve schema versions", ex); } } } }
#region File Description //----------------------------------------------------------------------------- // ScreenManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace Teeter { /// <summary> /// The screen manager is a component which manages one or more GameScreen /// instances. It maintains a stack of screens, calls their Update and Draw /// methods at the appropriate times, and automatically routes input to the /// topmost active screen. /// </summary> public class ScreenManager : DrawableGameComponent { #region Fields List<GameScreen> screens = new List<GameScreen>(); List<GameScreen> screensToUpdate = new List<GameScreen>(); InputState input = new InputState(); SpriteBatch spriteBatch; SpriteFont font; Texture2D blankTexture; bool isInitialized; bool traceEnabled; #endregion #region Properties /// <summary> /// A default SpriteBatch shared by all the screens. This saves /// each screen having to bother creating their own local instance. /// </summary> public SpriteBatch SpriteBatch { get { return spriteBatch; } } /// <summary> /// A default font shared by all the screens. This saves /// each screen having to bother loading their own local copy. /// </summary> public SpriteFont Font { get { return font; } } /// <summary> /// If true, the manager prints out a list of all the screens /// each time it is updated. This can be useful for making sure /// everything is being added and removed at the right times. /// </summary> public bool TraceEnabled { get { return traceEnabled; } set { traceEnabled = value; } } #endregion #region Initialization /// <summary> /// Constructs a new screen manager component. /// </summary> public ScreenManager(Game game) : base(game) { } /// <summary> /// Initializes the screen manager component. /// </summary> public override void Initialize() { base.Initialize(); isInitialized = true; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load content belonging to the screen manager. ContentManager content = Game.Content; spriteBatch = new SpriteBatch(GraphicsDevice); font = content.Load<SpriteFont>("menufont"); blankTexture = content.Load<Texture2D>("blank"); // Tell each of the screens to load their content. foreach (GameScreen screen in screens) { screen.LoadContent(); } } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { // Tell each of the screens to unload their content. foreach (GameScreen screen in screens) { screen.UnloadContent(); } } #endregion #region Update and Draw /// <summary> /// Allows each screen to run logic. /// </summary> public override void Update(GameTime gameTime) { // Read the keyboard and gamepad. input.Update(); // Make a copy of the master screen list, to avoid confusion if // the process of updating one screen adds or removes others. screensToUpdate.Clear(); foreach (GameScreen screen in screens) screensToUpdate.Add(screen); bool otherScreenHasFocus = !Game.IsActive; bool coveredByOtherScreen = false; // Loop as long as there are screens waiting to be updated. while (screensToUpdate.Count > 0) { // Pop the topmost screen off the waiting list. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1]; screensToUpdate.RemoveAt(screensToUpdate.Count - 1); // Update the screen. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active) { // If this is the first active screen we came across, // give it a chance to handle input. if (!otherScreenHasFocus) { screen.HandleInput(input); otherScreenHasFocus = true; } // If this is an active non-popup, inform any subsequent // screens that they are covered by it. if (!screen.IsPopup) coveredByOtherScreen = true; } } // Print debug trace? if (traceEnabled) TraceScreens(); } /// <summary> /// Prints a list of all the screens, for debugging. /// </summary> void TraceScreens() { List<string> screenNames = new List<string>(); foreach (GameScreen screen in screens) screenNames.Add(screen.GetType().Name); Trace.WriteLine(string.Join(", ", screenNames.ToArray())); } /// <summary> /// Tells each screen to draw itself. /// </summary> public override void Draw(GameTime gameTime) { foreach (GameScreen screen in screens) { if (screen.ScreenState == ScreenState.Hidden) continue; screen.Draw(gameTime); } } #endregion #region Public Methods /// <summary> /// Adds a new screen to the screen manager. /// </summary> public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer) { screen.ControllingPlayer = controllingPlayer; screen.ScreenManager = this; screen.IsExiting = false; // If we have a graphics device, tell the screen to load content. if (isInitialized) { screen.LoadContent(); } screens.Add(screen); } /// <summary> /// Removes a screen from the screen manager. You should normally /// use GameScreen.ExitScreen instead of calling this directly, so /// the screen can gradually transition off rather than just being /// instantly removed. /// </summary> public void RemoveScreen(GameScreen screen) { // If we have a graphics device, tell the screen to unload content. if (isInitialized) { screen.UnloadContent(); } screens.Remove(screen); screensToUpdate.Remove(screen); } /// <summary> /// Expose an array holding all the screens. We return a copy rather /// than the real master list, because screens should only ever be added /// or removed using the AddScreen and RemoveScreen methods. /// </summary> public GameScreen[] GetScreens() { return screens.ToArray(); } /// <summary> /// Helper draws a translucent black fullscreen sprite, used for fading /// screens in and out, and for darkening the background behind popups. /// </summary> public void FadeBackBufferToBlack(int alpha) { Viewport viewport = GraphicsDevice.Viewport; spriteBatch.Begin(); spriteBatch.Draw(blankTexture, new Rectangle(0, 0, viewport.Width, viewport.Height), new Color(0, 0, 0, (byte)alpha)); spriteBatch.End(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Net.Http.Headers { public class EntityTagHeaderValue : ICloneable { private static EntityTagHeaderValue s_any; private string _tag; private bool _isWeak; public string Tag { get { return _tag; } } public bool IsWeak { get { return _isWeak; } } public static EntityTagHeaderValue Any { get { if (s_any == null) { s_any = new EntityTagHeaderValue(); s_any._tag = "*"; s_any._isWeak = false; } return s_any; } } public EntityTagHeaderValue(string tag) : this(tag, false) { } public EntityTagHeaderValue(string tag, bool isWeak) { if (string.IsNullOrEmpty(tag)) { throw new ArgumentException("The value cannot be null or empty.", nameof(tag)); } int length = 0; if ((HttpRuleParser.GetQuotedStringLength(tag, 0, out length) != HttpParseResult.Parsed) || (length != tag.Length)) { // Note that we don't allow 'W/' prefixes for weak ETags in the 'tag' parameter. If the user wants to // add a weak ETag, he can set 'isWeak' to true. throw new FormatException("The specified value is not a valid quoted string."); } _tag = tag; _isWeak = isWeak; } private EntityTagHeaderValue(EntityTagHeaderValue source) { Debug.Assert(source != null); _tag = source._tag; _isWeak = source._isWeak; } private EntityTagHeaderValue() { } public override string ToString() { if (_isWeak) { return "W/" + _tag; } return _tag; } public override bool Equals(object obj) { EntityTagHeaderValue other = obj as EntityTagHeaderValue; if (other == null) { return false; } // Since the tag is a quoted-string we treat it case-sensitive. return ((_isWeak == other._isWeak) && string.Equals(_tag, other._tag, StringComparison.Ordinal)); } public override int GetHashCode() { // Since the tag is a quoted-string we treat it case-sensitive. return _tag.GetHashCode() ^ _isWeak.GetHashCode(); } public static EntityTagHeaderValue Parse(string input) { int index = 0; return (EntityTagHeaderValue)GenericHeaderParser.SingleValueEntityTagParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out EntityTagHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueEntityTagParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (EntityTagHeaderValue)output; return true; } return false; } internal static int GetEntityTagLength(string input, int startIndex, out EntityTagHeaderValue parsedValue) { Debug.Assert(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespace. If not, we'll return 0. bool isWeak = false; int current = startIndex; char firstChar = input[startIndex]; if (firstChar == '*') { // We have '*' value, indicating "any" ETag. parsedValue = Any; current++; } else { // The RFC defines 'W/' as prefix, but we'll be flexible and also accept lower-case 'w'. if ((firstChar == 'W') || (firstChar == 'w')) { current++; // We need at least 3 more chars: the '/' character followed by two quotes. if ((current + 2 >= input.Length) || (input[current] != '/')) { return 0; } isWeak = true; current++; // we have a weak-entity tag. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } int tagStartIndex = current; int tagLength = 0; if (HttpRuleParser.GetQuotedStringLength(input, current, out tagLength) != HttpParseResult.Parsed) { return 0; } parsedValue = new EntityTagHeaderValue(); if (tagLength == input.Length) { // Most of the time we'll have strong ETags without leading/trailing whitespace. Debug.Assert(startIndex == 0); Debug.Assert(!isWeak); parsedValue._tag = input; parsedValue._isWeak = false; } else { parsedValue._tag = input.Substring(tagStartIndex, tagLength); parsedValue._isWeak = isWeak; } current = current + tagLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return current - startIndex; } object ICloneable.Clone() { if (this == s_any) { return s_any; } else { return new EntityTagHeaderValue(this); } } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Text; using System.Threading; using Quartz.Spi; namespace Quartz { /// <summary> /// Describes the settings and capabilities of a given <see cref="IScheduler" /> /// instance. /// </summary> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class SchedulerMetaData { private readonly string schedName; private readonly string schedInst; private readonly Type schedType; private readonly bool isRemote; private readonly bool started; private readonly bool isInStandbyMode; private readonly bool shutdown; private readonly DateTimeOffset? startTime; private readonly int numberOfJobsExec; private readonly Type jsType; private readonly bool jsPersistent; private readonly bool jsClustered; private readonly Type tpType; private readonly int tpSize; private readonly string version; /// <summary> /// Initializes a new instance of the <see cref="SchedulerMetaData"/> class. /// </summary> /// <param name="schedName">Name of the scheduler.</param> /// <param name="schedInst">The scheduler instance.</param> /// <param name="schedType">The scheduler type.</param> /// <param name="isRemote">if set to <c>true</c>, scheduler is a remote scheduler.</param> /// <param name="started">if set to <c>true</c>, scheduler is started.</param> /// <param name="isInStandbyMode">if set to <c>true</c>, scheduler is in standby mode.</param> /// <param name="shutdown">if set to <c>true</c>, scheduler is shutdown.</param> /// <param name="startTime">The start time.</param> /// <param name="numberOfJobsExec">The number of jobs executed.</param> /// <param name="jsType">The job store type.</param> /// <param name="jsPersistent">if set to <c>true</c>, job store is persistent.</param> /// <param name="jsClustered">if set to <c>true</c>, the job store is clustered</param> /// <param name="tpType">The thread pool type.</param> /// <param name="tpSize">Size of the thread pool.</param> /// <param name="version">The version string.</param> public SchedulerMetaData( string schedName, string schedInst, Type schedType, bool isRemote, bool started, bool isInStandbyMode, bool shutdown, DateTimeOffset? startTime, int numberOfJobsExec, Type jsType, bool jsPersistent, bool jsClustered, Type tpType, int tpSize, string version) { this.schedName = schedName; this.schedInst = schedInst; this.schedType = schedType; this.isRemote = isRemote; this.started = started; this.isInStandbyMode = isInStandbyMode; this.shutdown = shutdown; this.startTime = startTime; this.numberOfJobsExec = numberOfJobsExec; this.jsType = jsType; this.jsPersistent = jsPersistent; this.jsClustered = jsClustered; this.tpType = tpType; this.tpSize = tpSize; this.version = version; } /// <summary> /// Returns the name of the <see cref="IScheduler" />. /// </summary> public virtual string SchedulerName { get { return schedName; } } /// <summary> /// Returns the instance Id of the <see cref="IScheduler" />. /// </summary> public virtual string SchedulerInstanceId { get { return schedInst; } } /// <summary> /// Returns the class-name of the <see cref="IScheduler" /> instance. /// </summary> public virtual Type SchedulerType { get { return schedType; } } /// <summary> /// Returns whether the <see cref="IScheduler" /> is being used remotely (via remoting). /// </summary> public virtual bool SchedulerRemote { get { return isRemote; } } /// <summary> /// Returns whether the scheduler has been started. /// </summary> /// <remarks> /// Note: <see cref="Started" /> may return <see langword="true" /> even if /// <see cref="InStandbyMode" /> returns <see langword="true" />. /// </remarks> public virtual bool Started { get { return started; } } /// <summary> /// Reports whether the <see cref="IScheduler" /> is in standby mode. /// </summary> /// <remarks> /// Note: <see cref="Started" /> may return <see langword="true" /> even if /// <see cref="InStandbyMode" /> returns <see langword="true" />. /// </remarks> public virtual bool InStandbyMode { get { return isInStandbyMode; } } /// <summary> /// Reports whether the <see cref="IScheduler" /> has been Shutdown. /// </summary> public virtual bool Shutdown { get { return shutdown; } } /// <summary> /// Returns the class-name of the <see cref="IJobStore" /> instance that is /// being used by the <see cref="IScheduler" />. /// </summary> public virtual Type JobStoreType { get { return jsType; } } /// <summary> /// Returns the type name of the <see cref="ThreadPool" /> instance that is /// being used by the <see cref="IScheduler" />. /// </summary> public virtual Type ThreadPoolType { get { return tpType; } } /// <summary> /// Returns the number of threads currently in the <see cref="IScheduler" />'s /// </summary> public virtual int ThreadPoolSize { get { return tpSize; } } /// <summary> /// Returns the version of Quartz that is running. /// </summary> public virtual string Version { get { return version; } } /// <summary> /// Returns a formatted (human readable) string describing all the <see cref="IScheduler" />'s /// meta-data values. /// </summary> /// <remarks> /// <para> /// The format of the string looks something like this: /// <pre> /// Quartz Scheduler 'SchedulerName' with instanceId 'SchedulerInstanceId' Scheduler class: 'Quartz.Impl.StdScheduler' - running locally. Running since: '11:33am on Jul 19, 2002' Not currently paused. Number of Triggers fired: '123' Using thread pool 'Quartz.Simpl.SimpleThreadPool' - with '8' threads Using job-store 'Quartz.Impl.JobStore' - which supports persistence. /// </pre> /// </para> /// </remarks> public string GetSummary() { StringBuilder str = new StringBuilder("Quartz Scheduler (v"); str.Append(Version); str.Append(") '"); str.Append(SchedulerName); str.Append("' with instanceId '"); str.Append(SchedulerInstanceId); str.Append("'\n"); str.Append(" Scheduler class: '"); str.Append(SchedulerType.FullName); str.Append("'"); if (SchedulerRemote) { str.Append(" - access via remote invocation."); } else { str.Append(" - running locally."); } str.Append("\n"); if (!Shutdown) { if (RunningSince.HasValue) { str.Append(" Running since: "); str.Append(RunningSince); } else { str.Append(" NOT STARTED."); } str.Append("\n"); if (InStandbyMode) { str.Append(" Currently in standby mode."); } else { str.Append(" Not currently in standby mode."); } } else { str.Append(" Scheduler has been SHUTDOWN."); } str.Append("\n"); str.Append(" Number of jobs executed: "); str.Append(NumberOfJobsExecuted); str.Append("\n"); str.Append(" Using thread pool '"); str.Append(ThreadPoolType.FullName); str.Append("' - with "); str.Append(ThreadPoolSize); str.Append(" threads."); str.Append("\n"); str.Append(" Using job-store '"); str.Append(JobStoreType.FullName); str.Append("' - which "); if (JobStoreSupportsPersistence) { str.Append("supports persistence."); } else { str.Append("does not support persistence."); } if (JobStoreClustered) { str.Append(" and is clustered."); } else { str.Append(" and is not clustered."); } str.Append("\n"); return str.ToString(); } /// <summary> /// Returns the <see cref="DateTimeOffset" /> at which the Scheduler started running. /// </summary> /// <returns> null if the scheduler has not been started. /// </returns> public virtual DateTimeOffset? RunningSince { get { return startTime; } } /// <summary> /// Returns the number of jobs executed since the <see cref="IScheduler" /> /// started.. /// </summary> public virtual int NumberOfJobsExecuted { get { return numberOfJobsExec; } } /// <summary> /// Returns whether or not the <see cref="IScheduler" />'s<see cref="IJobStore" /> /// instance supports persistence. /// </summary> public virtual bool JobStoreSupportsPersistence { get { return jsPersistent; } } /// <summary> /// Returns whether or not the <see cref="IScheduler" />'s <see cref="IJobStore" /> /// is clustered. /// </summary> public virtual bool JobStoreClustered { get { return jsClustered; } } /// <summary> /// Return a simple string representation of this object. /// </summary> public override string ToString() { try { return GetSummary(); } catch (SchedulerException) { return "SchedulerMetaData: indeterminable."; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RisEstudioAseguradora class. /// </summary> [Serializable] public partial class RisEstudioAseguradoraCollection : ActiveList<RisEstudioAseguradora, RisEstudioAseguradoraCollection> { public RisEstudioAseguradoraCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisEstudioAseguradoraCollection</returns> public RisEstudioAseguradoraCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisEstudioAseguradora o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the RIS_EstudioAseguradora table. /// </summary> [Serializable] public partial class RisEstudioAseguradora : ActiveRecord<RisEstudioAseguradora>, IActiveRecord { #region .ctors and Default Settings public RisEstudioAseguradora() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisEstudioAseguradora(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisEstudioAseguradora(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisEstudioAseguradora(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("RIS_EstudioAseguradora", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEstudioAseguradora = new TableSchema.TableColumn(schema); colvarIdEstudioAseguradora.ColumnName = "idEstudioAseguradora"; colvarIdEstudioAseguradora.DataType = DbType.Int32; colvarIdEstudioAseguradora.MaxLength = 0; colvarIdEstudioAseguradora.AutoIncrement = true; colvarIdEstudioAseguradora.IsNullable = false; colvarIdEstudioAseguradora.IsPrimaryKey = true; colvarIdEstudioAseguradora.IsForeignKey = false; colvarIdEstudioAseguradora.IsReadOnly = false; colvarIdEstudioAseguradora.DefaultSetting = @""; colvarIdEstudioAseguradora.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudioAseguradora); TableSchema.TableColumn colvarIdEstudio = new TableSchema.TableColumn(schema); colvarIdEstudio.ColumnName = "idEstudio"; colvarIdEstudio.DataType = DbType.Int32; colvarIdEstudio.MaxLength = 0; colvarIdEstudio.AutoIncrement = false; colvarIdEstudio.IsNullable = false; colvarIdEstudio.IsPrimaryKey = false; colvarIdEstudio.IsForeignKey = false; colvarIdEstudio.IsReadOnly = false; colvarIdEstudio.DefaultSetting = @""; colvarIdEstudio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudio); TableSchema.TableColumn colvarIdAseguradora = new TableSchema.TableColumn(schema); colvarIdAseguradora.ColumnName = "idAseguradora"; colvarIdAseguradora.DataType = DbType.Int32; colvarIdAseguradora.MaxLength = 0; colvarIdAseguradora.AutoIncrement = false; colvarIdAseguradora.IsNullable = false; colvarIdAseguradora.IsPrimaryKey = false; colvarIdAseguradora.IsForeignKey = false; colvarIdAseguradora.IsReadOnly = false; colvarIdAseguradora.DefaultSetting = @""; colvarIdAseguradora.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAseguradora); TableSchema.TableColumn colvarNumeroPoliza = new TableSchema.TableColumn(schema); colvarNumeroPoliza.ColumnName = "numeroPoliza"; colvarNumeroPoliza.DataType = DbType.AnsiString; colvarNumeroPoliza.MaxLength = 100; colvarNumeroPoliza.AutoIncrement = false; colvarNumeroPoliza.IsNullable = false; colvarNumeroPoliza.IsPrimaryKey = false; colvarNumeroPoliza.IsForeignKey = false; colvarNumeroPoliza.IsReadOnly = false; colvarNumeroPoliza.DefaultSetting = @""; colvarNumeroPoliza.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumeroPoliza); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_EstudioAseguradora",schema); } } #endregion #region Props [XmlAttribute("IdEstudioAseguradora")] [Bindable(true)] public int IdEstudioAseguradora { get { return GetColumnValue<int>(Columns.IdEstudioAseguradora); } set { SetColumnValue(Columns.IdEstudioAseguradora, value); } } [XmlAttribute("IdEstudio")] [Bindable(true)] public int IdEstudio { get { return GetColumnValue<int>(Columns.IdEstudio); } set { SetColumnValue(Columns.IdEstudio, value); } } [XmlAttribute("IdAseguradora")] [Bindable(true)] public int IdAseguradora { get { return GetColumnValue<int>(Columns.IdAseguradora); } set { SetColumnValue(Columns.IdAseguradora, value); } } [XmlAttribute("NumeroPoliza")] [Bindable(true)] public string NumeroPoliza { get { return GetColumnValue<string>(Columns.NumeroPoliza); } set { SetColumnValue(Columns.NumeroPoliza, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEstudio,int varIdAseguradora,string varNumeroPoliza) { RisEstudioAseguradora item = new RisEstudioAseguradora(); item.IdEstudio = varIdEstudio; item.IdAseguradora = varIdAseguradora; item.NumeroPoliza = varNumeroPoliza; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEstudioAseguradora,int varIdEstudio,int varIdAseguradora,string varNumeroPoliza) { RisEstudioAseguradora item = new RisEstudioAseguradora(); item.IdEstudioAseguradora = varIdEstudioAseguradora; item.IdEstudio = varIdEstudio; item.IdAseguradora = varIdAseguradora; item.NumeroPoliza = varNumeroPoliza; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEstudioAseguradoraColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEstudioColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdAseguradoraColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NumeroPolizaColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string IdEstudioAseguradora = @"idEstudioAseguradora"; public static string IdEstudio = @"idEstudio"; public static string IdAseguradora = @"idAseguradora"; public static string NumeroPoliza = @"numeroPoliza"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Text; using OpenLiveWriter.BlogClient; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Localization; namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl { internal interface IBlogCategorySettings { BlogPostCategory[] RefreshCategories(bool ignoreErrors); void UpdateCategories(BlogPostCategory[] category) ; } internal class CategoryContext { public CategoryContext() { _selectedCategories = new BlogPostCategory[0]; SetBlogCategories(new BlogPostCategory[0]) ; SetNewCategories(new BlogPostCategory[0]) ; _selectionMode = SelectionModes.MultiSelect ; _supportsAddingCategories = false ; _supportsHeirarchicalCategories = false ; } public BlogPostCategory[] SelectedExistingCategories { get { ArrayList selectedExistingCategories = new ArrayList(); foreach (BlogPostCategory category in SelectedCategories) if ( _blogCategories.Contains(category) ) selectedExistingCategories.Add(category) ; return selectedExistingCategories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[] ; } } public BlogPostCategory[] SelectedNewCategories { get { ArrayList selectedNewCategories = new ArrayList(); foreach (BlogPostCategory category in SelectedCategories) if ( _newCategories.Contains(category) ) selectedNewCategories.Add(category) ; return selectedNewCategories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[] ; } } public BlogPostCategory[] SelectedCategories { get { return _selectedCategories; } set { _selectedCategories = InsureSelectedValuesAreInCategoryList(value, true); DoChange(ChangeType.SelectedCategory); } } private BlogPostCategory[] _selectedCategories = new BlogPostCategory[0]; public BlogPostCategory[] BlogCategories { get { return _blogCategories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[] ; } } public BlogPostCategory[] Categories { get { // first return the new categories, then return the blog categories ArrayList categories = new ArrayList(); categories.AddRange(_newCategories); categories.AddRange(_blogCategories); return categories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[] ; } } public void SetBlogCategories(BlogPostCategory[] categories) { _blogCategories.Clear(); _blogCategories.AddRange(categories); DoChange(ChangeType.Category) ; } private ArrayList _blogCategories = new ArrayList(); public void SetNewCategories(BlogPostCategory[] categories) { _newCategories.Clear(); // de-dup with any categories that already exist for this blog foreach (BlogPostCategory category in categories) if ( !_blogCategories.Contains(category) ) _newCategories.Add(category) ; DoChange(ChangeType.Category) ; } public void AddNewCategory(BlogPostCategory newCategory) { // add the new category _newCategories.Add(newCategory) ; // fire the change event DoChange(ChangeType.Category) ; } private ArrayList _newCategories = new ArrayList(); public void CommitNewCategory(BlogPostCategory newCategory) { // remove from the new category list for (int i=0; i<_newCategories.Count; i++) { if ( (_newCategories[i] as BlogPostCategory).Name.Equals(newCategory.Name) ) { _newCategories.RemoveAt(i); break; } } // add to blog categories list and save the list _blogCategories.Add(newCategory) ; _blogCategorySettings.UpdateCategories(BlogCategories); // refresh selected categories (makes sure they pickup the category id) SelectedCategories = InsureSelectedValuesAreInCategoryList(_selectedCategories, false); // notify of change DoChange(ChangeType.Category) ; } public string Text { get { switch(SelectedCategories.Length) { case 0: return SelectionMode == SelectionModes.MultiSelect ? Res.Get(StringId.CategoryControlSetCategories) : Res.Get(StringId.CategoryControlSetCategory) ; default: return HtmlUtils.UnEscapeEntities(StringHelper.Join(SelectedCategories, CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "), HtmlUtils.UnEscapeMode.Attribute); } } } public string FormattedCategoryList { get { return string.Format( CultureInfo.CurrentCulture, ( SelectionMode == SelectionModes.MultiSelect ) ? Res.Get(StringId.CategoryControlCategories) : Res.Get(StringId.CategoryControlCategory), (SelectedCategories.Length == 0) ? Res.Get(StringId.CategoryControlNoCategories) : HtmlUtils.UnEscapeEntities(StringHelper.Join(SelectedCategories, CultureInfo.CurrentCulture.TextInfo.ListSeparator + " "), HtmlUtils.UnEscapeMode.Default)); } } public SelectionModes SelectionMode { get { return _selectionMode; } set { if (_selectionMode != value) { _selectionMode = value; DoChange(ChangeType.SelectionMode); } } } private SelectionModes _selectionMode = SelectionModes.MultiSelect; public bool SupportsAddingCategories { get { return _supportsAddingCategories; } set { _supportsAddingCategories = value; } } private bool _supportsAddingCategories = false ; public bool SupportsHierarchicalCategories { get { return _supportsHeirarchicalCategories; } set { _supportsHeirarchicalCategories = value; } } private bool _supportsHeirarchicalCategories = false ; public int MaxCategoryNameLength { get { return _maxCategoryNameLength; } set { _maxCategoryNameLength = value; } } private int _maxCategoryNameLength = 0 ; public enum SelectionModes { SingleSelect, MultiSelect } public void Refresh() { Refresh(false); } private void Refresh(bool ignoreErrors) { if (_blogCategorySettings != null) { SetBlogCategories(_blogCategorySettings.RefreshCategories(ignoreErrors)) ; SelectedCategories = InsureSelectedValuesAreInCategoryList(_selectedCategories, false); } } public IBlogCategorySettings BlogCategorySettings { get { return _blogCategorySettings; } set { _blogCategorySettings = value; } } private IBlogCategorySettings _blogCategorySettings; public event CategoryChangedEventHandler Changed; protected virtual void OnChanged(object sender, CategoryChangedEventArgs e) { if (Changed != null) Changed(sender, e); } private BlogPostCategory[] InsureSelectedValuesAreInCategoryList(BlogPostCategory[] selectedCategories, bool allowAutoRefresh) { ArrayList updatedCategoryList = new ArrayList(); // for each potential selection, validate that there is an existing category // with the same id or name and "match" it by adding the category to our // list of selected categories foreach ( BlogPostCategory selectedCategory in selectedCategories ) { // find a match in the list foreach ( BlogPostCategory category in Categories ) { if ( category.Equals(selectedCategory) ) { updatedCategoryList.Add(category) ; break ; } } } return (BlogPostCategory[]) updatedCategoryList.ToArray(typeof(BlogPostCategory)); } private void DoChange(ChangeType changeType) { OnChanged(this, new CategoryChangedEventArgs(changeType)); } public enum ChangeType { Category, SelectedCategory, SelectionMode } public delegate void CategoryChangedEventHandler(object sender, CategoryChangedEventArgs eventArgs); public class CategoryChangedEventArgs : EventArgs { private ChangeType _changeType; public CategoryChangedEventArgs(ChangeType changeType) : base() { _changeType = changeType; } public ChangeType ChangeType { get { return _changeType; } } } } internal class BlogPostCategoryListItem : IComparable, ICloneable { public BlogPostCategoryListItem(BlogPostCategory category, int indentLevel) : this(category, indentLevel, new ArrayList()) { } public BlogPostCategoryListItem(BlogPostCategory category, int indentLevel, ArrayList children) { _category = category ; _indentLevel = indentLevel ; _children = children ; } public BlogPostCategory Category { get { return _category; } } private BlogPostCategory _category ; public int IndentLevel { get { return _indentLevel; } } private int _indentLevel ; public ArrayList Children{ get { return _children; } } private ArrayList _children ; public int CompareTo(object obj) { return Category.CompareTo((obj as BlogPostCategoryListItem).Category) ; } public object Clone() { return new BlogPostCategoryListItem(Category, IndentLevel, Children.Clone() as ArrayList); } public static BlogPostCategoryListItem[] BuildList(BlogPostCategory[] categories, bool flatten) { // acculate available parents Hashtable availableParents = new Hashtable(); foreach (BlogPostCategory category in categories) availableParents[category.Id] = null ; // build an array list of categories, fixing up categories with "invalid" // parent ids to be root items ArrayList sourceCategories = new ArrayList(); foreach (BlogPostCategory category in categories) { string parent = category.Parent ; if ( !availableParents.ContainsKey(category.Parent) ) parent = String.Empty ; sourceCategories.Add(new BlogPostCategory(category.Id, category.Name, parent)) ; } // get a tree of child items ArrayList categoryListItems = ExtractChildItemsOfParent(sourceCategories, String.Empty, 0) ; // flatten list if requested if ( flatten ) categoryListItems = FlattenList(categoryListItems) ; // return list return categoryListItems.ToArray(typeof(BlogPostCategoryListItem)) as BlogPostCategoryListItem[] ; } private static ArrayList ExtractChildItemsOfParent(ArrayList sourceCategories, string parentId, int indentLevel) { // accumulate all categories with the specified parent ArrayList childItems = new ArrayList(); foreach ( BlogPostCategory category in sourceCategories.Clone() as ArrayList) { if ( category.Parent == parentId ) { // add category to our list and remove it from the source list childItems.Add( new BlogPostCategoryListItem(category, indentLevel) ) ; sourceCategories.Remove(category); } } // sort the list alphabetically childItems.Sort(); // add the children of each item recursively foreach (BlogPostCategoryListItem categoryListItem in childItems) categoryListItem.Children.AddRange(ExtractChildItemsOfParent(sourceCategories, categoryListItem.Category.Id, categoryListItem.IndentLevel+1)); // return the list return childItems ; } private static ArrayList FlattenList(ArrayList sourceList) { ArrayList flattenedList = new ArrayList(); foreach( BlogPostCategoryListItem listItem in sourceList ) { // add the item flattenedList.Add(listItem) ; if ( listItem.Children.Count > 0 ) { // add children recursively flattenedList.AddRange(FlattenList(listItem.Children)); // reset children because we are flattened listItem.Children.Clear(); } } return flattenedList ; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using FunWithPostgres.Models; using FunWithPostgres.Models.ManageViewModels; using FunWithPostgres.Services; namespace FunWithPostgres.Controllers { [Authorize] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly string _externalCookieScheme; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IOptions<IdentityCookieOptions> identityCookieOptions, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LinkLogin(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(nameof(LinkLoginCallback), "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return Challenge(properties, provider); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = ManageMessageId.Error; if (result.Succeeded) { message = ManageMessageId.AddLoginSuccess; // Clear the existing external cookie to ensure a clean login process await HttpContext.Authentication.SignOutAsync(_externalCookieScheme); } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SourceParkAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- // // Description: // ContentType class parses and validates the content-type string. // It provides functionality to compare the type/subtype values. // // Details: // Grammar which this class follows - // // Content-type grammar MUST conform to media-type grammar as per // RFC 2616 (ABNF notation): // // media-type = type "/" subtype *( ";" parameter ) // type = token // subtype = token // parameter = attribute "=" value // attribute = token // value = token | quoted-string // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) // qdtext = <any TEXT except <">> // quoted-pair = "\" CHAR // token = 1*<any CHAR except CTLs or separators> // separators = "(" | ")" | "<" | ">" | "@" // | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" // | "{" | "}" | SP | HT // TEXT = <any OCTET except CTLs, but including LWS> // OCTET = <any 8-bit sequence of data> // CHAR = <any US-ASCII character (octets 0 - 127)> // CTL = <any US-ASCII control character(octets 0 - 31)and DEL(127)> // CR = <US-ASCII CR, carriage return (13)> // LF = <US-ASCII LF, linefeed (10)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // <"> = <US-ASCII double-quote mark (34)> // LWS = [CRLF] 1*( SP | HT ) // CRLF = CR LF // Linear white space (LWS) MUST NOT be used between the type and subtype, nor // between an attribute and its value. Leading and trailing LWS are prohibited. // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; // For Dictionary<string, string> using System.Text; // For StringBuilder using System.Diagnostics; // For Debug.Assert namespace System.IO.Packaging { /// <summary> /// Content Type class /// </summary> internal sealed class ContentType { #region Internal Constructors /// <summary> /// This constructor creates a ContentType object that represents /// the content-type string. At construction time we validate the /// string as per the grammar specified in RFC 2616. /// Note: We allow empty strings as valid input. Empty string should /// we used more as an indication of an absent/unknown ContentType. /// </summary> /// <param name="contentType">content-type</param> /// <exception cref="ArgumentNullException">If the contentType parameter is null</exception> /// <exception cref="ArgumentException">If the contentType string has leading or /// trailing Linear White Spaces(LWS) characters</exception> /// <exception cref="ArgumentException">If the contentType string invalid CR-LF characters</exception> internal ContentType(string contentType) { if (contentType == null) throw new ArgumentNullException(nameof(contentType)); if (contentType.Length == 0) { _contentType = String.Empty; } else { if (IsLinearWhiteSpaceChar(contentType[0]) || IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])) throw new ArgumentException(SR.ContentTypeCannotHaveLeadingTrailingLWS); //Carriage return can be expressed as '\r\n' or '\n\r' //We need to make sure that a \r is accompanied by \n ValidateCarriageReturns(contentType); //Begin Parsing int semiColonIndex = contentType.IndexOf(SemicolonSeparator); if (semiColonIndex == -1) { // Parse content type similar to - type/subtype ParseTypeAndSubType(contentType); } else { // Parse content type similar to - type/subtype ; param1=value1 ; param2=value2 ; param3="value3" ParseTypeAndSubType(contentType.Substring(0, semiColonIndex)); ParseParameterAndValue(contentType.Substring(semiColonIndex)); } } // keep this untouched for return from OriginalString property _originalString = contentType; //This variable is used to print out the correct content type string representation //using the ToString method. This is mainly important while debugging and seeing the //value of the content type object in the debugger. _isInitialized = true; } #endregion Internal Constructors #region Internal Properties /// <summary> /// TypeComponent of the Content Type /// If the content type is "text/xml". This property will return "text" /// </summary> internal string TypeComponent { get { return _type; } } /// <summary> /// SubType component /// If the content type is "text/xml". This property will return "xml" /// </summary> internal string SubTypeComponent { get { return _subType; } } /// <summary> /// Enumerator which iterates over the Parameter and Value pairs which are stored /// in a dictionary. We hand out just the enumerator in order to make this property /// ReadOnly /// Consider following Content type - /// type/subtype ; param1=value1 ; param2=value2 ; param3="value3" /// This will return an enumerator over a dictionary of the parameter/value pairs. /// </summary> internal Dictionary<string, string>.Enumerator ParameterValuePairs { get { EnsureParameterDictionary(); return _parameterDictionary.GetEnumerator(); } } #endregion Internal Properties #region Internal Methods /// <summary> /// This method does a strong comparison of the content types, as parameters are not allowed. /// We only compare the type and subType values in an ASCII case-insensitive manner. /// Parameters are not allowed to be present on any of the content type operands. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType) { return AreTypeAndSubTypeEqual(contentType, false); } /// <summary> /// This method does a weak comparison of the content types. We only compare the /// type and subType values in an ASCII case-insensitive manner. /// Parameter and value pairs are not used for the comparison. /// If you wish to compare the parameters too, then you must get the ParameterValuePairs from /// both the ContentType objects and compare each parameter entry. /// The allowParameterValuePairs parameter is used to indicate whether the /// comparison is tolerant to parameters being present or no. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <param name="allowParameterValuePairs">If true, allows the presence of parameter value pairs. /// If false, parameter/value pairs cannot be present in the content type string. /// In either case, the parameter value pair is not used for the comparison.</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType, bool allowParameterValuePairs) { bool result = false; if (contentType != null) { if (!allowParameterValuePairs) { //Return false if this content type object has parameters if (_parameterDictionary != null) { if (_parameterDictionary.Count > 0) return false; } //Return false if the content type object passed in has parameters Dictionary<string, string>.Enumerator contentTypeEnumerator; contentTypeEnumerator = contentType.ParameterValuePairs; contentTypeEnumerator.MoveNext(); if (contentTypeEnumerator.Current.Key != null) return false; } // Perform a case-insensitive comparison on the type/subtype strings. This is a // safe comparison because the _type and _subType strings have been restricted to // ASCII characters, digits, and a small set of symbols. This is not a safe comparison // for the broader set of strings that have not been restricted in the same way. result = (String.Equals(_type, contentType.TypeComponent, StringComparison.OrdinalIgnoreCase) && String.Equals(_subType, contentType.SubTypeComponent, StringComparison.OrdinalIgnoreCase)); } return result; } /// <summary> /// ToString - outputs a normalized form of the content type string /// </summary> /// <returns></returns> public override string ToString() { if (_contentType == null) { //This is needed so that while debugging we get the correct //string if (!_isInitialized) return String.Empty; Debug.Assert(String.CompareOrdinal(_type, String.Empty) != 0 || String.CompareOrdinal(_subType, String.Empty) != 0); StringBuilder stringBuilder = new StringBuilder(_type); stringBuilder.Append(PackUriHelper.ForwardSlashChar); stringBuilder.Append(_subType); if (_parameterDictionary != null && _parameterDictionary.Count > 0) { foreach (string parameterKey in _parameterDictionary.Keys) { stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(SemicolonSeparator); stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(parameterKey); stringBuilder.Append(EqualSeparator); stringBuilder.Append(_parameterDictionary[parameterKey]); } } _contentType = stringBuilder.ToString(); } return _contentType; } #endregion Internal Methods #region Private Methods /// <summary> /// This method validates if the content type string has /// valid CR-LF characters. Specifically we test if '\r' is /// accompanied by a '\n' in the string, else its an error. /// </summary> /// <param name="contentType"></param> private static void ValidateCarriageReturns(string contentType) { Debug.Assert(!IsLinearWhiteSpaceChar(contentType[0]) && !IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])); //Prior to calling this method we have already checked that first and last //character of the content type are not Linear White Spaces. So its safe to //assume that the index will be greater than 0 and less that length-2. int index = contentType.IndexOf(s_linearWhiteSpaceChars[2]); while (index != -1) { if (contentType[index - 1] == s_linearWhiteSpaceChars[1] || contentType[index + 1] == s_linearWhiteSpaceChars[1]) { index = contentType.IndexOf(s_linearWhiteSpaceChars[2], ++index); } else throw new ArgumentException(SR.InvalidLinearWhiteSpaceCharacter); } } /// <summary> /// Parses the type and subType tokens from the string. /// Also verifies if the Tokens are valid as per the grammar. /// </summary> /// <param name="typeAndSubType">substring that has the type and subType of the content type</param> /// <exception cref="ArgumentException">If the typeAndSubType parameter does not have the "/" character</exception> private void ParseTypeAndSubType(string typeAndSubType) { //okay to trim at this point the end of the string as Linear White Spaces(LWS) chars are allowed here. typeAndSubType = typeAndSubType.TrimEnd(s_linearWhiteSpaceChars); string[] splitBasedOnForwardSlash = typeAndSubType.Split(PackUriHelper.s_forwardSlashCharArray); if (splitBasedOnForwardSlash.Length != 2) throw new ArgumentException(SR.InvalidTypeSubType); _type = ValidateToken(splitBasedOnForwardSlash[0]); _subType = ValidateToken(splitBasedOnForwardSlash[1]); } /// <summary> /// Parse the individual parameter=value strings /// </summary> /// <param name="parameterAndValue">This string has the parameter and value pair of the form /// parameter=value</param> /// <exception cref="ArgumentException">If the string does not have the required "="</exception> private void ParseParameterAndValue(string parameterAndValue) { while (parameterAndValue != string.Empty) { //At this point the first character MUST be a semi-colon //First time through this test is serving more as an assert. if (parameterAndValue[0] != SemicolonSeparator) throw new ArgumentException(SR.ExpectingSemicolon); //At this point if we have just one semicolon, then its an error. //Also, there can be no trailing LWS characters, as we already checked for that //in the constructor. if (parameterAndValue.Length == 1) throw new ArgumentException(SR.ExpectingParameterValuePairs); //Removing the leading ; from the string parameterAndValue = parameterAndValue.Substring(1); //okay to trim start as there can be spaces before the beginning //of the parameter name. parameterAndValue = parameterAndValue.TrimStart(s_linearWhiteSpaceChars); int equalSignIndex = parameterAndValue.IndexOf(EqualSeparator); if (equalSignIndex <= 0 || equalSignIndex == (parameterAndValue.Length - 1)) throw new ArgumentException(SR.InvalidParameterValuePair); int parameterStartIndex = equalSignIndex + 1; //Get length of the parameter value int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex); EnsureParameterDictionary(); _parameterDictionary.Add( ValidateToken(parameterAndValue.Substring(0, equalSignIndex)), ValidateQuotedStringOrToken(parameterAndValue.Substring(parameterStartIndex, parameterValueLength))); parameterAndValue = parameterAndValue.Substring(parameterStartIndex + parameterValueLength).TrimStart(s_linearWhiteSpaceChars); } } /// <summary> /// This method returns the length of the first parameter value in the input string. /// </summary> /// <param name="s"></param> /// <param name="startIndex">Starting index for parsing</param> /// <returns></returns> private static int GetLengthOfParameterValue(string s, int startIndex) { Debug.Assert(s != null); int length = 0; //if the parameter value does not start with a '"' then, //we expect a valid token. So we look for Linear White Spaces or //a ';' as the terminator for the token value. if (s[startIndex] != '"') { int semicolonIndex = s.IndexOf(SemicolonSeparator, startIndex); if (semicolonIndex != -1) { int lwsIndex = s.IndexOfAny(s_linearWhiteSpaceChars, startIndex); if (lwsIndex != -1 && lwsIndex < semicolonIndex) length = lwsIndex; else length = semicolonIndex; } else length = semicolonIndex; //If there is no linear whitespace found we treat the entire remaining string as //parameter value. if (length == -1) length = s.Length; } else { //if the parameter value starts with a '"' then, we need to look for the //pairing '"' that is not preceded by a "\" ["\" is used to escape the '"'] bool found = false; length = startIndex; while (!found) { length = s.IndexOf('"', ++length); if (length == -1) throw new ArgumentException(SR.InvalidParameterValue); if (s[length - 1] != '\\') { found = true; length++; } } } return length - startIndex; } /// <summary> /// Validating the given token /// The following checks are being made - /// 1. If all the characters in the token are either ASCII letter or digit. /// 2. If all the characters in the token are either from the remaining allowed cha----ter set. /// </summary> /// <param name="token">string token</param> /// <returns>validated string token</returns> /// <exception cref="ArgumentException">If the token is Empty</exception> private static string ValidateToken(string token) { if (String.IsNullOrEmpty(token)) throw new ArgumentException(SR.InvalidToken); for (int i = 0; i < token.Length; i++) { if (!IsAsciiLetterOrDigit(token[i]) && !IsAllowedCharacter(token[i])) { throw new ArgumentException(SR.InvalidToken); } } return token; } /// <summary> /// Validating if the value of a parameter is either a valid token or a /// valid quoted string /// </summary> /// <param name="parameterValue">parameter value string</param> /// <returns>validate parameter value string</returns> /// <exception cref="ArgumentException">If the parameter value is empty</exception> private static string ValidateQuotedStringOrToken(string parameterValue) { if (String.IsNullOrEmpty(parameterValue)) throw new ArgumentException(SR.InvalidParameterValue); if (parameterValue.Length >= 2 && parameterValue.StartsWith(Quote, StringComparison.Ordinal) && parameterValue.EndsWith(Quote, StringComparison.Ordinal)) ValidateQuotedText(parameterValue.Substring(1, parameterValue.Length - 2)); else ValidateToken(parameterValue); return parameterValue; } /// <summary> /// This method validates if the text in the quoted string /// </summary> /// <param name="quotedText"></param> private static void ValidateQuotedText(string quotedText) { //empty is okay for (int i = 0; i < quotedText.Length; i++) { if (IsLinearWhiteSpaceChar(quotedText[i])) continue; if (quotedText[i] <= ' ' || quotedText[i] >= 0xFF) throw new ArgumentException(SR.InvalidParameterValue); else if (quotedText[i] == '"' && (i == 0 || quotedText[i - 1] != '\\')) throw new ArgumentException(SR.InvalidParameterValue); } } /// <summary> /// Returns true if the input character is an allowed character /// Returns false if the input cha----ter is not an allowed character /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAllowedCharacter(char character) { return Array.IndexOf(s_allowedCharacters, character) >= 0; } /// <summary> /// Returns true if the input character is an ASCII digit or letter /// Returns false if the input character is not an ASCII digit or letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetterOrDigit(char character) { return (IsAsciiLetter(character) || (character >= '0' && character <= '9')); } /// <summary> /// Returns true if the input character is an ASCII letter /// Returns false if the input character is not an ASCII letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } /// <summary> /// Returns true if the input character is one of the Linear White Space characters - /// ' ', '\t', '\n', '\r' /// Returns false if the input character is none of the above /// </summary> /// <param name="ch">input character</param> /// <returns></returns> private static bool IsLinearWhiteSpaceChar(char ch) { if (ch > ' ') { return false; } int whiteSpaceIndex = Array.IndexOf(s_linearWhiteSpaceChars, ch); return whiteSpaceIndex != -1; } /// <summary> /// Lazy initialization for the ParameterDictionary /// </summary> private void EnsureParameterDictionary() { if (_parameterDictionary == null) { _parameterDictionary = new Dictionary<string, string>(); //initial size 0 } } #endregion Private Methods #region Private Members private string _contentType = null; private string _type = String.Empty; private string _subType = String.Empty; private string _originalString; private Dictionary<string, string> _parameterDictionary = null; private bool _isInitialized = false; private const string Quote = "\""; private const char SemicolonSeparator = ';'; private const char EqualSeparator = '='; //This array is sorted by the ascii value of these characters. private static readonly char[] s_allowedCharacters = { '!' /*33*/, '#' /*35*/ , '$' /*36*/, '%' /*37*/, '&' /*38*/ , '\'' /*39*/, '*' /*42*/, '+' /*43*/ , '-' /*45*/, '.' /*46*/, '^' /*94*/ , '_' /*95*/, '`' /*96*/, '|' /*124*/, '~' /*126*/, }; //Linear White Space characters private static readonly char[] s_linearWhiteSpaceChars = { ' ', // space - \x20 '\n', // new line - \x0A '\r', // carriage return - \x0D '\t' // horizontal tab - \x09 }; #endregion Private Members } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using MLifter.DAL.Interfaces; using MLifter.DAL.Interfaces.DB; using MLifter.DAL.DB.PostgreSQL; using Npgsql; using MLifter.DAL.Tools; namespace MLifter.DAL.DB.PostgreSQL { class PgSqlQueryMultipleChoiceOptionsConnector : IDbQueryMultipleChoiceOptionsConnector { private static Dictionary<ConnectionStringStruct, PgSqlQueryMultipleChoiceOptionsConnector> instances = new Dictionary<ConnectionStringStruct, PgSqlQueryMultipleChoiceOptionsConnector>(); public static PgSqlQueryMultipleChoiceOptionsConnector GetInstance(ParentClass parentClass) { lock (instances) { ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString; if (!instances.ContainsKey(connection)) instances.Add(connection, new PgSqlQueryMultipleChoiceOptionsConnector(parentClass)); return instances[connection]; } } private ParentClass Parent; private PgSqlQueryMultipleChoiceOptionsConnector(ParentClass parentClass) { Parent = parentClass; Parent.DictionaryClosed += new EventHandler(Parent_DictionaryClosed); } void Parent_DictionaryClosed(object sender, EventArgs e) { IParent parent = sender as IParent; instances.Remove(parent.Parent.CurrentUser.ConnectionString); } private void GetSettingsValue(int multipleChoiceId, CacheObject cacheObjectType, out object cacheValue) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT * FROM \"MultipleChoiceOptions\" WHERE id=:id"; cmd.Parameters.Add("id", multipleChoiceId); NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser); reader.Read(); int? mid = DbValueConverter.Convert<int>(reader["id"]); bool? allowMultipleCorrectAnswers = DbValueConverter.Convert<bool>(reader["allow_multiple_correct_answers"]); bool? allowRandomDistractors = DbValueConverter.Convert<bool>(reader["allow_random_distractors"]); int? maxCorrectAnswers = DbValueConverter.Convert<int>(reader["max_correct_answers"]); int? numberOfChoices = DbValueConverter.Convert<int>(reader["number_of_choices"]); //cache values DateTime expires = DateTime.Now.Add(Cache.DefaultSettingsValidationTime); Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers, multipleChoiceId, expires)] = allowMultipleCorrectAnswers; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors, multipleChoiceId, expires)] = allowRandomDistractors; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers, multipleChoiceId, expires)] = maxCorrectAnswers; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices, multipleChoiceId, expires)] = numberOfChoices; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsId, multipleChoiceId, expires)] = mid; //set output value switch (cacheObjectType) { case CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers: cacheValue = allowMultipleCorrectAnswers; break; case CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors: cacheValue = allowRandomDistractors; break; case CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers: cacheValue = maxCorrectAnswers; break; case CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices: cacheValue = numberOfChoices; break; case CacheObject.SettingsMultipleChoiceOptionsId: cacheValue = mid; break; default: cacheValue = null; break; } } } } private bool SettingsCached(int multipleChoiceId, CacheObject cacheObjectType, out object cacheValue) { int? multipleChoiceIdCached = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.SettingsMultipleChoiceOptionsId, multipleChoiceId)] as int?; cacheValue = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(cacheObjectType, multipleChoiceId)]; return multipleChoiceIdCached.HasValue && (cacheValue != null); } #region IDbQueryMultipleChoiceOptionsConnector Members public void CheckId(int id) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "SELECT count(*) FROM \"MultipleChoiceOptions\" WHERE id=:id"; cmd.Parameters.Add("id", id); if (Convert.ToInt32(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser)) < 1) throw new IdAccessException(id); } } } public bool? GetAllowMultiple(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; //using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) //{ // using (NpgsqlCommand cmd = con.CreateCommand()) // { // cmd.CommandText = "SELECT allow_multiple_correct_answers FROM \"MultipleChoiceOptions\" WHERE id=:id"; // cmd.Parameters.Add("id", id); // return PostgreSQLConn.ExecuteScalar<bool>(cmd); // } //} } public void SetAllowMultiple(int id, bool? AllowMultiple) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"MultipleChoiceOptions\" SET allow_multiple_correct_answers=" + (AllowMultiple.HasValue ? ":value" : "null") + " WHERE id=:id"; cmd.Parameters.Add("id", id); if (AllowMultiple.HasValue) cmd.Parameters.Add("value", AllowMultiple); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsAllowMultipleCorrectAnswers, id, Cache.DefaultSettingsValidationTime)] = AllowMultiple; } } } public bool? GetAllowRandom(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as bool?; //using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) //{ // using (NpgsqlCommand cmd = con.CreateCommand()) // { // cmd.CommandText = "SELECT allow_random_distractors FROM \"MultipleChoiceOptions\" WHERE id=:id"; // cmd.Parameters.Add("id", id); // return PostgreSQLConn.ExecuteScalar<bool>(cmd); // } //} } public void SetAllowRandom(int id, bool? AllowRandom) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"MultipleChoiceOptions\" SET allow_random_distractors=" + (AllowRandom.HasValue ? ":value" : "null") + " WHERE id=:id"; cmd.Parameters.Add("id", id); if (AllowRandom.HasValue) cmd.Parameters.Add("value", AllowRandom); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsAllowRandomDistractors, id, Cache.DefaultSettingsValidationTime)] = AllowRandom; } } } public int? GetMaxCorrect(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as int?; //using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) //{ // using (NpgsqlCommand cmd = con.CreateCommand()) // { // cmd.CommandText = "SELECT max_correct_answers FROM \"MultipleChoiceOptions\" WHERE id=:id"; // cmd.Parameters.Add("id", id); // return PostgreSQLConn.ExecuteScalar<int>(cmd); // } //} } public void SetMaxCorrect(int id, int? MaxCorrect) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"MultipleChoiceOptions\" SET max_correct_answers=" + (MaxCorrect.HasValue ? ":value" : "null") + " WHERE id=:id"; cmd.Parameters.Add("id", id); if (MaxCorrect.HasValue) cmd.Parameters.Add("value", MaxCorrect); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsMaxCorrectAnswers, id, Cache.DefaultSettingsValidationTime)] = MaxCorrect; } } } public int? GetChoices(int id) { object cacheValue; if (!SettingsCached(id, CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices, out cacheValue)) //if settings are not in Cache --> load them GetSettingsValue(id, CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices, out cacheValue); //Saves the current Settings from the DB to the Cache return cacheValue as int?; //using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) //{ // using (NpgsqlCommand cmd = con.CreateCommand()) // { // cmd.CommandText = "SELECT number_of_choices FROM \"MultipleChoiceOptions\" WHERE id=:id"; // cmd.Parameters.Add("id", id); // return PostgreSQLConn.ExecuteScalar<int>(cmd); // } //} } public void SetChoices(int id, int? Choices) { using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser)) { using (NpgsqlCommand cmd = con.CreateCommand()) { cmd.CommandText = "UPDATE \"MultipleChoiceOptions\" SET number_of_choices=" + (Choices.HasValue ? ":value" : "null") + " WHERE id=:id"; cmd.Parameters.Add("id", id); if (Choices.HasValue) cmd.Parameters.Add("value", Choices); PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser); //Save to Cache Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.SettingsMultipleChoiceOptionsNumberOfChoices, id, Cache.DefaultSettingsValidationTime)] = Choices; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.ExceptionServices; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Microsoft.AspNetCore.Components.Rendering { public class HtmlRendererTest { protected readonly HtmlEncoder _encoder = HtmlEncoder.Default; [Fact] public void RenderComponentAsync_CanRenderEmptyElement() { // Arrange var expectedHtml = new[] { "<", "p", ">", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanRenderSimpleComponent() { // Arrange var expectedHtml = new[] { "<", "p", ">", "Hello world!", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddContent(1, "Hello world!"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_HtmlEncodesContent() { // Arrange var expectedHtml = new[] { "<", "p", ">", "&lt;Hello world!&gt;", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddContent(1, "<Hello world!>"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_DoesNotEncodeMarkup() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<span>Hello world!</span>", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddMarkupContent(1, "<span>Hello world!</span>"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanRenderWithAttributes() { // Arrange var expectedHtml = new[] { "<", "p", " ", "class", "=", "\"", "lead", "\"", ">", "Hello world!", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddAttribute(1, "class", "lead"); rtb.AddContent(2, "Hello world!"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_SkipsDuplicatedAttribute() { // Arrange var expectedHtml = new[] { "<", "p", " ", "another", "=", "\"", "another-value", "\"", " ", "Class", "=", "\"", "test2", "\"", ">", "Hello world!", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddAttribute(1, "class", "test1"); rtb.AddAttribute(2, "another", "another-value"); rtb.AddMultipleAttributes(3, new Dictionary<string, object>() { { "Class", "test2" }, // Matching is case-insensitive. }); rtb.AddContent(4, "Hello world!"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_HtmlEncodesAttributeValues() { // Arrange var expectedHtml = new[] { "<", "p", " ", "class", "=", "\"", "&lt;lead", "\"", ">", "Hello world!", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddAttribute(1, "class", "<lead"); rtb.AddContent(2, "Hello world!"); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanRenderBooleanAttributes() { // Arrange var expectedHtml = new[] { "<", "input", " ", "disabled", " />" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "input"); rtb.AddAttribute(1, "disabled", true); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_DoesNotRenderBooleanAttributesWhenValueIsFalse() { // Arrange var expectedHtml = new[] { "<", "input", " />" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "input"); rtb.AddAttribute(1, "disabled", false); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanRenderWithChildren() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "span", ">", "Hello world!", "</", "span", ">", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "span"); rtb.AddContent(2, "Hello world!"); rtb.CloseElement(); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanRenderWithMultipleChildren() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "span", ">", "Hello world!", "</", "span", ">", "<", "span", ">", "Bye Bye world!", "</", "span", ">", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "span"); rtb.AddContent(2, "Hello world!"); rtb.CloseElement(); rtb.OpenElement(3, "span"); rtb.AddContent(4, "Bye Bye world!"); rtb.CloseElement(); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_MarksSelectedOptionsAsSelected() { // Arrange var expectedHtml = "<p>" + @"<select unrelated-attribute-before=""a"" value=""b"" unrelated-attribute-after=""c"">" + @"<option unrelated-attribute=""a"" value=""a"">Pick value a</option>" + @"<option unrelated-attribute=""a"" value=""b"" selected>Pick value b</option>" + @"<option unrelated-attribute=""a"" value=""c"">Pick value c</option>" + "</select>" + @"<option value=""b"">unrelated option</option>" + "</p>"; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "select"); rtb.AddAttribute(2, "unrelated-attribute-before", "a"); rtb.AddAttribute(3, "value", "b"); rtb.AddAttribute(4, "unrelated-attribute-after", "c"); foreach (var optionValue in new[] { "a", "b", "c" }) { rtb.OpenElement(5, "option"); rtb.AddAttribute(6, "unrelated-attribute", "a"); rtb.AddAttribute(7, "value", optionValue); rtb.AddContent(8, $"Pick value {optionValue}"); rtb.CloseElement(); // option } rtb.CloseElement(); // select rtb.OpenElement(9, "option"); // To show other value-matching options don't get marked as selected rtb.AddAttribute(10, "value", "b"); rtb.AddContent(11, "unrelated option"); rtb.CloseElement(); // option rtb.CloseElement(); // p })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, string.Concat(result)); } [Fact] public void RenderComponentAsync_MarksSelectedOptionsAsSelected_WithOptGroups() { // Arrange var expectedHtml = @"<select value=""beta"">" + @"<optgroup><option value=""alpha"">alpha</option></optgroup>" + @"<optgroup><option value=""beta"" selected>beta</option></optgroup>" + @"<optgroup><option value=""gamma"">gamma</option></optgroup>" + "</select>"; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "select"); rtb.AddAttribute(1, "value", "beta"); foreach (var optionValue in new[] { "alpha", "beta", "gamma" }) { rtb.OpenElement(2, "optgroup"); rtb.OpenElement(3, "option"); rtb.AddAttribute(4, "value", optionValue); rtb.AddContent(5, optionValue); rtb.CloseElement(); // option rtb.CloseElement(); // optgroup } rtb.CloseElement(); // select })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, string.Concat(result)); } [Fact] public void RenderComponentAsync_CanRenderComponentAsyncWithChildrenComponents() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "span", ">", "Hello world!", "</", "span", ">", "</", "p", ">", "<", "span", ">", "Child content!", "</", "span", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "span"); rtb.AddContent(2, "Hello world!"); rtb.CloseElement(); rtb.CloseElement(); rtb.OpenComponent(3, typeof(ChildComponent)); rtb.AddAttribute(4, "Value", "Child content!"); rtb.CloseComponent(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_ComponentReferenceNoops() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "span", ">", "Hello world!", "</", "span", ">", "</", "p", ">", "<", "span", ">", "Child content!", "</", "span", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "span"); rtb.AddContent(2, "Hello world!"); rtb.CloseElement(); rtb.CloseElement(); rtb.OpenComponent(3, typeof(ChildComponent)); rtb.AddAttribute(4, "Value", "Child content!"); rtb.AddComponentReferenceCapture(5, cr => { }); rtb.CloseComponent(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanPassParameters() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "input", " ", "value", "=", "\"", "5", "\"", " />", "</", "p", ">" }; RenderFragment Content(ParameterView pc) => new RenderFragment((RenderTreeBuilder rtb) => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "input"); rtb.AddAttribute(2, "change", pc.GetValueOrDefault<Action<ChangeEventArgs>>("update")); rtb.AddAttribute(3, "value", pc.GetValueOrDefault<int>("value")); rtb.CloseElement(); rtb.CloseElement(); }); var serviceProvider = new ServiceCollection() .AddSingleton(new Func<ParameterView, RenderFragment>(Content)) .BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); Action<ChangeEventArgs> change = (ChangeEventArgs changeArgs) => throw new InvalidOperationException(); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<ComponentWithParameters>( ParameterView.FromDictionary(new Dictionary<string, object> { { "update", change }, { "value", 5 } })))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_CanRenderComponentAsyncWithRenderFragmentContent() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "span", ">", "Hello world!", "</", "span", ">", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.OpenElement(1, "span"); rtb.AddContent(2, // This internally creates a region frame. rf => rf.AddContent(0, "Hello world!")); rtb.CloseElement(); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } [Fact] public void RenderComponentAsync_ElementRefsNoops() { // Arrange var expectedHtml = new[] { "<", "p", ">", "<", "span", ">", "Hello world!", "</", "span", ">", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddElementReferenceCapture(1, er => { }); rtb.OpenElement(2, "span"); rtb.AddContent(3, // This internally creates a region frame. rf => rf.AddContent(0, "Hello world!")); rtb.CloseElement(); rtb.CloseElement(); })).BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = GetResult(htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<TestComponent>(ParameterView.Empty))); // Assert Assert.Equal(expectedHtml, result); } private IEnumerable<string> GetResult(Task<ComponentRenderedText> task) { Assert.True(task.IsCompleted); if (task.IsCompletedSuccessfully) { return task.Result.Tokens; } else { ExceptionDispatchInfo.Capture(task.Exception).Throw(); throw new InvalidOperationException("We will never hit this line"); } } private class ComponentWithParameters : IComponent { public RenderHandle RenderHandle { get; private set; } public void Attach(RenderHandle renderHandle) { RenderHandle = renderHandle; } [Inject] Func<ParameterView, RenderFragment> CreateRenderFragment { get; set; } public Task SetParametersAsync(ParameterView parameters) { RenderHandle.Render(CreateRenderFragment(parameters)); return Task.CompletedTask; } } [Fact] public async Task CanRender_AsyncComponent() { // Arrange var expectedHtml = new[] { "<", "p", ">", "20", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton<AsyncComponent>().BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = await htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<AsyncComponent>(ParameterView.FromDictionary(new Dictionary<string, object> { ["Value"] = 10 }))); // Assert Assert.Equal(expectedHtml, result.Tokens); } [Fact] public async Task CanRender_NestedAsyncComponents() { // Arrange var expectedHtml = new[] { "<", "p", ">", "20", "</", "p", ">", "<", "p", ">", "80", "</", "p", ">" }; var serviceProvider = new ServiceCollection().AddSingleton<AsyncComponent>().BuildServiceProvider(); var htmlRenderer = GetHtmlRenderer(serviceProvider); // Act var result = await htmlRenderer.Dispatcher.InvokeAsync(() => htmlRenderer.RenderComponentAsync<NestedAsyncComponent>(ParameterView.FromDictionary(new Dictionary<string, object> { ["Nested"] = false, ["Value"] = 10 }))); // Assert Assert.Equal(expectedHtml, result.Tokens); } [Fact] public async Task PrerendersMultipleComponentsSuccessfully() { // Arrange var serviceProvider = new ServiceCollection().AddSingleton(new RenderFragment(rtb => { rtb.OpenElement(0, "p"); rtb.AddMarkupContent(1, "<span>Hello world!</span>"); rtb.CloseElement(); })).BuildServiceProvider(); var renderer = GetHtmlRenderer(serviceProvider); // Act var first = await renderer.Dispatcher.InvokeAsync(() => renderer.RenderComponentAsync<TestComponent>(ParameterView.Empty)); var second = await renderer.Dispatcher.InvokeAsync(() => renderer.RenderComponentAsync<TestComponent>(ParameterView.Empty)); // Assert Assert.Equal(0, first.ComponentId); Assert.Equal(1, second.ComponentId); } private HtmlRenderer GetHtmlRenderer(IServiceProvider serviceProvider) { return new HtmlRenderer(serviceProvider, NullLoggerFactory.Instance, _encoder); } private class NestedAsyncComponent : ComponentBase { [Parameter] public bool Nested { get; set; } [Parameter] public int Value { get; set; } protected override async Task OnInitializedAsync() { Value = Value * 2; await Task.Yield(); } protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "p"); builder.AddContent(1, Value.ToString(CultureInfo.InvariantCulture)); builder.CloseElement(); if (!Nested) { builder.OpenComponent<NestedAsyncComponent>(2); builder.AddAttribute(3, "Nested", true); builder.AddAttribute(4, "Value", Value * 2); builder.CloseComponent(); } } } private class AsyncComponent : ComponentBase { public AsyncComponent() { } [Parameter] public int Value { get; set; } protected override async Task OnInitializedAsync() { Value = Value * 2; await Task.Delay(Value * 100); } protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "p"); builder.AddContent(1, Value.ToString(CultureInfo.InvariantCulture)); builder.CloseElement(); } } private class ChildComponent : IComponent { private RenderHandle _renderHandle; public void Attach(RenderHandle renderHandle) { _renderHandle = renderHandle; } public Task SetParametersAsync(ParameterView parameters) { var content = parameters.GetValueOrDefault<string>("Value"); _renderHandle.Render(CreateRenderFragment(content)); return Task.CompletedTask; } private RenderFragment CreateRenderFragment(string content) { return RenderFragment; void RenderFragment(RenderTreeBuilder rtb) { rtb.OpenElement(1, "span"); rtb.AddContent(2, content); rtb.CloseElement(); } } } private class TestComponent : IComponent { private RenderHandle _renderHandle; [Inject] public RenderFragment Fragment { get; set; } public void Attach(RenderHandle renderHandle) { _renderHandle = renderHandle; } public Task SetParametersAsync(ParameterView parameters) { _renderHandle.Render(Fragment); return Task.CompletedTask; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Linq; using JetBrains.Annotations; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Lists; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Statistics; using osu.Framework.Testing; using osu.Game.Beatmaps.Formats; using osu.Game.IO; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Beatmaps { public class WorkingBeatmapCache : IBeatmapResourceProvider, IWorkingBeatmapCache { private readonly WeakList<BeatmapManagerWorkingBeatmap> workingCache = new WeakList<BeatmapManagerWorkingBeatmap>(); /// <summary> /// A default representation of a WorkingBeatmap to use when no beatmap is available. /// </summary> public readonly WorkingBeatmap DefaultBeatmap; public BeatmapModelManager BeatmapManager { private get; set; } private readonly AudioManager audioManager; private readonly IResourceStore<byte[]> resources; private readonly LargeTextureStore largeTextureStore; private readonly ITrackStore trackStore; private readonly IResourceStore<byte[]> files; [CanBeNull] private readonly GameHost host; public WorkingBeatmapCache(ITrackStore trackStore, AudioManager audioManager, IResourceStore<byte[]> resources, IResourceStore<byte[]> files, WorkingBeatmap defaultBeatmap = null, GameHost host = null) { DefaultBeatmap = defaultBeatmap; this.audioManager = audioManager; this.resources = resources; this.host = host; this.files = files; largeTextureStore = new LargeTextureStore(host?.CreateTextureLoaderStore(files)); this.trackStore = trackStore; } public void Invalidate(BeatmapSetInfo info) { foreach (var b in info.Beatmaps) Invalidate(b); } public void Invalidate(BeatmapInfo info) { lock (workingCache) { var working = workingCache.FirstOrDefault(w => info.Equals(w.BeatmapInfo)); if (working != null) { Logger.Log($"Invalidating working beatmap cache for {info}"); workingCache.Remove(working); } } } public virtual WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo) { // if there are no files, presume the full beatmap info has not yet been fetched from the database. if (beatmapInfo?.BeatmapSet?.Files.Count == 0) { int lookupId = beatmapInfo.ID; beatmapInfo = BeatmapManager.QueryBeatmap(b => b.ID == lookupId); } if (beatmapInfo?.BeatmapSet == null) return DefaultBeatmap; lock (workingCache) { var working = workingCache.FirstOrDefault(w => beatmapInfo.Equals(w.BeatmapInfo)); if (working != null) return working; beatmapInfo.Metadata ??= beatmapInfo.BeatmapSet.Metadata; workingCache.Add(working = new BeatmapManagerWorkingBeatmap(beatmapInfo, this)); // best effort; may be higher than expected. GlobalStatistics.Get<int>(nameof(Beatmaps), $"Cached {nameof(WorkingBeatmap)}s").Value = workingCache.Count(); return working; } } #region IResourceStorageProvider TextureStore IBeatmapResourceProvider.LargeTextureStore => largeTextureStore; ITrackStore IBeatmapResourceProvider.Tracks => trackStore; AudioManager IStorageResourceProvider.AudioManager => audioManager; IResourceStore<byte[]> IStorageResourceProvider.Files => files; IResourceStore<byte[]> IStorageResourceProvider.Resources => resources; IResourceStore<TextureUpload> IStorageResourceProvider.CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => host?.CreateTextureLoaderStore(underlyingStore); #endregion [ExcludeFromDynamicCompile] private class BeatmapManagerWorkingBeatmap : WorkingBeatmap { [NotNull] private readonly IBeatmapResourceProvider resources; public BeatmapManagerWorkingBeatmap(BeatmapInfo beatmapInfo, [NotNull] IBeatmapResourceProvider resources) : base(beatmapInfo, resources.AudioManager) { this.resources = resources; } protected override IBeatmap GetBeatmap() { if (BeatmapInfo.Path == null) return new Beatmap { BeatmapInfo = BeatmapInfo }; try { using (var stream = new LineBufferedReader(GetStream(BeatmapSetInfo.GetPathForFile(BeatmapInfo.Path)))) return Decoder.GetDecoder<Beatmap>(stream).Decode(stream); } catch (Exception e) { Logger.Error(e, "Beatmap failed to load"); return null; } } protected override bool BackgroundStillValid(Texture b) => false; // bypass lazy logic. we want to return a new background each time for refcounting purposes. protected override Texture GetBackground() { if (string.IsNullOrEmpty(Metadata?.BackgroundFile)) return null; try { return resources.LargeTextureStore.Get(BeatmapSetInfo.GetPathForFile(Metadata.BackgroundFile)); } catch (Exception e) { Logger.Error(e, "Background failed to load"); return null; } } protected override Track GetBeatmapTrack() { if (string.IsNullOrEmpty(Metadata?.AudioFile)) return null; try { return resources.Tracks.Get(BeatmapSetInfo.GetPathForFile(Metadata.AudioFile)); } catch (Exception e) { Logger.Error(e, "Track failed to load"); return null; } } protected override Waveform GetWaveform() { if (string.IsNullOrEmpty(Metadata?.AudioFile)) return null; try { var trackData = GetStream(BeatmapSetInfo.GetPathForFile(Metadata.AudioFile)); return trackData == null ? null : new Waveform(trackData); } catch (Exception e) { Logger.Error(e, "Waveform failed to load"); return null; } } protected override Storyboard GetStoryboard() { Storyboard storyboard; try { using (var stream = new LineBufferedReader(GetStream(BeatmapSetInfo.GetPathForFile(BeatmapInfo.Path)))) { var decoder = Decoder.GetDecoder<Storyboard>(stream); string storyboardFilename = BeatmapSetInfo?.Files.FirstOrDefault(f => f.Filename.EndsWith(".osb", StringComparison.OrdinalIgnoreCase))?.Filename; // todo: support loading from both set-wide storyboard *and* beatmap specific. if (string.IsNullOrEmpty(storyboardFilename)) storyboard = decoder.Decode(stream); else { using (var secondaryStream = new LineBufferedReader(GetStream(BeatmapSetInfo.GetPathForFile(storyboardFilename)))) storyboard = decoder.Decode(stream, secondaryStream); } } } catch (Exception e) { Logger.Error(e, "Storyboard failed to load"); storyboard = new Storyboard(); } storyboard.BeatmapInfo = BeatmapInfo; return storyboard; } protected internal override ISkin GetSkin() { try { return new LegacyBeatmapSkin(BeatmapInfo, resources.Files, resources); } catch (Exception e) { Logger.Error(e, "Skin failed to load"); return null; } } public override Stream GetStream(string storagePath) => resources.Files.GetStream(storagePath); } } }
// Copyright (c) Microsoft. All rights reserved. using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Security.Credentials; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace SDKTemplate { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario9_CustomPairDevice : Page { private MainPage rootPage = MainPage.Current; private DeviceWatcherHelper deviceWatcherHelper; TaskCompletionSource<string> providePinTaskSrc; TaskCompletionSource<bool> confirmPinTaskSrc; TaskCompletionSource<PasswordCredential> providePasswordCredential; private ObservableCollection<DeviceInformationDisplay> resultCollection = new ObservableCollection<DeviceInformationDisplay>(); public Scenario9_CustomPairDevice() { this.InitializeComponent(); deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher); deviceWatcherHelper.DeviceChanged += OnDeviceListChanged; } protected override void OnNavigatedTo(NavigationEventArgs e) { resultsListView.ItemsSource = resultCollection; selectorComboBox.ItemsSource = DeviceSelectorChoices.PairingSelectors; selectorComboBox.SelectedIndex = 0; protectionLevelComboBox.ItemsSource = ProtectionSelectorChoices.Selectors; protectionLevelComboBox.SelectedIndex = 0; } protected override void OnNavigatedFrom(NavigationEventArgs e) { deviceWatcherHelper.Reset(); CompleteProvidePinTask(); // Abandon any previous pin request. CompletePasswordCredential(); // Abandon any previous pin request. CompleteConfirmPinTask(false); // Abandon any previous request. } private void StartWatcherButton_Click(object sender, RoutedEventArgs e) { StartWatcher(); } private void StopWatcherButton_Click(object sender, RoutedEventArgs e) { StopWatcher(); } private void StartWatcher() { startWatcherButton.IsEnabled = false; resultCollection.Clear(); DeviceWatcher deviceWatcher; // Get the device selector chosen by the UI then add additional constraints for devices that // can be paired or are already paired. DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem; string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)"; if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown) { // Kind will be determined by the selector deviceWatcher = DeviceInformation.CreateWatcher( selector, null // don't request additional properties for this sample ); } else { // Kind is specified in the selector info deviceWatcher = DeviceInformation.CreateWatcher( selector, null, // don't request additional properties for this sample deviceSelectorInfo.Kind); } rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage); deviceWatcherHelper.StartWatcher(deviceWatcher); stopWatcherButton.IsEnabled = true; } private void StopWatcher() { stopWatcherButton.IsEnabled = false; deviceWatcherHelper.StopWatcher(); startWatcherButton.IsEnabled = true; } private void OnDeviceListChanged(DeviceWatcher sender, string id) { // If the item being updated is currently "selected", then update the pairing buttons DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem; if ((selectedDeviceInfoDisp != null) && (selectedDeviceInfoDisp.Id == id)) { UpdatePairingButtons(); } } private async void PairButton_Click(object sender, RoutedEventArgs e) { // Gray out the pair button and results view while pairing is in progress. resultsListView.IsEnabled = false; pairButton.IsEnabled = false; rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage); // Get the device selected for pairing DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay; // Get ceremony type and protection level selections DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); ProtectionLevelSelectorInfo protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem; DevicePairingProtectionLevel protectionLevel = protectionLevelInfo.ProtectionLevel; DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom; customPairing.PairingRequested += PairingRequestedHandler; DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel); customPairing.PairingRequested -= PairingRequestedHandler; rootPage.NotifyUser( "Pairing result = " + result.Status.ToString(), result.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage); HidePairingPanel(); UpdatePairingButtons(); resultsListView.IsEnabled = true; } private async void UnpairButton_Click(object sender, RoutedEventArgs e) { // Gray out the unpair button and results view while unpairing is in progress. resultsListView.IsEnabled = false; unpairButton.IsEnabled = false; rootPage.NotifyUser("Unpairing started. Please wait...", NotifyType.StatusMessage); DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay; DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); rootPage.NotifyUser( "Unpairing result = " + dupr.Status.ToString(), dupr.Status == DeviceUnpairingResultStatus.Unpaired ? NotifyType.StatusMessage : NotifyType.ErrorMessage); UpdatePairingButtons(); resultsListView.IsEnabled = true; } private async void PairingRequestedHandler( DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args) { switch (args.PairingKind) { case DevicePairingKinds.ConfirmOnly: // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile // If this is an App for 'Windows IoT Core' where there is no Windows Consent UX, you may want to provide your own confirmation. args.Accept(); break; case DevicePairingKinds.DisplayPin: // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN // on the target device. We automatically accept here since we can't really "cancel" the operation // from this side. args.Accept(); // No need for a deferral since we don't need any decision from the user await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ShowPairingPanel( "Please enter this PIN on the device you are pairing with: " + args.Pin, args.PairingKind); }); break; case DevicePairingKinds.ProvidePin: // A PIN may be shown on the target device and the user needs to enter the matching PIN on // this Windows device. Get a deferral so we can perform the async request to the user. var collectPinDeferral = args.GetDeferral(); await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { string pin = await GetPinFromUserAsync(); if (!string.IsNullOrEmpty(pin)) { args.Accept(pin); } collectPinDeferral.Complete(); }); break; case DevicePairingKinds.ProvidePasswordCredential: var collectCredentialDeferral = args.GetDeferral(); await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { var credential = await GetPasswordCredentialFromUserAsync(); if (credential != null) { args.AcceptWithPasswordCredential(credential); } collectCredentialDeferral.Complete(); }); break; case DevicePairingKinds.ConfirmPinMatch: // We show the PIN here and the user responds with whether the PIN matches what they see // on the target device. Response comes back and we set it on the PinComparePairingRequestedData // then complete the deferral. var displayMessageDeferral = args.GetDeferral(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { bool accept = await GetUserConfirmationAsync(args.Pin); if (accept) { args.Accept(); } displayMessageDeferral.Complete(); }); break; } } private void ShowPairingPanel(string text, DevicePairingKinds pairingKind) { pairingPanel.Visibility = Visibility.Collapsed; pinEntryTextBox.Visibility = Visibility.Collapsed; okButton.Visibility = Visibility.Collapsed; usernameEntryTextBox.Visibility = Visibility.Collapsed; passwordEntryTextBox.Visibility = Visibility.Collapsed; verifyButton.Visibility = Visibility.Collapsed; yesButton.Visibility = Visibility.Collapsed; noButton.Visibility = Visibility.Collapsed; pairingTextBlock.Text = text; switch (pairingKind) { case DevicePairingKinds.ConfirmOnly: case DevicePairingKinds.DisplayPin: // Don't need any buttons break; case DevicePairingKinds.ProvidePin: pinEntryTextBox.Text = ""; pinEntryTextBox.Visibility = Visibility.Visible; okButton.Visibility = Visibility.Visible; break; case DevicePairingKinds.ConfirmPinMatch: yesButton.Visibility = Visibility.Visible; noButton.Visibility = Visibility.Visible; break; case DevicePairingKinds.ProvidePasswordCredential: usernameEntryTextBox.Text = ""; passwordEntryTextBox.Text = ""; passwordEntryTextBox.Visibility = Visibility.Visible; usernameEntryTextBox.Visibility = Visibility.Visible; verifyButton.Visibility = Visibility.Visible; break; } pairingPanel.Visibility = Visibility.Visible; } private void HidePairingPanel() { pairingPanel.Visibility = Visibility.Collapsed; pairingTextBlock.Text = ""; } private async Task<string> GetPinFromUserAsync() { HidePairingPanel(); CompleteProvidePinTask(); // Abandon any previous pin request. ShowPairingPanel( "Please enter the PIN shown on the device you're pairing with", DevicePairingKinds.ProvidePin); providePinTaskSrc = new TaskCompletionSource<string>(); return await providePinTaskSrc.Task; } // If pin is not provided, then any pending pairing request is abandoned. private void CompleteProvidePinTask(string pin = null) { if (providePinTaskSrc != null) { providePinTaskSrc.SetResult(pin); providePinTaskSrc = null; } } private async Task<PasswordCredential> GetPasswordCredentialFromUserAsync() { HidePairingPanel(); CompletePasswordCredential(); // Abandon any previous pin request. ShowPairingPanel( "Please enter the username and password", DevicePairingKinds.ProvidePasswordCredential); providePasswordCredential = new TaskCompletionSource<PasswordCredential>(); return await providePasswordCredential.Task; } private void CompletePasswordCredential(string username = null, string password = null) { if (providePasswordCredential != null) { if (String.IsNullOrEmpty(username)) { providePasswordCredential.SetResult(null); } else { providePasswordCredential.SetResult(new PasswordCredential() { UserName = username, Password = password }); } providePasswordCredential = null; } } private async Task<bool> GetUserConfirmationAsync(string pin) { HidePairingPanel(); CompleteConfirmPinTask(false); // Abandon any previous request. ShowPairingPanel( "Does the following PIN match the one shown on the device you are pairing?: " + pin, DevicePairingKinds.ConfirmPinMatch); confirmPinTaskSrc = new TaskCompletionSource<bool>(); return await confirmPinTaskSrc.Task; } // If pin is not provided, then any pending pairing request is abandoned. private void CompleteConfirmPinTask(bool accept) { if (confirmPinTaskSrc != null) { confirmPinTaskSrc.SetResult(accept); confirmPinTaskSrc = null; } } private void okButton_Click(object sender, RoutedEventArgs e) { // OK button is only used for the ProvidePin scenario CompleteProvidePinTask(pinEntryTextBox.Text); HidePairingPanel(); } private void verifyButton_Click(object sender, RoutedEventArgs e) { // verify button is only used for the ProvidePin scenario CompletePasswordCredential(usernameEntryTextBox.Text, passwordEntryTextBox.Text); HidePairingPanel(); } private void yesButton_Click(object sender, RoutedEventArgs e) { CompleteConfirmPinTask(true); HidePairingPanel(); } private void noButton_Click(object sender, RoutedEventArgs e) { CompleteConfirmPinTask(false); HidePairingPanel(); } private DevicePairingKinds GetSelectedCeremonies() { DevicePairingKinds ceremonySelection = DevicePairingKinds.None; if (confirmOnlyOption.IsChecked.Value) ceremonySelection |= DevicePairingKinds.ConfirmOnly; if (displayPinOption.IsChecked.Value) ceremonySelection |= DevicePairingKinds.DisplayPin; if (providePinOption.IsChecked.Value) ceremonySelection |= DevicePairingKinds.ProvidePin; if (confirmPinMatchOption.IsChecked.Value) ceremonySelection |= DevicePairingKinds.ConfirmPinMatch; if (passwordCredentialOption.IsChecked.Value) ceremonySelection |= DevicePairingKinds.ProvidePasswordCredential; return ceremonySelection; } private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { UpdatePairingButtons(); } private void UpdatePairingButtons() { DeviceInformationDisplay deviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem; if (null != deviceInfoDisp && deviceInfoDisp.DeviceInformation.Pairing.CanPair && !deviceInfoDisp.DeviceInformation.Pairing.IsPaired) { pairButton.IsEnabled = true; } else { pairButton.IsEnabled = false; } if (null != deviceInfoDisp && deviceInfoDisp.DeviceInformation.Pairing.IsPaired) { unpairButton.IsEnabled = true; } else { unpairButton.IsEnabled = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Debug = System.Diagnostics.Debug; namespace System.Xml.Linq { internal class XNodeReader : XmlReader, IXmlLineInfo { private static readonly char[] s_WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; // The reader position is encoded by the tuple (source, parent). // Lazy text uses (instance, parent element). Attribute value // uses (instance, parent attribute). End element uses (instance, // instance). Common XObject uses (instance, null). private object _source; private object _parent; private ReadState _state; private XNode _root; private XmlNameTable _nameTable; private bool _omitDuplicateNamespaces; internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options) { _source = node; _root = node; _nameTable = nameTable != null ? nameTable : CreateNameTable(); _omitDuplicateNamespaces = (options & ReaderOptions.OmitDuplicateNamespaces) != 0 ? true : false; } internal XNodeReader(XNode node, XmlNameTable nameTable) : this(node, nameTable, (node.GetSaveOptionsFromAnnotations() & SaveOptions.OmitDuplicateNamespaces) != 0 ? ReaderOptions.OmitDuplicateNamespaces : ReaderOptions.None) { } public override int AttributeCount { get { if (!IsInteractive) { return 0; } int count = 0; XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { count++; } } while (a != e.lastAttr); } } return count; } } public override string BaseURI { get { XObject o = _source as XObject; if (o != null) { return o.BaseUri; } o = _parent as XObject; if (o != null) { return o.BaseUri; } return string.Empty; } } public override int Depth { get { if (!IsInteractive) { return 0; } XObject o = _source as XObject; if (o != null) { return GetDepth(o); } o = _parent as XObject; if (o != null) { return GetDepth(o) + 1; } return 0; } } private static int GetDepth(XObject o) { int depth = 0; while (o.parent != null) { depth++; o = o.parent; } if (o is XDocument) { depth--; } return depth; } public override bool EOF { get { return _state == ReadState.EndOfFile; } } public override bool HasAttributes { get { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null && e.lastAttr != null) { if (_omitDuplicateNamespaces) { return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next) != null; } else { return true; } } else { return false; } } } public override bool HasValue { get { if (!IsInteractive) { return false; } XObject o = _source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: return true; default: return false; } } return true; } } public override bool IsEmptyElement { get { if (!IsInteractive) { return false; } XElement e = _source as XElement; return e != null && e.IsEmpty; } } public override string LocalName { get { return _nameTable.Add(GetLocalName()); } } private string GetLocalName() { if (!IsInteractive) { return string.Empty; } XElement e = _source as XElement; if (e != null) { return e.Name.LocalName; } XAttribute a = _source as XAttribute; if (a != null) { return a.Name.LocalName; } XProcessingInstruction p = _source as XProcessingInstruction; if (p != null) { return p.Target; } XDocumentType n = _source as XDocumentType; if (n != null) { return n.Name; } return string.Empty; } public override string Name { get { string prefix = GetPrefix(); if (prefix.Length == 0) { return _nameTable.Add(GetLocalName()); } return _nameTable.Add(string.Concat(prefix, ":", GetLocalName())); } } public override string NamespaceURI { get { return _nameTable.Add(GetNamespaceURI()); } } private string GetNamespaceURI() { if (!IsInteractive) { return string.Empty; } XElement e = _source as XElement; if (e != null) { return e.Name.NamespaceName; } XAttribute a = _source as XAttribute; if (a != null) { string namespaceName = a.Name.NamespaceName; if (namespaceName.Length == 0 && a.Name.LocalName == "xmlns") { return XNamespace.xmlnsPrefixNamespace; } return namespaceName; } return string.Empty; } public override XmlNameTable NameTable { get { return _nameTable; } } public override XmlNodeType NodeType { get { if (!IsInteractive) { return XmlNodeType.None; } XObject o = _source as XObject; if (o != null) { if (IsEndElement) { return XmlNodeType.EndElement; } XmlNodeType nt = o.NodeType; if (nt != XmlNodeType.Text) { return nt; } if (o.parent != null && o.parent.parent == null && o.parent is XDocument) { return XmlNodeType.Whitespace; } return XmlNodeType.Text; } if (_parent is XDocument) { return XmlNodeType.Whitespace; } return XmlNodeType.Text; } } public override string Prefix { get { return _nameTable.Add(GetPrefix()); } } private string GetPrefix() { if (!IsInteractive) { return string.Empty; } XElement e = _source as XElement; if (e != null) { string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } XAttribute a = _source as XAttribute; if (a != null) { string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; } } return string.Empty; } public override ReadState ReadState { get { return _state; } } public override XmlReaderSettings Settings { get { XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = false; return settings; } } public override string Value { get { if (!IsInteractive) { return string.Empty; } XObject o = _source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Attribute: return ((XAttribute)o).Value; case XmlNodeType.Text: case XmlNodeType.CDATA: return ((XText)o).Value; case XmlNodeType.Comment: return ((XComment)o).Value; case XmlNodeType.ProcessingInstruction: return ((XProcessingInstruction)o).Data; case XmlNodeType.DocumentType: return ((XDocumentType)o).InternalSubset; default: return string.Empty; } } return (string)_source; } } public override string XmlLang { get { if (!IsInteractive) { return string.Empty; } XElement e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("lang"); do { XAttribute a = e.Attribute(name); if (a != null) { return a.Value; } e = e.parent as XElement; } while (e != null); } return string.Empty; } } public override XmlSpace XmlSpace { get { if (!IsInteractive) { return XmlSpace.None; } XElement e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("space"); do { XAttribute a = e.Attribute(name); if (a != null) { switch (a.Value.Trim(s_WhitespaceChars)) { case "preserve": return XmlSpace.Preserve; case "default": return XmlSpace.Default; default: break; } } e = e.parent as XElement; } while (e != null); } return XmlSpace.None; } } protected override void Dispose(bool disposing) { if (disposing && ReadState != ReadState.Closed) { Close(); } } public override void Close() { _source = null; _parent = null; _root = null; _state = ReadState.Closed; } public override string GetAttribute(string name) { if (!IsInteractive) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { string localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { return null; } else { return a.Value; } } } while (a != e.lastAttr); } return null; } XDocumentType n = _source as XDocumentType; if (n != null) { switch (name) { case "PUBLIC": return n.PublicId; case "SYSTEM": return n.SystemId; } } return null; } public override string GetAttribute(string localName, string namespaceName) { if (!IsInteractive) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") { if (namespaceName != null && namespaceName.Length == 0) { return null; } if (namespaceName == XNamespace.xmlnsPrefixNamespace) { namespaceName = string.Empty; } } XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { return null; } else { return a.Value; } } } while (a != e.lastAttr); } } return null; } public override string GetAttribute(int index) { if (!IsInteractive) { return null; } if (index < 0) { return null; } XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { if (index-- == 0) { return a.Value; } } } while (a != e.lastAttr); } } return null; } public override string LookupNamespace(string prefix) { if (!IsInteractive) { return null; } if (prefix == null) { return null; } XElement e = GetElementInScope(); if (e != null) { XNamespace ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix); if (ns != null) { return _nameTable.Add(ns.NamespaceName); } } return null; } public override bool MoveToAttribute(string name) { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { string localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { // If it's a duplicate namespace attribute just act as if it doesn't exist return false; } else { _source = a; _parent = null; return true; } } } while (a != e.lastAttr); } } return false; } public override bool MoveToAttribute(string localName, string namespaceName) { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") { if (namespaceName != null && namespaceName.Length == 0) { return false; } if (namespaceName == XNamespace.xmlnsPrefixNamespace) { namespaceName = string.Empty; } } XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) { // If it's a duplicate namespace attribute just act as if it doesn't exist return false; } else { _source = a; _parent = null; return true; } } } while (a != e.lastAttr); } } return false; } public override void MoveToAttribute(int index) { if (!IsInteractive) { return; } if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); XElement e = GetElementInAttributeScope(); if (e != null) { XAttribute a = e.lastAttr; if (a != null) { do { a = a.next; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { // Only count those which are non-duplicates if we're asked to if (index-- == 0) { _source = a; _parent = null; return; } } } while (a != e.lastAttr); } } throw new ArgumentOutOfRangeException(nameof(index)); } public override bool MoveToElement() { if (!IsInteractive) { return false; } XAttribute a = _source as XAttribute; if (a == null) { a = _parent as XAttribute; } if (a != null) { if (a.parent != null) { _source = a.parent; _parent = null; return true; } } return false; } public override bool MoveToFirstAttribute() { if (!IsInteractive) { return false; } XElement e = GetElementInAttributeScope(); if (e != null) { if (e.lastAttr != null) { if (_omitDuplicateNamespaces) { object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); if (na == null) { return false; } _source = na; } else { _source = e.lastAttr.next; } return true; } } return false; } public override bool MoveToNextAttribute() { if (!IsInteractive) { return false; } XElement e = _source as XElement; if (e != null) { if (IsEndElement) { return false; } if (e.lastAttr != null) { if (_omitDuplicateNamespaces) { // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); if (na == null) { return false; } _source = na; } else { _source = e.lastAttr.next; } return true; } return false; } XAttribute a = _source as XAttribute; if (a == null) { a = _parent as XAttribute; } if (a != null) { if (a.parent != null && ((XElement)a.parent).lastAttr != a) { if (_omitDuplicateNamespaces) { // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now object na = GetFirstNonDuplicateNamespaceAttribute(a.next); if (na == null) { return false; } _source = na; } else { _source = a.next; } _parent = null; return true; } } return false; } public override bool Read() { switch (_state) { case ReadState.Initial: _state = ReadState.Interactive; XDocument d = _source as XDocument; if (d != null) { return ReadIntoDocument(d); } return true; case ReadState.Interactive: return Read(false); default: return false; } } public override bool ReadAttributeValue() { if (!IsInteractive) { return false; } XAttribute a = _source as XAttribute; if (a != null) { return ReadIntoAttribute(a); } return false; } public override bool ReadToDescendant(string localName, string namespaceName) { if (!IsInteractive) { return false; } MoveToElement(); XElement c = _source as XElement; if (c != null && !c.IsEmpty) { if (IsEndElement) { return false; } foreach (XElement e in c.Descendants()) { if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { _source = e; return true; } } IsEndElement = true; } return false; } public override bool ReadToFollowing(string localName, string namespaceName) { while (Read()) { XElement e = _source as XElement; if (e != null) { if (IsEndElement) continue; if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { return true; } } } return false; } public override bool ReadToNextSibling(string localName, string namespaceName) { if (!IsInteractive) { return false; } MoveToElement(); if (_source != _root) { XNode n = _source as XNode; if (n != null) { foreach (XElement e in n.ElementsAfterSelf()) { if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { _source = e; IsEndElement = false; return true; } } if (n.parent is XElement) { _source = n.parent; IsEndElement = true; return false; } } else { if (_parent is XElement) { _source = _parent; _parent = null; IsEndElement = true; return false; } } } return ReadToEnd(); } public override void ResolveEntity() { } public override void Skip() { if (!IsInteractive) { return; } Read(true); } bool IXmlLineInfo.HasLineInfo() { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = _source as XElement; if (e != null) { return e.Annotation<LineInfoEndElementAnnotation>() != null; } } else { IXmlLineInfo li = _source as IXmlLineInfo; if (li != null) { return li.HasLineInfo(); } } return false; } int IXmlLineInfo.LineNumber { get { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = _source as XElement; if (e != null) { LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>(); if (a != null) { return a.lineNumber; } } } else { IXmlLineInfo li = _source as IXmlLineInfo; if (li != null) { return li.LineNumber; } } return 0; } } int IXmlLineInfo.LinePosition { get { if (IsEndElement) { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement XElement e = _source as XElement; if (e != null) { LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>(); if (a != null) { return a.linePosition; } } } else { IXmlLineInfo li = _source as IXmlLineInfo; if (li != null) { return li.LinePosition; } } return 0; } } private bool IsEndElement { get { return _parent == _source; } set { _parent = value ? _source : null; } } private bool IsInteractive { get { return _state == ReadState.Interactive; } } private static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(XNamespace.xmlnsPrefixNamespace); nameTable.Add(XNamespace.xmlPrefixNamespace); return nameTable; } private XElement GetElementInAttributeScope() { XElement e = _source as XElement; if (e != null) { if (IsEndElement) { return null; } return e; } XAttribute a = _source as XAttribute; if (a != null) { return (XElement)a.parent; } a = _parent as XAttribute; if (a != null) { return (XElement)a.parent; } return null; } private XElement GetElementInScope() { XElement e = _source as XElement; if (e != null) { return e; } XNode n = _source as XNode; if (n != null) { return n.parent as XElement; } XAttribute a = _source as XAttribute; if (a != null) { return (XElement)a.parent; } e = _parent as XElement; if (e != null) { return e; } a = _parent as XAttribute; if (a != null) { return (XElement)a.parent; } return null; } private static void GetNameInAttributeScope(string qualifiedName, XElement e, out string localName, out string namespaceName) { if (!string.IsNullOrEmpty(qualifiedName)) { int i = qualifiedName.IndexOf(':'); if (i != 0 && i != qualifiedName.Length - 1) { if (i == -1) { localName = qualifiedName; namespaceName = string.Empty; return; } XNamespace ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i)); if (ns != null) { localName = qualifiedName.Substring(i + 1, qualifiedName.Length - i - 1); namespaceName = ns.NamespaceName; return; } } } localName = null; namespaceName = null; } private bool Read(bool skipContent) { XElement e = _source as XElement; if (e != null) { if (e.IsEmpty || IsEndElement || skipContent) { return ReadOverNode(e); } return ReadIntoElement(e); } XNode n = _source as XNode; if (n != null) { return ReadOverNode(n); } XAttribute a = _source as XAttribute; if (a != null) { return ReadOverAttribute(a, skipContent); } return ReadOverText(skipContent); } private bool ReadIntoDocument(XDocument d) { XNode n = d.content as XNode; if (n != null) { _source = n.next; return true; } string s = d.content as string; if (s != null) { if (s.Length > 0) { _source = s; _parent = d; return true; } } return ReadToEnd(); } private bool ReadIntoElement(XElement e) { XNode n = e.content as XNode; if (n != null) { _source = n.next; return true; } string s = e.content as string; if (s != null) { if (s.Length > 0) { _source = s; _parent = e; } else { _source = e; IsEndElement = true; } return true; } return ReadToEnd(); } private bool ReadIntoAttribute(XAttribute a) { _source = a.value; _parent = a; return true; } private bool ReadOverAttribute(XAttribute a, bool skipContent) { XElement e = (XElement)a.parent; if (e != null) { if (e.IsEmpty || skipContent) { return ReadOverNode(e); } return ReadIntoElement(e); } return ReadToEnd(); } private bool ReadOverNode(XNode n) { if (n == _root) { return ReadToEnd(); } XNode next = n.next; if (null == next || next == n || n == n.parent.content) { if (n.parent == null || (n.parent.parent == null && n.parent is XDocument)) { return ReadToEnd(); } _source = n.parent; IsEndElement = true; } else { _source = next; IsEndElement = false; } return true; } private bool ReadOverText(bool skipContent) { if (_parent is XElement) { _source = _parent; _parent = null; IsEndElement = true; return true; } XAttribute parent = _parent as XAttribute; if (parent != null) { _parent = null; return ReadOverAttribute(parent, skipContent); } return ReadToEnd(); } private bool ReadToEnd() { _state = ReadState.EndOfFile; return false; } /// <summary> /// Determines if the specified attribute would be a duplicate namespace declaration /// - one which we already reported on some ancestor, so it's not necessary to report it here /// </summary> /// <param name="candidateAttribute">The attribute to test.</param> /// <returns>true if the attribute is a duplicate namespace declaration attribute</returns> private bool IsDuplicateNamespaceAttribute(XAttribute candidateAttribute) { if (!candidateAttribute.IsNamespaceDeclaration) { return false; } else { // Split the method in two to enable inlining of this piece (Which will work for 95% of cases) return IsDuplicateNamespaceAttributeInner(candidateAttribute); } } private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) { // First of all - if this is an xmlns:xml declaration then it's a duplicate // since xml prefix can't be redeclared and it's declared by default always. if (candidateAttribute.Name.LocalName == "xml") { return true; } // The algorithm we use is: // Go up the tree (but don't go higher than the root of this reader) // and find the closest namespace declaration attribute which declares the same prefix // If it declares that prefix to the exact same URI as ours does then ours is a duplicate // Note that if we find a namespace declaration for the same prefix but with a different URI, then we don't have a dupe! XElement element = candidateAttribute.parent as XElement; if (element == _root || element == null) { // If there's only the parent element of our attribute, there can be no duplicates return false; } element = element.parent as XElement; while (element != null) { // Search all attributes of this element for the same prefix declaration // Trick - a declaration for the same prefix will have the exact same XName - so we can do a quick ref comparison of names // (The default ns decl is represented by an XName "xmlns{}", even if you try to create // an attribute with XName "xmlns{http://www.w3.org/2000/xmlns/}" it will fail, // because it's treated as a declaration of prefix "xmlns" which is invalid) XAttribute a = element.lastAttr; if (a != null) { do { if (a.name == candidateAttribute.name) { // Found the same prefix decl if (a.Value == candidateAttribute.Value) { // And it's for the same namespace URI as well - so ours is a duplicate return true; } else { // It's not for the same namespace URI - which means we have to keep ours // (no need to continue the search as this one overrides anything above it) return false; } } a = a.next; } while (a != element.lastAttr); } if (element == _root) { return false; } element = element.parent as XElement; } return false; } /// <summary> /// Finds a first attribute (starting with the parameter) which is not a duplicate namespace attribute /// </summary> /// <param name="candidate">The attribute to start with</param> /// <returns>The first attribute which is not a namespace attribute or null if the end of attributes has bean reached</returns> private XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) { Debug.Assert(_omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute." + "For perf reason it's better to test this flag in the caller method."); if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; } XElement e = candidate.parent as XElement; if (e != null && candidate != e.lastAttr) { do { candidate = candidate.next; if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; } } while (candidate != e.lastAttr); } return null; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPOSlist { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPOSlist() : base() { FormClosed += frmPOSlist_FormClosed; Load += frmPOSlist_Load; KeyPress += frmPOSlist_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdNew; public System.Windows.Forms.Button cmdNew { get { return withEventsField_cmdNew; } set { if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click -= cmdNew_Click; } withEventsField_cmdNew = value; if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click += cmdNew_Click; } } } private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Label lbl; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPOSlist)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.cmdNew = new System.Windows.Forms.Button(); this.DataList1 = new myDataGridView(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdExit = new System.Windows.Forms.Button(); this.lbl = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a Point Of Sale"; this.ClientSize = new System.Drawing.Size(259, 433); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPOSlist"; this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNew.Text = "&New"; this.cmdNew.Size = new System.Drawing.Size(97, 52); this.cmdNew.Location = new System.Drawing.Point(8, 375); this.cmdNew.TabIndex = 4; this.cmdNew.TabStop = false; this.cmdNew.BackColor = System.Drawing.SystemColors.Control; this.cmdNew.CausesValidation = true; this.cmdNew.Enabled = true; this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNew.Name = "cmdNew"; //'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(244, 342); this.DataList1.Location = new System.Drawing.Point(6, 27); this.DataList1.TabIndex = 2; this.DataList1.Name = "DataList1"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(199, 19); this.txtSearch.Location = new System.Drawing.Point(51, 3); this.txtSearch.TabIndex = 1; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(153, 375); this.cmdExit.TabIndex = 3; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 6); this.lbl.TabIndex = 0; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.Controls.Add(cmdNew); this.Controls.Add(DataList1); this.Controls.Add(txtSearch); this.Controls.Add(cmdExit); this.Controls.Add(lbl); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ProjectTracker.Library; using Csla.Security; namespace PTWin { public partial class MainForm : Form { public MainForm() { InitializeComponent(); _main = this; } private static MainForm _main; internal static MainForm Instance { get { return _main; } } private async void MainForm_Load(object sender, EventArgs e) { if (Csla.ApplicationContext.AuthenticationType == "Windows") { AppDomain.CurrentDomain.SetPrincipalPolicy( System.Security.Principal.PrincipalPolicy.WindowsPrincipal); ApplyAuthorizationRules(); } else { DoLogin(); } if (DocumentCount == 0) DocumentsToolStripDropDownButton.Enabled = false; // initialize cache of role list await RoleList.CacheListAsync(); } #region Projects private void NewProjectToolStripMenuItem_Click( object sender, EventArgs e) { using (StatusBusy busy = new StatusBusy("Creating project...")) { AddWinPart(new ProjectEdit(ProjectTracker.Library.ProjectEdit.NewProject())); } } private void EditProjectToolStripMenuItem_Click( object sender, EventArgs e) { using (ProjectSelect dlg = new ProjectSelect()) { dlg.Text = "Edit Project"; if (dlg.ShowDialog() == DialogResult.OK) { ShowEditProject(dlg.ProjectId); } } } public void ShowEditProject(int projectId) { // see if this project is already loaded foreach (Control ctl in Panel1.Controls) { if (ctl is ProjectEdit) { ProjectEdit part = (ProjectEdit)ctl; if (part.Project.Id.Equals(projectId)) { // project already loaded so just // display the existing winpart ShowWinPart(part); return; } } } // the project wasn't already loaded // so load it and display the new winpart using (StatusBusy busy = new StatusBusy("Loading project...")) { try { AddWinPart(new ProjectEdit(ProjectTracker.Library.ProjectEdit.GetProject(projectId))); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } private void DeleteProjectToolStripMenuItem_Click(object sender, EventArgs e) { ProjectSelect dlg = new ProjectSelect(); dlg.Text = "Delete Project"; if (dlg.ShowDialog() == DialogResult.OK) { // get the project id var projectId = dlg.ProjectId; if (MessageBox.Show("Are you sure?", "Delete project", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { using (StatusBusy busy = new StatusBusy("Deleting project...")) { try { ProjectTracker.Library.ProjectEdit.DeleteProject(projectId); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } } #endregion #region Resources private void NewResourceToolStripMenuItem_Click(object sender, EventArgs e) { using (StatusBusy busy = new StatusBusy("Creating resource...")) { AddWinPart(new ResourceEdit(ProjectTracker.Library.ResourceEdit.NewResourceEdit())); } } private void EditResourceToolStripMenuItem_Click( object sender, EventArgs e) { ResourceSelect dlg = new ResourceSelect(); dlg.Text = "Edit Resource"; if (dlg.ShowDialog() == DialogResult.OK) { // get the resource id ShowEditResource(dlg.ResourceId); } } public void ShowEditResource(int resourceId) { // see if this resource is already loaded foreach (Control ctl in Panel1.Controls) { if (ctl is ResourceEdit) { ResourceEdit part = (ResourceEdit)ctl; if (part.Resource.Id.Equals(resourceId)) { // resource already loaded so just // display the existing winpart ShowWinPart(part); return; } } } // the resource wasn't already loaded // so load it and display the new winpart using (StatusBusy busy = new StatusBusy("Loading resource...")) { try { AddWinPart(new ResourceEdit(ProjectTracker.Library.ResourceEdit.GetResourceEdit(resourceId))); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } private void DeleteResourceToolStripMenuItem_Click( object sender, EventArgs e) { ResourceSelect dlg = new ResourceSelect(); dlg.Text = "Delete Resource"; if (dlg.ShowDialog() == DialogResult.OK) { // get the resource id int resourceId = dlg.ResourceId; if (MessageBox.Show("Are you sure?", "Delete resource", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { using (StatusBusy busy = new StatusBusy("Deleting resource...")) { try { ProjectTracker.Library.ResourceEdit.DeleteResourceEdit(resourceId); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error deleting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } } #endregion #region Roles private void EditRolesToolStripMenuItem_Click( object sender, EventArgs e) { // see if this form is already loaded foreach (Control ctl in Panel1.Controls) { if (ctl is RolesEdit) { ShowWinPart((WinPart)ctl); return; } } // it wasn't already loaded, so show it. AddWinPart(new RolesEdit()); } #endregion #region ApplyAuthorizationRules private void ApplyAuthorizationRules() { // Project menu this.NewProjectToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectTracker.Library.ProjectEdit)); this.EditProjectToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ProjectEdit)); if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ProjectEdit))) this.EditProjectToolStripMenuItem.Text = "Edit project"; else this.EditProjectToolStripMenuItem.Text = "View project"; this.DeleteProjectToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectTracker.Library.ProjectEdit)); // Resource menu this.NewResourceToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(ProjectTracker.Library.ResourceEdit)); this.EditResourceToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(ProjectTracker.Library.ResourceEdit)); if (Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ResourceEdit))) this.EditResourceToolStripMenuItem.Text = "Edit resource"; else this.EditResourceToolStripMenuItem.Text = "View resource"; this.DeleteResourceToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(ProjectTracker.Library.ResourceEdit)); // Admin menu this.EditRolesToolStripMenuItem.Enabled = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.Admin.RoleEditBindingList)); } #endregion #region Login/Logout private void LoginToolStripButton_Click( object sender, EventArgs e) { DoLogin(); } private void DoLogin() { ProjectTracker.Library.Security.PTPrincipal.Logout(); if (this.LoginToolStripButton.Text == "Login") { LoginForm loginForm = new LoginForm(); loginForm.ShowDialog(this); } System.Security.Principal.IPrincipal user = Csla.ApplicationContext.User; if (user.Identity.IsAuthenticated) { this.LoginToolStripLabel.Text = "Logged in as " + user.Identity.Name; this.LoginToolStripButton.Text = "Logout"; } else { this.LoginToolStripLabel.Text = "Not logged in"; this.LoginToolStripButton.Text = "Login"; } // reset menus, etc. ApplyAuthorizationRules(); // notify all documents List<object> tmpList = new List<object>(); foreach (var ctl in Panel1.Controls) tmpList.Add(ctl); foreach (var ctl in tmpList) if (ctl is WinPart) ((WinPart)ctl).OnCurrentPrincipalChanged(this, EventArgs.Empty); } #endregion #region WinPart handling /// <summary> /// Add a new WinPart control to the /// list of available documents and /// make it the active WinPart. /// </summary> /// <param name="part">The WinPart control to add and display.</param> private void AddWinPart(WinPart part) { part.CloseWinPart += new EventHandler(CloseWinPart); part.BackColor = toolStrip1.BackColor; Panel1.Controls.Add(part); this.DocumentsToolStripDropDownButton.Enabled = true; ShowWinPart(part); } /// <summary> /// Make the specified WinPart the /// active, displayed control. /// </summary> /// <param name="part">The WinPart control to display.</param> private void ShowWinPart(WinPart part) { part.Dock = DockStyle.Fill; part.Visible = true; part.BringToFront(); this.Text = "Project Tracker - " + part.ToString(); PopulateDocuments(); } /// <summary> /// Populate the Documents dropdown list. /// </summary> private void DocumentsToolStripDropDownButton_DropDownOpening( object sender, EventArgs e) { PopulateDocuments(); } /// <summary> /// Populate the Documents dropdown list. /// </summary> private void PopulateDocuments() { ToolStripItemCollection items = DocumentsToolStripDropDownButton.DropDownItems; foreach (ToolStripItem item in items) item.Click -= new EventHandler(DocumentClick); items.Clear(); foreach (Control ctl in Panel1.Controls) if (ctl is WinPart) { ToolStripItem item = new ToolStripMenuItem(); item.Text = ((WinPart)ctl).ToString(); item.Tag = ctl; item.Click += new EventHandler(DocumentClick); items.Add(item); } } /// <summary> /// Make selected WinPart the active control. /// </summary> private void DocumentClick(object sender, EventArgs e) { WinPart ctl = (WinPart)((ToolStripItem)sender).Tag; ShowWinPart(ctl); } /// <summary> /// Gets a count of the number of loaded /// documents. /// </summary> public int DocumentCount { get { int count = 0; foreach (Control ctl in Panel1.Controls) if (ctl is WinPart) count++; return count; } } /// <summary> /// Handles event from WinPart when that /// WinPart is closing. /// </summary> private void CloseWinPart(object sender, EventArgs e) { WinPart part = (WinPart)sender; part.CloseWinPart -= new EventHandler(CloseWinPart); part.Visible = false; Panel1.Controls.Remove(part); part.Dispose(); PopulateDocuments(); if (DocumentCount == 0) { this.DocumentsToolStripDropDownButton.Enabled = false; this.Text = "Project Tracker"; } else { // Find the first WinPart control and set // the main form's Text property accordingly. // This works because the first WinPart // is the active one. foreach (Control ctl in Panel1.Controls) { if (ctl is WinPart) { this.Text = "Project Tracker - " + ((WinPart)ctl).ToString(); break; } } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using MemberListType = System.RuntimeType.MemberListType; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.CompilerServices; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodInfo : MethodBase, _MethodInfo { #region Constructor protected MethodInfo() { } #endregion public static bool operator ==(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeMethodInfo || right is RuntimeMethodInfo) { return false; } return left.Equals(right); } public static bool operator !=(MethodInfo left, MethodInfo right) { return !(left == right); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } } #endregion #region Public Abstract\Virtual Members public virtual Type ReturnType { get { throw new NotImplementedException(); } } public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } } public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; } public abstract MethodInfo GetBaseDefinition(); [System.Runtime.InteropServices.ComVisible(true)] public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } [System.Runtime.InteropServices.ComVisible(true)] public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } #endregion #if !FEATURE_CORECLR Type _MethodInfo.GetType() { return base.GetType(); } void _MethodInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members private IntPtr m_handle; private RuntimeTypeCache m_reflectedTypeCache; private string m_name; private string m_toString; private ParameterInfo[] m_parameters; private ParameterInfo m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; private Signature m_signature; private RuntimeType m_declaringType; private object m_keepalive; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (m_declaringType.IsArray && IsPublic && !IsStatic) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; if (IsGenericMethod && !IsGenericMethodDefinition) { foreach (Type t in GetGenericArguments()) { if (((RuntimeType)t).IsNonW8PFrameworkAPI()) return true; } } return false; } internal override bool IsDynamicallyInvokable { get { return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI(); } } #endif internal INVOCATION_FLAGS InvocationFlags { [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if (ContainsGenericParameters || ReturnType.IsByRef || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0) { if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || (declaringType != null && declaringType.NeedsReflectionSecurityCheck) ) { // If method is non-public, or declaring type is not visible invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; } else if (IsGenericMethod) { Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].NeedsReflectionSecurityCheck) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; break; } } } } } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { Contract.Ensures(!m_handle.IsNull()); Contract.Assert(!handle.IsNullHandle()); Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_keepalive = keepalive; m_handle = handle.Value; m_reflectedTypeCache = reflectedTypeCache; m_methodAttributes = methodAttributes; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingMethodCachedData m_cachedData; internal RemotingMethodCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingMethodCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingMethodCachedData(this); RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } [System.Security.SecurityCritical] // auto-generated private ParameterInfo[] FetchNonReturnParameters() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } [System.Security.SecurityCritical] // auto-generated private ParameterInfo FetchReturnParameter() { if (m_returnParameter == null) m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); return m_returnParameter; } #endregion #region Internal Members internal override string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; if (IsGenericMethod) sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeMethodInfo m = o as RuntimeMethodInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } internal Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types internal RuntimeMethodHandle GetMethodHandle() { return new RuntimeMethodHandle(this); } [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeMethodInfo GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) return null; RuntimeType parent = (RuntimeType)m_declaringType.BaseType; if (parent == null) return null; int slot = RuntimeMethodHandle.GetSlot(this); if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) return null; return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); } // Unlike DeclaringType, this will return a valid type even for global methods internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } #endregion #region Object Overrides public override String ToString() { if (m_toString == null) m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); return m_toString; } public override int GetHashCode() { // See RuntimeMethodInfo.Equals() below. if (IsGenericMethod) return ValueType.GetHashCodeOfPtr(m_handle); else return base.GetHashCode(); } [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(object obj) { if (!IsGenericMethod) return obj == (object)this; // We cannot do simple object identity comparisons for generic methods. // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. RuntimeMethodInfo mi = obj as RuntimeMethodInfo; if (mi == null || !mi.IsGenericMethod) return false; // now we know that both operands are generic methods IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); if (handle1.Value.Value != handle2.Value.Value) return false; Type[] lhs = GetGenericArguments(); Type[] rhs = mi.GetGenericArguments(); if (lhs.Length != rhs.Length) return false; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != rhs[i]) return false; } if (DeclaringType != mi.DeclaringType) return false; if (ReflectedType != mi.ReflectedType) return false; return true; } #endregion #region ICustomAttributeProvider [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); } [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeMethodHandle.GetName(this); return m_name; } } public override Type DeclaringType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_declaringType; } } public override Type ReflectedType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_reflectedTypeCache.GetRuntimeType(); } } public override MemberTypes MemberType { get { return MemberTypes.Method; } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } public override bool IsSecurityCritical { get { return RuntimeMethodHandle.IsSecurityCritical(this); } } public override bool IsSecuritySafeCritical { get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } } public override bool IsSecurityTransparent { get { return RuntimeMethodHandle.IsSecurityTransparent(this); } } #endregion #region MethodBase Overrides [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { FetchNonReturnParameters(); return m_parameters; } [System.Security.SecuritySafeCritical] // auto-generated [System.Diagnostics.Contracts.Pure] public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); if (m_parameters.Length == 0) return m_parameters; ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; Array.Copy(m_parameters, ret, m_parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } internal bool IsOverloaded { get { return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1; } } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } [System.Security.SecuritySafeCritical] // overrides SafeCritical member #if !FEATURE_CORECLR #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 #endif public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } #endregion #region Invocation Logic(On MemberBase) private void CheckConsistency(Object target) { // only test instance methods if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); else throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); } } } [System.Security.SecuritySafeCritical] private void ThrowNoInvokeException() { // method is ReflectionOnly Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) { throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); } // method is on a class that contains stack pointers else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam")); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } // ByRef return are not allowed in reflection else if (ReturnType.IsByRef) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn")); } throw new TargetException(); } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); #region Security Check INVOCATION_FLAGS invocationFlags = InvocationFlags; #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif #if !FEATURE_CORECLR if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) { if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } #endif // !FEATURE_CORECLR #endregion return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) { if (arguments == null || arguments.Length == 0) return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false); else { Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; INVOCATION_FLAGS invocationFlags = InvocationFlags; // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); if (actualCount != 0) return CheckArguments(parameters, binder, invokeAttr, culture, sig); else return null; } #endregion #region MethodInfo Overrides public override Type ReturnType { get { return Signature.ReturnType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return ReturnParameter; } } public override ParameterInfo ReturnParameter { [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(m_returnParameter != null); FetchReturnParameter(); return m_returnParameter as ParameterInfo; } } [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) return this; int slot = RuntimeMethodHandle.GetSlot(this); RuntimeType declaringType = (RuntimeType)DeclaringType; RuntimeType baseDeclaringType = declaringType; RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); do { int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); if (cVtblSlots <= slot) break; baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); baseDeclaringType = declaringType; declaringType = (RuntimeType)declaringType.BaseType; } while (declaringType != null); return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). return CreateDelegateInternal( delegateType, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType, Object target) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking). The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. return CreateDelegateInternal( delegateType, target, DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecurityCritical] private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) { // Validate the parameters. if (delegateType == null) throw new ArgumentNullException("delegateType"); Contract.EndContractBlock(); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType"); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType"); Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); if (d == null) { throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); } return d; } #endregion #region Generics [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException("methodInstantiation"); Contract.EndContractBlock(); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) throw new InvalidOperationException( Environment.GetResourceString("Arg_NotGenericMethodDefinition", this)); for (int i = 0; i < methodInstantiation.Length; i++) { Type methodInstantiationElem = methodInstantiation[i]; if (methodInstantiationElem == null) throw new ArgumentNullException(); RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; if (rtMethodInstantiationElem == null) { Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; methodInstantiation = methodInstantiationCopy; return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); } methodInstantionRuntimeType[i] = rtMethodInstantiationElem; } RuntimeType[] genericParameters = GetGenericArgumentsInternal(); RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); MethodInfo ret = null; try { ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; } catch (VerificationException e) { RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); throw; } return ret; } internal RuntimeType[] GetGenericArgumentsInternal() { return RuntimeMethodHandle.GetMethodInstantiationInternal(this); } public override Type[] GetGenericArguments() { Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); if (types == null) { types = EmptyArray<Type>.Value; } return types; } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); Contract.EndContractBlock(); return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } public override bool IsGenericMethod { get { return RuntimeMethodHandle.HasMethodInstantiation(this); } } public override bool IsGenericMethodDefinition { get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } } public override bool ContainsGenericParameters { get { if (DeclaringType != null && DeclaringType.ContainsGenericParameters) return true; if (!IsGenericMethod) return false; Type[] pis = GetGenericArguments(); for (int i = 0; i < pis.Length; i++) { if (pis[i].ContainsGenericParameters) return true; } return false; } } #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); if (m_reflectedTypeCache.IsGlobal) throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization")); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Method, IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null); } internal string SerializationToString() { return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); } #endregion #region Legacy Internal internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (method == null) return null; return RuntimeType.GetMethodBase(method); } #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Linq; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Data.Market; using System.Collections.Generic; using QuantConnect.Data.Fundamental; using QuantConnect.Data.UniverseSelection; using QuantConnect.Logging; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides an implementations of <see cref="ISubscriptionDataSourceReader"/> that uses the /// <see cref="BaseData.Reader(SubscriptionDataConfig,string,DateTime,bool)"/> /// method to read lines of text from a <see cref="SubscriptionDataSource"/> /// </summary> public class TextSubscriptionDataSourceReader : BaseSubscriptionDataSourceReader { private readonly bool _implementsStreamReader; private readonly DateTime _date; private readonly SubscriptionDataConfig _config; private BaseData _factory; private bool _shouldCacheDataPoints; private static int CacheSize = 100; private static volatile Dictionary<string, List<BaseData>> BaseDataSourceCache = new Dictionary<string, List<BaseData>>(100); private static Queue<string> CacheKeys = new Queue<string>(100); /// <summary> /// Event fired when the specified source is considered invalid, this may /// be from a missing file or failure to download a remote source /// </summary> public override event EventHandler<InvalidSourceEventArgs> InvalidSource; /// <summary> /// Event fired when an exception is thrown during a call to /// <see cref="BaseData.Reader(SubscriptionDataConfig,string,DateTime,bool)"/> /// </summary> public event EventHandler<ReaderErrorEventArgs> ReaderError; /// <summary> /// Event fired when there's an error creating an <see cref="IStreamReader"/> or the /// instantiated <see cref="IStreamReader"/> has no data. /// </summary> public event EventHandler<CreateStreamReaderErrorEventArgs> CreateStreamReaderError; /// <summary> /// Initializes a new instance of the <see cref="TextSubscriptionDataSourceReader"/> class /// </summary> /// <param name="dataCacheProvider">This provider caches files if needed</param> /// <param name="config">The subscription's configuration</param> /// <param name="date">The date this factory was produced to read data for</param> /// <param name="isLiveMode">True if we're in live mode, false for backtesting</param> public TextSubscriptionDataSourceReader(IDataCacheProvider dataCacheProvider, SubscriptionDataConfig config, DateTime date, bool isLiveMode) : base(dataCacheProvider, isLiveMode) { _date = date; _config = config; _shouldCacheDataPoints = !_config.IsCustomData && _config.Resolution >= Resolution.Hour && _config.Type != typeof(FineFundamental) && _config.Type != typeof(CoarseFundamental) && !DataCacheProvider.IsDataEphemeral; // we know these type implement the streamReader interface lets avoid dynamic reflection call to figure it out if (_config.Type == typeof(TradeBar) || _config.Type == typeof(QuoteBar) || _config.Type == typeof(Tick)) { _implementsStreamReader = true; } else { var method = _config.Type.GetMethod("Reader", new[] { typeof(SubscriptionDataConfig), typeof(StreamReader), typeof(DateTime), typeof(bool) }); if (method != null && method.DeclaringType == _config.Type) { _implementsStreamReader = true; } } } /// <summary> /// Reads the specified <paramref name="source"/> /// </summary> /// <param name="source">The source to be read</param> /// <returns>An <see cref="IEnumerable{BaseData}"/> that contains the data in the source</returns> public override IEnumerable<BaseData> Read(SubscriptionDataSource source) { List<BaseData> cache = null; _shouldCacheDataPoints = _shouldCacheDataPoints && // only cache local files source.TransportMedium == SubscriptionTransportMedium.LocalFile; string cacheKey = null; if (_shouldCacheDataPoints) { cacheKey = source.Source + _config.Type; BaseDataSourceCache.TryGetValue(cacheKey, out cache); } if (cache == null) { cache = _shouldCacheDataPoints ? new List<BaseData>(30000) : null; using (var reader = CreateStreamReader(source)) { // if the reader doesn't have data then we're done with this subscription if (reader == null || reader.EndOfStream) { OnCreateStreamReaderError(_date, source); yield break; } if (_factory == null) { // only create a factory if the stream isn't null _factory = _config.GetBaseDataInstance(); } // while the reader has data while (!reader.EndOfStream) { BaseData instance = null; string line = null; try { if (reader.StreamReader != null && _implementsStreamReader) { instance = _factory.Reader(_config, reader.StreamReader, _date, IsLiveMode); } else { // read a line and pass it to the base data factory line = reader.ReadLine(); instance = _factory.Reader(_config, line, _date, IsLiveMode); } } catch (Exception err) { OnReaderError(line ?? "StreamReader", err); } if (instance != null && instance.EndTime != default(DateTime)) { if (_shouldCacheDataPoints) { cache.Add(instance); } else { yield return instance; } } else if (reader.ShouldBeRateLimited) { yield return instance; } } } if (!_shouldCacheDataPoints) { yield break; } lock (CacheKeys) { CacheKeys.Enqueue(cacheKey); // we create a new dictionary, so we don't have to take locks when reading, and add our new item var newCache = new Dictionary<string, List<BaseData>>(BaseDataSourceCache) { [cacheKey] = cache }; if (BaseDataSourceCache.Count > CacheSize) { var removeCount = 0; // we remove a portion of the first in entries while (++removeCount < (CacheSize / 4)) { newCache.Remove(CacheKeys.Dequeue()); } // update the cache instance BaseDataSourceCache = newCache; } else { // update the cache instance BaseDataSourceCache = newCache; } } } if (cache == null) { throw new InvalidOperationException($"Cache should not be null. Key: {cacheKey}"); } // Find the first data point 10 days (just in case) before the desired date // and subtract one item (just in case there was a time gap and data.Time is after _date) var frontier = _date.AddDays(-10); var index = cache.FindIndex(data => data.Time > frontier); index = index > 0 ? (index - 1) : 0; foreach (var data in cache.Skip(index)) { var clone = data.Clone(); clone.Symbol = _config.Symbol; yield return clone; } } /// <summary> /// Event invocator for the <see cref="InvalidSource"/> event /// </summary> /// <param name="source">The <see cref="SubscriptionDataSource"/> that was invalid</param> /// <param name="exception">The exception if one was raised, otherwise null</param> private void OnInvalidSource(SubscriptionDataSource source, Exception exception) { var handler = InvalidSource; if (handler != null) handler(this, new InvalidSourceEventArgs(source, exception)); } /// <summary> /// Event invocator for the <see cref="ReaderError"/> event /// </summary> /// <param name="line">The line that caused the exception</param> /// <param name="exception">The exception that was caught</param> private void OnReaderError(string line, Exception exception) { var handler = ReaderError; if (handler != null) handler(this, new ReaderErrorEventArgs(line, exception)); } /// <summary> /// Event invocator for the <see cref="CreateStreamReaderError"/> event /// </summary> /// <param name="date">The date of the source</param> /// <param name="source">The source that caused the error</param> private void OnCreateStreamReaderError(DateTime date, SubscriptionDataSource source) { var handler = CreateStreamReaderError; if (handler != null) handler(this, new CreateStreamReaderErrorEventArgs(date, source)); } /// <summary> /// Set the cache size to use /// </summary> /// <remarks>How to size this cache: Take worst case scenario, BTCUSD hour, 60k QuoteBar entries, which are roughly 200 bytes in size -> 11 MB * CacheSize</remarks> public static void SetCacheSize(int megaBytesToUse) { if (megaBytesToUse != 0) { // we take worst case scenario, each entry is 12 MB CacheSize = megaBytesToUse / 12; Log.Trace($"TextSubscriptionDataSourceReader.SetCacheSize(): Setting cache size to {CacheSize} items"); } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.txt file at the root of this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using Microsoft.VisualStudio.Shell; using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Text; namespace Microsoft.VisualStudio.Project { /// <summary> /// Replacement type /// </summary> public enum TokenReplaceType { ReplaceString, ReplaceNumber, ReplaceCode } /// <summary> /// Contain a number of functions that handle token replacement /// </summary> [CLSCompliant(false)] public class TokenProcessor { #region fields // Internal fields private ArrayList tokenlist; #endregion #region Initialization /// <summary> /// Constructor /// </summary> public TokenProcessor() { tokenlist = new ArrayList(); } /// <summary> /// Reset list of TokenReplacer entries /// </summary> public virtual void Reset() { tokenlist.Clear(); } /// <summary> /// Add a replacement type entry /// </summary> /// <param name="token">token to replace</param> /// <param name="replacement">replacement string</param> public virtual void AddReplace(string token, string replacement) { tokenlist.Add(new ReplacePairToken(token, replacement)); } /// <summary> /// Add replace between entry /// </summary> /// <param name="tokenStart">Start token</param> /// <param name="tokenEnd">End token</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "tokenid")] public virtual void AddReplaceBetween(string tokenid, string tokenStart, string tokenEnd, string replacement) { tokenlist.Add(new ReplaceBetweenPairToken(tokenid, tokenStart, tokenEnd, replacement)); } /// <summary> /// Add a deletion entry /// </summary> /// <param name="tokenToDelete">Token to delete</param> public virtual void AddDelete(string tokenToDelete) { tokenlist.Add(new DeleteToken(tokenToDelete)); } #endregion #region TokenProcessing /// <summary> /// For all known token, replace token with correct value /// </summary> /// <param name="source">File of the source file</param> /// <param name="destination">File of the destination file</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily"), SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Untoken")] public virtual void UntokenFile(string source, string destination) { Utilities.ArgumentNotNullOrEmpty("source", source); Utilities.ArgumentNotNullOrEmpty("destination", destination); // Make sure that the destination folder exists. string destinationFolder = Path.GetDirectoryName(destination); if(!Directory.Exists(destinationFolder)) { Directory.CreateDirectory(destinationFolder); } // Open the file. Check to see if the File is binary or text. // NOTE: This is not correct because GetBinaryType will return true // only if the file is executable, not if it is a dll, a library or // any other type of binary file. uint binaryType; if(!NativeMethods.GetBinaryType(source, out binaryType)) { Encoding encoding = Encoding.Default; string buffer = null; // Create the reader to get the text. Note that we will default to ASCII as // encoding if the file does not contains a different signature. using(StreamReader reader = new StreamReader(source, Encoding.ASCII, true)) { // Get the content of the file. buffer = reader.ReadToEnd(); // Detect the encoding of the source file. Note that we // can get the encoding only after a read operation is // performed on the file. encoding = reader.CurrentEncoding; } foreach(object pair in tokenlist) { if(pair is DeleteToken) DeleteTokens(ref buffer, (DeleteToken)pair); if(pair is ReplaceBetweenPairToken) ReplaceBetweenTokens(ref buffer, (ReplaceBetweenPairToken)pair); if(pair is ReplacePairToken) ReplaceTokens(ref buffer, (ReplacePairToken)pair); } File.WriteAllText(destination, buffer, encoding); } else Utilities.CopyFileSafe(source, destination); } /// <summary> /// Replaces the tokens in a buffer with the replacement string /// </summary> /// <param name="buffer">Buffer to update</param> /// <param name="tokenToReplace">replacement data</param> public virtual void ReplaceTokens(ref string buffer, ReplacePairToken tokenToReplace) { Utilities.ArgumentNotNull("tokenToReplace", tokenToReplace); Utilities.ArgumentNotNull("buffer", buffer); buffer = buffer.Replace(tokenToReplace.Token, tokenToReplace.Replacement); } /// <summary> /// Deletes the token from the buffer /// </summary> /// <param name="buffer">Buffer to update</param> /// <param name="tokenToDelete">token to delete</param> public virtual void DeleteTokens(ref string buffer, DeleteToken tokenToDelete) { Utilities.ArgumentNotNull("tokenToDelete", tokenToDelete); Utilities.ArgumentNotNull("buffer", buffer); buffer = buffer.Replace(tokenToDelete.StringToDelete, string.Empty); } /// <summary> /// Replaces the token from the buffer between the provided tokens /// </summary> /// <param name="buffer">Buffer to update</param> /// <param name="rpBetweenToken">replacement token</param> public virtual void ReplaceBetweenTokens(ref string buffer, ReplaceBetweenPairToken rpBetweenToken) { Utilities.ArgumentNotNull("rpBetweenToken", rpBetweenToken); Utilities.ArgumentNotNull("buffer", buffer); string regularExp = rpBetweenToken.TokenStart + "[^" + rpBetweenToken.TokenIdentifier + "]*" + rpBetweenToken.TokenEnd; buffer = System.Text.RegularExpressions.Regex.Replace(buffer, regularExp, rpBetweenToken.TokenReplacement); } #endregion #region Guid generators /// <summary> /// Generates a string representation of a guid with the following format: /// 0x01020304, 0x0506, 0x0708, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 /// </summary> /// <param name="value">Guid to be generated</param> /// <returns>The guid as string</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public string GuidToForm1(Guid value) { byte[] GuidBytes = value.ToByteArray(); StringBuilder ResultingStr = new StringBuilder(80); // First 4 bytes int i = 0; int Number = 0; for(i = 0; i < 4; ++i) { int CurrentByte = GuidBytes[i]; Number += CurrentByte << (8 * i); } UInt32 FourBytes = (UInt32)Number; ResultingStr.AppendFormat(CultureInfo.InvariantCulture, "0x{0}", FourBytes.ToString("X", CultureInfo.InvariantCulture)); // 2 chunks of 2 bytes for(int j = 0; j < 2; ++j) { Number = 0; for(int k = 0; k < 2; ++k) { int CurrentByte = GuidBytes[i++]; Number += CurrentByte << (8 * k); } UInt16 TwoBytes = (UInt16)Number; ResultingStr.AppendFormat(CultureInfo.InvariantCulture, ", 0x{0}", TwoBytes.ToString("X", CultureInfo.InvariantCulture)); } // 8 chunks of 1 bytes for(int j = 0; j < 8; ++j) { ResultingStr.AppendFormat(CultureInfo.InvariantCulture, ", 0x{0}", GuidBytes[i++].ToString("X", CultureInfo.InvariantCulture)); } return ResultingStr.ToString(); } /// <summary> /// Generates a string representation of a guid with the following format: /// 0x01020304, 0x0506, 0x0708, { 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 } /// </summary> /// <param name="value">Guid to be generated.</param> /// <returns>The guid as string.</returns> private string GuidToForm2(Guid value) { byte[] GuidBytes = value.ToByteArray(); StringBuilder ResultingStr = new StringBuilder(80); // First 4 bytes int i = 0; int Number = 0; for (i = 0; i < 4; ++i) { int CurrentByte = GuidBytes[i]; Number += CurrentByte << (8 * i); } UInt32 FourBytes = (UInt32)Number; ResultingStr.AppendFormat(CultureInfo.InvariantCulture, "0x{0}", FourBytes.ToString("X", CultureInfo.InvariantCulture)); // 2 chunks of 2 bytes for (int j = 0; j < 2; ++j) { Number = 0; for (int k = 0; k < 2; ++k) { int CurrentByte = GuidBytes[i++]; Number += CurrentByte << (8 * k); } UInt16 TwoBytes = (UInt16)Number; ResultingStr.AppendFormat(CultureInfo.InvariantCulture, ", 0x{0}", TwoBytes.ToString("X", CultureInfo.InvariantCulture)); } // 8 chunks of 1 bytes ResultingStr.AppendFormat(CultureInfo.InvariantCulture, ", {{ 0x{0}", GuidBytes[i++].ToString("X", CultureInfo.InvariantCulture)); for (int j = 1; j < 8; ++j) { ResultingStr.AppendFormat(CultureInfo.InvariantCulture, ", 0x{0}", GuidBytes[i++].ToString("X", CultureInfo.InvariantCulture)); } ResultingStr.Append(" }"); return ResultingStr.ToString(); } #endregion #region Helper Methods /// <summary> /// This function will accept a subset of the characters that can create an /// identifier name: there are other unicode char that can be inside the name, but /// this function will not allow. By now it can work this way, but when and if the /// VSIP package will handle also languages different from english, this function /// must be changed. /// </summary> /// <param name="c">Character to validate</param> /// <returns>true if successful false otherwise</returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "c")] protected static bool IsValidIdentifierChar(char c) { if((c >= 'a') && (c <= 'z')) { return true; } if((c >= 'A') && (c <= 'Z')) { return true; } if(c == '_') { return true; } if((c >= '0') && (c <= '9')) { return true; } return false; } /// <summary> /// Verifies if the start character is valid /// </summary> /// <param name="c">Start character</param> /// <returns>true if successful false otherwise</returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "c")] protected static bool IsValidIdentifierStartChar(char c) { if(!IsValidIdentifierChar(c)) { return false; } if((c >= '0') && (c <= '9')) { return false; } return true; } /// <summary> /// The goal here is to reduce the risk of name conflict between 2 classes /// added in different directories. This code does NOT garanty uniqueness. /// To guaranty uniqueness, you should change this function to work with /// the language service to verify that the namespace+class generated does /// not conflict. /// </summary> /// <param name="fileFullPath">Full path to the new file</param> /// <returns>Namespace to use for the new file</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public string GetFileNamespace(string fileFullPath, ProjectNode node) { Utilities.ArgumentNotNull("node", node); ThreadHelper.ThrowIfNotOnUIThread(); // Get base namespace from the project string namespce = node.GetProjectProperty("RootNamespace"); if(String.IsNullOrEmpty(namespce)) namespce = Path.GetFileNameWithoutExtension(fileFullPath); // If the item is added to a sub folder, the name space should reflect this. // This is done so that class names from 2 files with the same name but different // directories don't conflict. string relativePath = Path.GetDirectoryName(fileFullPath); string projectPath = Path.GetDirectoryName(node.GetMkDocument()); // Our project system only support adding files that are sibling of the project file or that are in subdirectories. if(String.Compare(projectPath, 0, relativePath, 0, projectPath.Length, true, CultureInfo.CurrentCulture) == 0) { relativePath = relativePath.Substring(projectPath.Length); } else { Debug.Fail("Adding an item to the project that is NOT under the project folder."); // We are going to use the full file path for generating the namespace } // Get the list of parts int index = 0; string[] pathParts; pathParts = relativePath.Split(Path.DirectorySeparatorChar); // Use a string builder with default size being the expected size StringBuilder result = new StringBuilder(namespce, namespce.Length + relativePath.Length + 1); // For each path part while(index < pathParts.Length) { string part = pathParts[index]; ++index; // This could happen if the path had leading/trailing slash, we want to ignore empty pieces if(String.IsNullOrEmpty(part)) continue; // If we reach here, we will be adding something, so add a namespace separator '.' result.Append('.'); // Make sure it starts with a letter if(!char.IsLetter(part, 0)) result.Append('N'); // Filter invalid namespace characters foreach(char c in part) { if(char.IsLetterOrDigit(c)) result.Append(c); } } return result.ToString(); } #endregion } /// <summary> /// Storage classes for replacement tokens /// </summary> public class ReplacePairToken { /// <summary> /// token string /// </summary> private string token; /// <summary> /// Replacement string /// </summary> private string replacement; /// <summary> /// Constructor /// </summary> /// <param name="token">replaceable token</param> /// <param name="replacement">replacement string</param> public ReplacePairToken(string token, string replacement) { this.token = token; this.replacement = replacement; } /// <summary> /// Token that needs to be replaced /// </summary> public string Token { get { return token; } } /// <summary> /// String to replace the token with /// </summary> public string Replacement { get { return replacement; } } } /// <summary> /// Storage classes for token to be deleted /// </summary> public class DeleteToken { /// <summary> /// String to delete /// </summary> private string token; /// <summary> /// Constructor /// </summary> /// <param name="token">Deletable token.</param> public DeleteToken(string token) { this.token = token; } /// <summary> /// Token marking the end of the block to delete /// </summary> public string StringToDelete { get { return token; } } } /// <summary> /// Storage classes for string to be deleted between tokens to be deleted /// </summary> public class ReplaceBetweenPairToken { /// <summary> /// Token start /// </summary> private string tokenStart; /// <summary> /// End token /// </summary> private string tokenEnd; /// <summary> /// Replacement string /// </summary> private string replacement; /// <summary> /// Token identifier string /// </summary> private string tokenidentifier; /// <summary> /// Constructor /// </summary> /// <param name="blockStart">Start token</param> /// <param name="blockEnd">End Token</param> /// <param name="replacement">Replacement string.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "tokenid")] public ReplaceBetweenPairToken(string tokenid, string blockStart, string blockEnd, string replacement) { tokenStart = blockStart; tokenEnd = blockEnd; this.replacement = replacement; tokenidentifier = tokenid; } /// <summary> /// Token marking the begining of the block to delete /// </summary> public string TokenStart { get { return tokenStart; } } /// <summary> /// Token marking the end of the block to delete /// </summary> public string TokenEnd { get { return tokenEnd; } } /// <summary> /// Token marking the end of the block to delete /// </summary> public string TokenReplacement { get { return replacement; } } /// <summary> /// Token Identifier /// </summary> public string TokenIdentifier { get { return tokenidentifier; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xna.Framework.Content; namespace Cocos2D { #if IOS [MonoTouch.Foundation.Preserve (AllMembers = true)] #endif public class CCBMFontConfiguration { [ContentSerializer] internal int m_nCommonHeight; [ContentSerializer] internal Dictionary<int, CCBMFontDef> m_pFontDefDictionary = new Dictionary<int, CCBMFontDef>(); [ContentSerializer] internal Dictionary<int, CCKerningHashElement> m_pKerningDictionary = new Dictionary<int, CCKerningHashElement>(); [ContentSerializer] internal string m_sAtlasName; [ContentSerializer] internal CCBMFontPadding m_tPadding; private List<int> m_pCharacterSet = new List<int>(); public string AtlasName { get { return m_sAtlasName; } set { m_sAtlasName = value; } } public List<int> CharacterSet { set { m_pCharacterSet = value; } get { return m_pCharacterSet; } } public CCBMFontConfiguration() { } public CCBMFontConfiguration(string data, string fntFile) { InitWithString(data, fntFile); } /// <summary> /// This create method is left in the project because this class is loaded /// by the ContentManager. This create factory is a legitimate use of the /// self factory pattern. /// </summary> /// <param name="fntFile"></param> /// <returns></returns> public static CCBMFontConfiguration Create(string fntFile) { try { return CCContentManager.SharedContentManager.Load<CCBMFontConfiguration>(fntFile); } catch (ContentLoadException) { var pRet = new CCBMFontConfiguration(); if (pRet.InitWithFNTFile(fntFile)) { return pRet; } } return null; } protected virtual bool InitWithFNTFile(string fntFile) { string content = CCContentManager.SharedContentManager.Load<string>(fntFile); return InitWithString(content, fntFile); } protected virtual bool InitWithString(string data, string fntFile) { m_pKerningDictionary.Clear(); m_pFontDefDictionary.Clear(); m_pCharacterSet = ParseConfigFile(data, fntFile); if (m_pCharacterSet == null) { return false; } return true; } private List<int> ParseConfigFile(string pBuffer, string fntFile) { long nBufSize = pBuffer.Length; Debug.Assert(pBuffer != null, "CCBMFontConfiguration::parseConfigFile | Open file error."); if (string.IsNullOrEmpty(pBuffer)) { return null; } var validCharsString = new List<int>(); // parse spacing / padding string line; string strLeft = pBuffer; while (strLeft.Length > 0) { int pos = strLeft.IndexOf('\n'); if (pos != -1) { // the data is more than a line.get one line line = strLeft.Substring(0, pos); strLeft = strLeft.Substring(pos + 1); } else { // get the left data line = strLeft; strLeft = null; } if (line.StartsWith("info face")) { // XXX: info parsing is incomplete // Not needed for the Hiero editors, but needed for the AngelCode editor // [self parseInfoArguments:line]; parseInfoArguments(line); } // Check to see if the start of the line is something we are interested in else if (line.StartsWith("common lineHeight")) { parseCommonArguments(line); } else if (line.StartsWith("page id")) { parseImageFileName(line, fntFile); } else if (line.StartsWith("chars c")) { // Ignore this line } else if (line.StartsWith("char")) { // Parse the current line and create a new CharDef var characterDefinition = new CCBMFontDef(); parseCharacterDefinition(line, characterDefinition); m_pFontDefDictionary.Add(characterDefinition.charID, characterDefinition); validCharsString.Add(characterDefinition.charID); } //else if (line.StartsWith("kernings count")) //{ // this.parseKerningCapacity(line); //} else if (line.StartsWith("kerning first")) { parseKerningEntry(line); } } return validCharsString; } private void parseCharacterDefinition(string line, CCBMFontDef characterDefinition) { ////////////////////////////////////////////////////////////////////////// // line to parse: // char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0 ////////////////////////////////////////////////////////////////////////// // Character ID int index = line.IndexOf("id="); int index2 = line.IndexOf(' ', index); string value = line.Substring(index, index2 - index); characterDefinition.charID = Cocos2D.CCUtils.CCParseInt(value.Replace("id=", "")); //CCAssert(characterDefinition->charID < kCCBMFontMaxChars, "BitmpaFontAtlas: CharID bigger than supported"); // Character x index = line.IndexOf("x="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.rect.Origin.X = Cocos2D.CCUtils.CCParseFloat(value.Replace("x=", "")); // Character y index = line.IndexOf("y="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.rect.Origin.Y = Cocos2D.CCUtils.CCParseFloat(value.Replace("y=", "")); // Character width index = line.IndexOf("width="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.rect.Size.Width = Cocos2D.CCUtils.CCParseFloat(value.Replace("width=", "")); // Character height index = line.IndexOf("height="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.rect.Size.Height = Cocos2D.CCUtils.CCParseFloat(value.Replace("height=", "")); // Character xoffset index = line.IndexOf("xoffset="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.xOffset = Cocos2D.CCUtils.CCParseInt(value.Replace("xoffset=", "")); // Character yoffset index = line.IndexOf("yoffset="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.yOffset = Cocos2D.CCUtils.CCParseInt(value.Replace("yoffset=", "")); // Character xadvance index = line.IndexOf("xadvance="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); characterDefinition.xAdvance = Cocos2D.CCUtils.CCParseInt(value.Replace("xadvance=", "")); } // info face private void parseInfoArguments(string line) { ////////////////////////////////////////////////////////////////////////// // possible lines to parse: // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0 // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 ////////////////////////////////////////////////////////////////////////// // padding int index = line.IndexOf("padding="); int index2 = line.IndexOf(' ', index); string value = line.Substring(index, index2 - index); value = value.Replace("padding=", ""); string[] temp = value.Split(','); m_tPadding.top = Cocos2D.CCUtils.CCParseInt(temp[0]); m_tPadding.right = Cocos2D.CCUtils.CCParseInt(temp[1]); m_tPadding.bottom = Cocos2D.CCUtils.CCParseInt(temp[2]); m_tPadding.left = Cocos2D.CCUtils.CCParseInt(temp[3]); //CCLOG("cocos2d: padding: %d,%d,%d,%d", m_tPadding.left, m_tPadding.top, m_tPadding.right, m_tPadding.bottom); } // common private void parseCommonArguments(string line) { ////////////////////////////////////////////////////////////////////////// // line to parse: // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0 ////////////////////////////////////////////////////////////////////////// // Height int index = line.IndexOf("lineHeight="); int index2 = line.IndexOf(' ', index); string value = line.Substring(index, index2 - index); m_nCommonHeight = Cocos2D.CCUtils.CCParseInt(value.Replace("lineHeight=", "")); // scaleW. sanity check index = line.IndexOf("scaleW=") + "scaleW=".Length; index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); //CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported"); // scaleH. sanity check index = line.IndexOf("scaleH=") + "scaleH=".Length; index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); //CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported"); // pages. sanity check index = line.IndexOf("pages=") + "pages=".Length; index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); //CCAssert(atoi(value.c_str()) == 1, "CCBitfontAtlas: only supports 1 page"); // packed (ignore) What does this mean ?? } //page file private void parseImageFileName(string line, string fntFile) { // ////////////////////////////////////////////////////////////////////////// //// line to parse: //// page id=0 file="bitmapFontTest.png" //////////////////////////////////////////////////////////////////////////// // page ID. Sanity check int index = line.IndexOf('=') + 1; int index2 = line.IndexOf(' ', index); string value = line.Substring(index, index2 - index); try { int ivalue = int.Parse(value); } catch (Exception) { throw (new ContentLoadException("Invalid page ID for FNT descriptor. Line=" + line + ", value=" + value + ", indices=" + index + "," + index2)); } // Debug.Assert(Convert.ToInt32(value) == 0, "LabelBMFont file could not be found"); // file index = line.IndexOf('"') + 1; index2 = line.IndexOf('"', index); value = line.Substring(index, index2 - index); m_sAtlasName = Cocos2D.CCFileUtils.FullPathFromRelativeFile(value, fntFile); } private void parseKerningEntry(string line) { ////////////////////////////////////////////////////////////////////////// // line to parse: // kerning first=121 second=44 amount=-7 ////////////////////////////////////////////////////////////////////////// // first int first; int index = line.IndexOf("first="); int index2 = line.IndexOf(' ', index); string value = line.Substring(index, index2 - index); first = Cocos2D.CCUtils.CCParseInt(value.Replace("first=", "")); // second int second; index = line.IndexOf("second="); index2 = line.IndexOf(' ', index); value = line.Substring(index, index2 - index); second = Cocos2D.CCUtils.CCParseInt(value.Replace("second=", "")); // amount int amount; index = line.IndexOf("amount="); index2 = line.IndexOf(' ', index); value = line.Substring(index); amount = Cocos2D.CCUtils.CCParseInt(value.Replace("amount=", "")); try { var element = new CCKerningHashElement(); element.amount = amount; element.key = (first << 16) | (second & 0xffff); m_pKerningDictionary.Add(element.key, element); } catch (Exception) { Cocos2D.CCLog.Log("Failed to parse font line: {0}", line); } } private void purgeKerningDictionary() { m_pKerningDictionary.Clear(); } #region Nested type: ccBMFontDef /// <summary> /// BMFont definition /// </summary> public class CCBMFontDef { /// <summary> /// ID of the character /// </summary> public int charID; /// <summary> /// origin and size of the font /// </summary> public CCRect rect; /// <summary> /// The amount to move the current position after drawing the character (in pixels) /// </summary> public int xAdvance; /// <summary> /// The X amount the image should be offset when drawing the image (in pixels) /// </summary> public int xOffset; /// <summary> /// The Y amount the image should be offset when drawing the image (in pixels) /// </summary> public int yOffset; } #endregion #region Nested type: ccBMFontPadding internal struct CCBMFontPadding { // padding left public int bottom; public int left; // padding top // padding right public int right; public int top; // padding bottom } #endregion #region Nested type: tKerningHashElement public struct CCKerningHashElement { public int amount; public int key; //key for the hash. 16-bit for 1st element, 16-bit for 2nd element } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ namespace NPOI.SS.Formula.Functions { using System; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula; using System.Text; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; /** * Implementation for Excel function INDIRECT<p/> * * INDIRECT() returns the cell or area reference denoted by the text argument.<p/> * * <b>Syntax</b>:<br/> * <b>INDIRECT</b>(<b>ref_text</b>,isA1Style)<p/> * * <b>ref_text</b> a string representation of the desired reference as it would normally be written * in a cell formula.<br/> * <b>isA1Style</b> (default TRUE) specifies whether the ref_text should be interpreted as A1-style * or R1C1-style. * * * @author Josh Micich */ public class Indirect : FreeRefFunction { public static FreeRefFunction instance = new Indirect(); private Indirect() { // enforce singleton } public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec) { if (args.Length < 1) { return ErrorEval.VALUE_INVALID; } bool isA1style; String text; try { ValueEval ve = OperandResolver.GetSingleValue(args[0], ec.RowIndex, ec .ColumnIndex); text = OperandResolver.CoerceValueToString(ve); switch (args.Length) { case 1: isA1style = true; break; case 2: isA1style = EvaluateBooleanArg(args[1], ec); break; default: return ErrorEval.VALUE_INVALID; } } catch (EvaluationException e) { return e.GetErrorEval(); } return EvaluateIndirect(ec, text, isA1style); } private static bool EvaluateBooleanArg(ValueEval arg, OperationEvaluationContext ec) { ValueEval ve = OperandResolver.GetSingleValue(arg, ec.RowIndex, ec.ColumnIndex); if (ve == BlankEval.instance || ve == MissingArgEval.instance) { return false; } // numeric quantities follow standard bool conversion rules // for strings, only "TRUE" and "FALSE" (case insensitive) are valid return (bool)OperandResolver.CoerceValueToBoolean(ve, false); } private static ValueEval EvaluateIndirect(OperationEvaluationContext ec, String text, bool isA1style) { int tmp = ec.RowIndex; tmp = ec.ColumnIndex; // Search backwards for '!' because sheet names can contain '!' int plingPos = text.LastIndexOf('!'); String workbookName; String sheetName; String refText; // whitespace around this Gets Trimmed OK if (plingPos < 0) { workbookName = null; sheetName = null; refText = text; } else { String[] parts = ParseWorkbookAndSheetName(text.Substring(0, plingPos)); if (parts == null) { return ErrorEval.REF_INVALID; } workbookName = parts[0]; sheetName = parts[1]; refText = text.Substring(plingPos + 1); } String refStrPart1; String refStrPart2; if (Table.IsStructuredReference.Match(refText).Success) { // The argument is structured reference Area3DPxg areaPtg = null; try { areaPtg = FormulaParser.ParseStructuredReference(refText, (IFormulaParsingWorkbook)ec.GetWorkbook(), ec.RowIndex); } catch (FormulaParseException e) { return ErrorEval.REF_INVALID; } return ec.GetArea3DEval(areaPtg); } else { // The argumnet is regular reference int colonPos = refText.IndexOf(':'); if (colonPos < 0) { refStrPart1 = refText.Trim(); refStrPart2 = null; } else { refStrPart1 = refText.Substring(0, colonPos).Trim(); refStrPart2 = refText.Substring(colonPos + 1).Trim(); } return ec.GetDynamicReference(workbookName, sheetName, refStrPart1, refStrPart2, isA1style); } } /** * @return array of length 2: {workbookName, sheetName,}. Second element will always be * present. First element may be null if sheetName is unqualified. * Returns <code>null</code> if text cannot be parsed. */ private static String[] ParseWorkbookAndSheetName(string text) { int lastIx = text.Length - 1; if (lastIx < 0) { return null; } if (CanTrim(text)) { return null; } char firstChar = text[0]; if (Char.IsWhiteSpace(firstChar)) { return null; } if (firstChar == '\'') { // workbookName or sheetName needs quoting // quotes go around both if (text[lastIx] != '\'') { return null; } firstChar = text[1]; if (Char.IsWhiteSpace(firstChar)) { return null; } String wbName; int sheetStartPos; if (firstChar == '[') { int rbPos = text.ToString().LastIndexOf(']'); if (rbPos < 0) { return null; } wbName = UnescapeString(text.Substring(2, rbPos - 2)); if (wbName == null || CanTrim(wbName)) { return null; } sheetStartPos = rbPos + 1; } else { wbName = null; sheetStartPos = 1; } // else - just sheet name String sheetName = UnescapeString(text.Substring(sheetStartPos, lastIx - sheetStartPos)); if (sheetName == null) { // note - when quoted, sheetName can // start/end with whitespace return null; } return new String[] { wbName, sheetName, }; } if (firstChar == '[') { int rbPos = text.ToString().LastIndexOf(']'); if (rbPos < 0) { return null; } string wbName = text.Substring(1, rbPos - 1); if (CanTrim(wbName)) { return null; } string sheetName = text.Substring(rbPos + 1); if (CanTrim(sheetName)) { return null; } return new String[] { wbName.ToString(), sheetName.ToString(), }; } // else - just sheet name return new String[] { null, text.ToString(), }; } /** * @return <code>null</code> if there is a syntax error in any escape sequence * (the typical syntax error is a single quote character not followed by another). */ private static String UnescapeString(string text) { int len = text.Length; StringBuilder sb = new StringBuilder(len); int i = 0; while (i < len) { char ch = text[i]; if (ch == '\'') { // every quote must be followed by another i++; if (i >= len) { return null; } ch = text[i]; if (ch != '\'') { return null; } } sb.Append(ch); i++; } return sb.ToString(); } private static bool CanTrim(string text) { int lastIx = text.Length - 1; if (lastIx < 0) { return false; } if (Char.IsWhiteSpace(text[0])) { return true; } if (Char.IsWhiteSpace(text[lastIx])) { return true; } return false; } } }
#region using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; #endregion namespace Highway.Data.Rest.ExampleAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator" /> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage" /> or /// <see cref="HttpResponseMessage" />. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription" />. /// </summary> /// <param name="api">The <see cref="ApiDescription" />.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription" />. /// </summary> /// <param name="api">The <see cref="ApiDescription" />.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription" />.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof (HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples" />. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if ( ActionSamples.TryGetValue( new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue( new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] {"*"}), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects" />. If no sample object is found, it will try to create one /// using <see cref="ObjectGenerator" />. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage" /> or /// <see cref="HttpResponseMessage" /> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription" />.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof (SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int) sampleDirection, typeof (SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if ( ActualHttpMessageTypes.TryGetValue( new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue( new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] {"*"}), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] {"*"}) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace WebMatrix.Data.StronglyTyped.Tests { using System; using System.ComponentModel.DataAnnotations; using System.Data.SqlServerCe; using System.IO; using NUnit.Framework; using System.Linq; using Should; [TestFixture] public class ExecuteTests { private string connString = "Data Source='Test.sdf'"; [TestFixtureSetUp] public void TestFixtureSetup() { // Initialize the database. if (File.Exists("Test.sdf")) { File.Delete("Test.sdf"); } using (var engine = new SqlCeEngine(connString)) { engine.CreateDatabase(); } using (var conn = new SqlCeConnection(connString)) { var cmd = conn.CreateCommand(); conn.Open(); cmd.CommandText = "create table Users (Id int identity not null, Name nvarchar(250))"; cmd.ExecuteNonQuery(); } StrongTypingExtensions.Log = Console.Out; } [SetUp] public void Setup() { using (var db = Database.Open("Test")) { db.Execute("delete from Users"); } } [Test] public void Deletes_all_records() { using (var db = Database.Open("Test")) { var user = new User { Name = "Foo" }; db.Insert(user); user.Name = "Bar"; db.Insert(user); var users = db.Query<User>(); users.Count().ShouldEqual(2); db.Delete<User>(); users = db.Query<User>(); users.Count().ShouldEqual(0); } } [Test] public void Deletes_records_by_id() { using (var db = Database.Open("Test")) { var user = new User { Name = "Foo" }; db.Insert(user); user.Name = "Bar"; db.Insert(user); user.Name = "Taco"; db.Insert(user); var users = db.Query<User>(); users.Count().ShouldEqual(3); db.Delete<User>("where id = @0", users.First().Id); users = db.Query<User>(); users.Count().ShouldEqual(2); db.Delete<User>("where id = @0", users.Last().Id); users = db.Query<User>(); users.Count().ShouldEqual(1); users.First().Name.ShouldEqual("Bar"); } } [Test] public void Deletes_records_by_query() { using (var db = Database.Open("Test")) { var user = new User { Name = "Boo" }; db.Insert(user); user.Name = "Bar"; db.Insert(user); user.Name = "Taco"; db.Insert(user); user.Name = "Bacon"; db.Insert(user); var users = db.Query<User>(); users.Count().ShouldEqual(4); db.Delete<User>("where name like @0", "b%"); users = db.Query<User>(); users.Count().ShouldEqual(1); users.First().Name.ShouldEqual("Taco"); } } [Test] public void Deletes_records_only_in_query() { using (var db = Database.Open("Test")) { var user = new User { Name = "Boo" }; db.Insert(user); user.Name = "Bar"; db.Insert(user); user.Name = "Taco"; db.Insert(user); user.Name = "Bacon"; db.Insert(user); var users = db.Query<User>(); users.Count().ShouldEqual(4); db.Delete<User>("where name = @0", "monkey"); users = db.Query<User>(); users.Count().ShouldEqual(4); } } [Test] public void Inserts_record() { using(var db = Database.Open("Test")) { db.Insert(new User { Name = "Foo" }); var result = db.Query<User>().Single(); result.Name.ShouldEqual("Foo"); } } [Test] public void Inserts_record_with_aliased_column() { using(var db = Database.Open("Test")) { db.Insert(new UserWithAliasedProperty { OtherName = "FooAliased" }); var result = db.Query<User>().Single(); result.Name.ShouldEqual("FooAliased"); } } [Test] public void Updates_record() { using (var db = Database.Open("Test")) { var user = new User { Name = "Foo" }; db.Insert(user); user.Name = "Bar"; db.Update(user); var result = db.Query<User>().Single(); result.Name.ShouldEqual("Bar"); } } [Test] public void Inserts_with_store_generated_id() { using(var db = Database.Open("Test")) { var user = new User{ Name = "Foo" }; db.Insert(user); user.Id.ShouldNotEqual(0); } } [Test] public void Inserts_with_store_generated_id_when_id_is_implicit() { using (var db = Database.Open("Test")) { var user = new UserWithImplicitId { Name = "Foo" }; db.Insert(user); user.Id.ShouldNotEqual(0); } } [Table("Users")] public class User { [Key] public int Id { get; set; } public string Name { get; set; } } [Table("Users")] public class UserWithImplicitId { public int Id { get; set; } public string Name { get; set; } } [Table("Users")] public class UserWithAliasedProperty { public int Id { get; set; } [Column("Name")] public string OtherName { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt641() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt641 { private struct TestStruct { public Vector128<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt641 testClass) { var result = Sse2.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt641() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt641() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShiftRightLogical( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftRightLogical( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftRightLogical( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt641(); var result = Sse2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((long)(firstOp[0] >> 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((long)(firstOp[i] >> 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int64>(Vector128<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #if !PORTABLE40 using System; using System.Collections.Generic; using System.Globalization; using System.Xml; #if !(NET20 || PORTABLE40) using System.Xml.Linq; #endif using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Converters { #region XmlNodeWrappers #if !NETFX_CORE && !PORTABLE && !PORTABLE40 internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument { private readonly XmlDocument _document; public XmlDocumentWrapper(XmlDocument document) : base(document) { _document = document; } public IXmlNode CreateComment(string data) { return new XmlNodeWrapper(_document.CreateComment(data)); } public IXmlNode CreateTextNode(string text) { return new XmlNodeWrapper(_document.CreateTextNode(text)); } public IXmlNode CreateCDataSection(string data) { return new XmlNodeWrapper(_document.CreateCDataSection(data)); } public IXmlNode CreateWhitespace(string text) { return new XmlNodeWrapper(_document.CreateWhitespace(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XmlNodeWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XmlElementWrapper(_document.CreateElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri)); } public IXmlNode CreateAttribute(string name, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name)); attribute.Value = value; return attribute; } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; return attribute; } public IXmlElement DocumentElement { get { if (_document.DocumentElement == null) return null; return new XmlElementWrapper(_document.DocumentElement); } } } internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement { private readonly XmlElement _element; public XmlElementWrapper(XmlElement element) : base(element) { _element = element; } public void SetAttributeNode(IXmlNode attribute) { XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute; _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode); } public string GetPrefixOfNamespace(string namespaceUri) { return _element.GetPrefixOfNamespace(namespaceUri); } } internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration { private readonly XmlDeclaration _declaration; public XmlDeclarationWrapper(XmlDeclaration declaration) : base(declaration) { _declaration = declaration; } public string Version { get { return _declaration.Version; } } public string Encoding { get { return _declaration.Encoding; } set { _declaration.Encoding = value; } } public string Standalone { get { return _declaration.Standalone; } set { _declaration.Standalone = value; } } } internal class XmlNodeWrapper : IXmlNode { private readonly XmlNode _node; public XmlNodeWrapper(XmlNode node) { _node = node; } public object WrappedNode { get { return _node; } } public XmlNodeType NodeType { get { return _node.NodeType; } } public string LocalName { get { return _node.LocalName; } } public IList<IXmlNode> ChildNodes { get { return _node.ChildNodes.Cast<XmlNode>().Select(n => WrapNode(n)).ToList(); } } private IXmlNode WrapNode(XmlNode node) { switch (node.NodeType) { case XmlNodeType.Element: return new XmlElementWrapper((XmlElement)node); case XmlNodeType.XmlDeclaration: return new XmlDeclarationWrapper((XmlDeclaration)node); default: return new XmlNodeWrapper(node); } } public IList<IXmlNode> Attributes { get { if (_node.Attributes == null) return null; return _node.Attributes.Cast<XmlAttribute>().Select(a => WrapNode(a)).ToList(); } } public IXmlNode ParentNode { get { XmlNode node = (_node is XmlAttribute) ? ((XmlAttribute)_node).OwnerElement : _node.ParentNode; if (node == null) return null; return WrapNode(node); } } public string Value { get { return _node.Value; } set { _node.Value = value; } } public IXmlNode AppendChild(IXmlNode newChild) { XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper)newChild; _node.AppendChild(xmlNodeWrapper._node); return newChild; } public string NamespaceUri { get { return _node.NamespaceURI; } } } #endif #endregion #region Interfaces internal interface IXmlDocument : IXmlNode { IXmlNode CreateComment(string text); IXmlNode CreateTextNode(string text); IXmlNode CreateCDataSection(string data); IXmlNode CreateWhitespace(string text); IXmlNode CreateSignificantWhitespace(string text); IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); IXmlNode CreateAttribute(string name, string value); IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); IXmlElement DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode { string Version { get; } string Encoding { get; set; } string Standalone { get; set; } } internal interface IXmlElement : IXmlNode { void SetAttributeNode(IXmlNode attribute); string GetPrefixOfNamespace(string namespaceUri); } internal interface IXmlNode { XmlNodeType NodeType { get; } string LocalName { get; } IList<IXmlNode> ChildNodes { get; } IList<IXmlNode> Attributes { get; } IXmlNode ParentNode { get; } string Value { get; set; } IXmlNode AppendChild(IXmlNode newChild); string NamespaceUri { get; } object WrappedNode { get; } } #endregion #region XNodeWrappers #if !NET20 internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration { internal XDeclaration Declaration { get; private set; } public XDeclarationWrapper(XDeclaration declaration) : base(null) { Declaration = declaration; } public override XmlNodeType NodeType { get { return XmlNodeType.XmlDeclaration; } } public string Version { get { return Declaration.Version; } } public string Encoding { get { return Declaration.Encoding; } set { Declaration.Encoding = value; } } public string Standalone { get { return Declaration.Standalone; } set { Declaration.Standalone = value; } } } internal class XDocumentWrapper : XContainerWrapper, IXmlDocument { private XDocument Document { get { return (XDocument)WrappedNode; } } public XDocumentWrapper(XDocument document) : base(document) { } public override IList<IXmlNode> ChildNodes { get { IList<IXmlNode> childNodes = base.ChildNodes; if (Document.Declaration != null) childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration)); return childNodes; } } public IXmlNode CreateComment(string text) { return new XObjectWrapper(new XComment(text)); } public IXmlNode CreateTextNode(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateCDataSection(string data) { return new XObjectWrapper(new XCData(data)); } public IXmlNode CreateWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XElementWrapper(new XElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); } public IXmlElement DocumentElement { get { if (Document.Root == null) return null; return new XElementWrapper(Document.Root); } } public override IXmlNode AppendChild(IXmlNode newChild) { XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper; if (declarationWrapper != null) { Document.Declaration = declarationWrapper.Declaration; return declarationWrapper; } else { return base.AppendChild(newChild); } } } internal class XTextWrapper : XObjectWrapper { private XText Text { get { return (XText)WrappedNode; } } public XTextWrapper(XText text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XCommentWrapper : XObjectWrapper { private XComment Text { get { return (XComment)WrappedNode; } } public XCommentWrapper(XComment text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XProcessingInstructionWrapper : XObjectWrapper { private XProcessingInstruction ProcessingInstruction { get { return (XProcessingInstruction)WrappedNode; } } public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) : base(processingInstruction) { } public override string LocalName { get { return ProcessingInstruction.Target; } } public override string Value { get { return ProcessingInstruction.Data; } set { ProcessingInstruction.Data = value; } } } internal class XContainerWrapper : XObjectWrapper { private XContainer Container { get { return (XContainer)WrappedNode; } } public XContainerWrapper(XContainer container) : base(container) { } public override IList<IXmlNode> ChildNodes { get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); } } public override IXmlNode ParentNode { get { if (Container.Parent == null) return null; return WrapNode(Container.Parent); } } internal static IXmlNode WrapNode(XObject node) { if (node is XDocument) return new XDocumentWrapper((XDocument)node); else if (node is XElement) return new XElementWrapper((XElement)node); else if (node is XContainer) return new XContainerWrapper((XContainer)node); else if (node is XProcessingInstruction) return new XProcessingInstructionWrapper((XProcessingInstruction)node); else if (node is XText) return new XTextWrapper((XText)node); else if (node is XComment) return new XCommentWrapper((XComment)node); else if (node is XAttribute) return new XAttributeWrapper((XAttribute)node); else return new XObjectWrapper(node); } public override IXmlNode AppendChild(IXmlNode newChild) { Container.Add(newChild.WrappedNode); return newChild; } } internal class XObjectWrapper : IXmlNode { private readonly XObject _xmlObject; public XObjectWrapper(XObject xmlObject) { _xmlObject = xmlObject; } public object WrappedNode { get { return _xmlObject; } } public virtual XmlNodeType NodeType { get { return _xmlObject.NodeType; } } public virtual string LocalName { get { return null; } } public virtual IList<IXmlNode> ChildNodes { get { return new List<IXmlNode>(); } } public virtual IList<IXmlNode> Attributes { get { return null; } } public virtual IXmlNode ParentNode { get { return null; } } public virtual string Value { get { return null; } set { throw new InvalidOperationException(); } } public virtual IXmlNode AppendChild(IXmlNode newChild) { throw new InvalidOperationException(); } public virtual string NamespaceUri { get { return null; } } } internal class XAttributeWrapper : XObjectWrapper { private XAttribute Attribute { get { return (XAttribute)WrappedNode; } } public XAttributeWrapper(XAttribute attribute) : base(attribute) { } public override string Value { get { return Attribute.Value; } set { Attribute.Value = value; } } public override string LocalName { get { return Attribute.Name.LocalName; } } public override string NamespaceUri { get { return Attribute.Name.NamespaceName; } } public override IXmlNode ParentNode { get { if (Attribute.Parent == null) return null; return XContainerWrapper.WrapNode(Attribute.Parent); } } } internal class XElementWrapper : XContainerWrapper, IXmlElement { private XElement Element { get { return (XElement)WrappedNode; } } public XElementWrapper(XElement element) : base(element) { } public void SetAttributeNode(IXmlNode attribute) { XObjectWrapper wrapper = (XObjectWrapper)attribute; Element.Add(wrapper.WrappedNode); } public override IList<IXmlNode> Attributes { get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); } } public override string Value { get { return Element.Value; } set { Element.Value = value; } } public override string LocalName { get { return Element.Name.LocalName; } } public override string NamespaceUri { get { return Element.Name.NamespaceName; } } public string GetPrefixOfNamespace(string namespaceUri) { return Element.GetPrefixOfNamespace(namespaceUri); } } #endif #endregion /// <summary> /// Converts XML to and from JSON. /// </summary> public class XmlNodeConverter : JsonConverter { private const string TextName = "#text"; private const string CommentName = "#comment"; private const string CDataName = "#cdata-section"; private const string WhitespaceName = "#whitespace"; private const string SignificantWhitespaceName = "#significant-whitespace"; private const string DeclarationName = "?xml"; private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json"; /// <summary> /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements. /// </summary> /// <value>The name of the deserialize root element.</value> public string DeserializeRootElementName { get; set; } /// <summary> /// Gets or sets a flag to indicate whether to write the Json.NET array attribute. /// This attribute helps preserve arrays when converting the written XML back to JSON. /// </summary> /// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value> public bool WriteArrayAttribute { get; set; } /// <summary> /// Gets or sets a value indicating whether to write the root JSON object. /// </summary> /// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value> public bool OmitRootObject { get; set; } #region Writing /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="serializer">The calling serializer.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IXmlNode node = WrapXml(value); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); PushParentNamespaces(node, manager); if (!OmitRootObject) writer.WriteStartObject(); SerializeNode(writer, node, manager, !OmitRootObject); if (!OmitRootObject) writer.WriteEndObject(); } private IXmlNode WrapXml(object value) { #if !NET20 if (value is XObject) return XContainerWrapper.WrapNode((XObject)value); #endif #if !(NETFX_CORE || PORTABLE) if (value is XmlNode) return new XmlNodeWrapper((XmlNode)value); #endif throw new ArgumentException("Value must be an XML object.", "value"); } private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> parentElements = null; IXmlNode parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) { if (parentElements == null) parentElements = new List<IXmlNode>(); parentElements.Add(parent); } } if (parentElements != null) { parentElements.Reverse(); foreach (IXmlNode parentElement in parentElements) { manager.PushScope(); foreach (IXmlNode attribute in parentElement.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") manager.AddNamespace(attribute.LocalName, attribute.Value); } } } } private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) ? null : manager.LookupPrefix(node.NamespaceUri); if (!string.IsNullOrEmpty(prefix)) return prefix + ":" + node.LocalName; else return node.LocalName; } private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager) { switch (node.NodeType) { case XmlNodeType.Attribute: if (node.NamespaceUri == JsonNamespaceUri) return "$" + node.LocalName; else return "@" + ResolveFullName(node, manager); case XmlNodeType.CDATA: return CDataName; case XmlNodeType.Comment: return CommentName; case XmlNodeType.Element: return ResolveFullName(node, manager); case XmlNodeType.ProcessingInstruction: return "?" + ResolveFullName(node, manager); case XmlNodeType.XmlDeclaration: return DeclarationName; case XmlNodeType.SignificantWhitespace: return SignificantWhitespaceName; case XmlNodeType.Text: return TextName; case XmlNodeType.Whitespace: return WhitespaceName; default: throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType); } } private bool IsArray(IXmlNode node) { IXmlNode jsonArrayAttribute = (node.Attributes != null) ? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri) : null; return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value)); } private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { // group nodes together by name Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>(); for (int i = 0; i < node.ChildNodes.Count; i++) { IXmlNode childNode = node.ChildNodes[i]; string nodeName = GetPropertyName(childNode, manager); List<IXmlNode> nodes; if (!nodesGroupedByName.TryGetValue(nodeName, out nodes)) { nodes = new List<IXmlNode>(); nodesGroupedByName.Add(nodeName, nodes); } nodes.Add(childNode); } // loop through grouped nodes. write single name instances as normal, // write multiple names together in an array foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName) { List<IXmlNode> groupedNodes = nodeNameGroup.Value; bool writeArray; if (groupedNodes.Count == 1) { writeArray = IsArray(groupedNodes[0]); } else { writeArray = true; } if (!writeArray) { SerializeNode(writer, groupedNodes[0], manager, writePropertyName); } else { string elementNames = nodeNameGroup.Key; if (writePropertyName) writer.WritePropertyName(elementNames); writer.WriteStartArray(); for (int i = 0; i < groupedNodes.Count; i++) { SerializeNode(writer, groupedNodes[i], manager, false); } writer.WriteEndArray(); } } } private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Document: case XmlNodeType.DocumentFragment: SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.Element: if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { SerializeGroupedNodes(writer, node, manager, false); } else { manager.PushScope(); foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") ? attribute.LocalName : string.Empty; string namespaceUri = attribute.Value; manager.AddNamespace(namespacePrefix, namespaceUri); } } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) { // empty element writer.WriteNull(); } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { SerializeNode(writer, node.Attributes[i], manager, true); } SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); } break; case XmlNodeType.Comment: if (writePropertyName) writer.WriteComment(node.Value); break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) return; if (node.NamespaceUri == JsonNamespaceUri) { if (node.LocalName == "Array") return; } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration declaration = (IXmlDeclaration)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); } } #endregion #region Reading /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); IXmlDocument document = null; IXmlNode rootNode = null; #if !NET20 if (typeof(XObject).IsAssignableFrom(objectType)) { if (objectType != typeof(XDocument) && objectType != typeof(XElement)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement."); XDocument d = new XDocument(); document = new XDocumentWrapper(d); rootNode = document; } #endif #if !(NETFX_CORE || PORTABLE) if (typeof(XmlNode).IsAssignableFrom(objectType)) { if (objectType != typeof(XmlDocument)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments"); XmlDocument d = new XmlDocument(); document = new XmlDocumentWrapper(d); rootNode = document; } #endif if (document == null || rootNode == null) throw new JsonSerializationException("Unexpected type when converting XML: " + objectType); if (reader.TokenType != JsonToken.StartObject) throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object."); if (!string.IsNullOrEmpty(DeserializeRootElementName)) { //rootNode = document.CreateElement(DeserializeRootElementName); //document.AppendChild(rootNode); ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); } else { reader.Read(); DeserializeNode(reader, document, manager, rootNode); } #if !NET20 if (objectType == typeof(XElement)) { XElement element = (XElement)document.DocumentElement.WrappedNode; element.Remove(); return element; } #endif return document.WrappedNode; } private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode) { switch (propertyName) { case TextName: currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); break; case CDataName: currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); break; case WhitespaceName: currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); break; case SignificantWhitespaceName: currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); break; default: // processing instructions and the xml declaration start with ? if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { CreateInstruction(reader, document, currentNode, propertyName); } else { if (reader.TokenType == JsonToken.StartArray) { // handle nested arrays ReadArrayElements(reader, document, propertyName, currentNode, manager); return; } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element ReadElement(reader, document, currentNode, propertyName, manager); } break; } } private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith("@")) { var attributeName = propertyName.Substring(1); var attributeValue = reader.Value.ToString(); var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); var attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } else { IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } } } private string ConvertTokenToXmlValue(JsonReader reader) { if (reader.TokenType == JsonToken.String) { return reader.Value.ToString(); } else if (reader.TokenType == JsonToken.Integer) { return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Float) { return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Boolean) { return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Date) { DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); #if !(NETFX_CORE || PORTABLE) return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)); #else return XmlConvert.ToString(d); #endif } else if (reader.TokenType == JsonToken.Null) { return null; } else { throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) { string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(nestedArrayElement); int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, nestedArrayElement); count++; } if (WriteArrayAttribute) { AddJsonArrayAttribute(nestedArrayElement, document); } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document) { element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true")); #if !NET20 // linq to xml doesn't automatically include prefixes via the namespace manager if (element is XElementWrapper) { if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null) { element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri)); } } #endif } private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { Dictionary<string, string> attributeNameValues = new Dictionary<string, string>(); bool finishedAttributes = false; bool finishedElement = false; // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; string attributeValue; switch (firstChar) { case '@': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = ConvertTokenToXmlValue(reader); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } break; case '$': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = reader.Value.ToString(); // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { // ensure that the prefix used is free int? i = null; while (manager.LookupNamespace("json" + i) != null) { i = i.GetValueOrDefault() + 1; } jsonPrefix = "json" + i; attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri); manager.AddNamespace(jsonPrefix, JsonNamespaceUri); } attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); break; default: finishedAttributes = true; break; } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } return attributeNameValues; } private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName) { if (propertyName == DeclarationName) { string version = null; string encoding = null; string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@version": reader.Read(); version = reader.Value.ToString(); break; case "@encoding": reader.Read(); encoding = reader.Value.ToString(); break; case "@standalone": reader.Read(); standalone = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); currentNode.AppendChild(instruction); } } private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName); return element; } private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode) { do { switch (reader.TokenType) { case JsonToken.PropertyName: if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); string propertyName = reader.Value.ToString(); reader.Read(); if (reader.TokenType == JsonToken.StartArray) { int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, currentNode); count++; } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } else { DeserializeValue(reader, document, manager, propertyName, currentNode); } break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { DeserializeValue(reader, document, manager, constructorName, currentNode); } break; case JsonToken.Comment: currentNode.AppendChild(document.CreateComment((string)reader.Value)); break; case JsonToken.EndObject: case JsonToken.EndArray: return; default: throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType); } } while (reader.TokenType == JsonToken.PropertyName || reader.Read()); // don't read if current token is a property. token was already read when parsing element attributes } /// <summary> /// Checks if the attributeName is a namespace attribute. /// </summary> /// <param name="attributeName">Attribute name to test.</param> /// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param> /// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns> private bool IsNamespaceAttribute(string attributeName, out string prefix) { if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) { if (attributeName.Length == 5) { prefix = string.Empty; return true; } else if (attributeName[5] == ':') { prefix = attributeName.Substring(6, attributeName.Length - 6); return true; } } prefix = null; return false; } private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c) { return c.Where(a => a.NamespaceUri != JsonNamespaceUri); } #endregion /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { #if !NET20 if (typeof(XObject).IsAssignableFrom(valueType)) return true; #endif #if !(NETFX_CORE || PORTABLE) if (typeof(XmlNode).IsAssignableFrom(valueType)) return true; #endif return false; } } } #endif
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.IO; using System.Text; using System.Xml.Linq; using System.Linq; using System.Xml; using System.Collections.Generic; using System.Globalization; using Kodestruct.Common.Maps; using Kodestruct.Common.Data; using Kodestruct.Common.Mathematics; namespace Kodestruct.Common.MapData { public class PolylineReader { public static List<MapPolyline> ReadPolylineData(string stringData, string LayerName) { List<MapPolyline> Polylines = new List<MapPolyline>(); string aLine = null; int polyIterator = 0; var polydata = new { AttributeData = "", XData = "", YData = "" }; // sample var polyList = ListFactory.MakeList(polydata); string attrDat = null; string xDat = null; string yDat = null; StringReader strReader = new StringReader(stringData); while (true) { aLine = strReader.ReadLine(); if (aLine != null) { polyIterator++; polyIterator = polyIterator > 3 ? 1 : polyIterator; switch (polyIterator) { case 1: attrDat = aLine; break; case 2: xDat = aLine; break; case 3: yDat = aLine; polyList.Add(new { AttributeData = attrDat, XData = xDat, YData = yDat }); attrDat = null; xDat = null; yDat = null; break; } } else { //process all the data if (polyList.Count > 1) { foreach (var polyDatElem in polyList) { MapPolyline polyline = new MapPolyline(); polyline.Locations = new LocationCollection(); string[] attVals = polyDatElem.AttributeData.Split(','); // not used for now, use later for lineweight an annotation string[] xVals = polyDatElem.XData.Split(','); string[] yVals = polyDatElem.YData.Split(','); if (xVals.Length == yVals.Length) { for (int i = 0; i < xVals.Length; i++) { double x; double y; if (Double.TryParse(xVals[i], out x) && Double.TryParse(yVals[i], out y)) // if done, then is a number { Location thisLoc = new Location(x, y); polyline.Locations.Add(thisLoc); } } Polylines.Add(polyline); } else { throw new Exception("Number of X coordinates and Y coordinates in data does not match"); } } } break; } } return Polylines; } public static List<MapAnalyticalPolygon> ReadAnalyticalPolygonData(XDocument xmlString) { List<MapAnalyticalPolygon> polygonData = new List<MapAnalyticalPolygon>(); var collection = from nod in xmlString.Descendants("MultiPolygon") select nod; foreach (var multiPolygon in collection) { MapAnalyticalPolygon ap = new MapAnalyticalPolygon(); List<LocationCollection> innerLoops = new List<LocationCollection>(); LocationCollection outerLoop = new LocationCollection(); var Loops = from poly in multiPolygon.Descendants("Polygon") select poly; var LoopList = multiPolygon.Descendants("Polygon") .Select(p => GetLocationData(p.Value)) .ToList(); if (LoopList.Count==1) { ap.OuterLoop = LoopList[0]; } else { for (int i = 0; i < LoopList.Count; i++) { var poly = LoopList[i]; bool IsOuter = DetermineIfPolygonIsOuter(poly, LoopList,i); if (IsOuter == true) { ap.OuterLoop = poly; } else { ap.InnerLoops.Add(poly); } } } ap.ObjectId = multiPolygon.Attribute("ObjectId").Value; polygonData.Add(ap); } return polygonData; } private static bool DetermineIfPolygonIsOuter(LocationCollection poly, List<LocationCollection> LoopList, int currentIndex) { //Assumption is that all points are inside. //therefore it is necessary to only test one point bool IsInside = false; bool FoundPolyOutsideThisOne = false; Location point = poly[0]; for (int i = 0; i < LoopList.Count; i++) { if (i!=currentIndex) // make sure to exclude current loop from checking { LocationCollection loop = LoopList[i]; IsInside = PolygonLocationChecking.IsLocationInComplexPolygon(loop, null, point); if (IsInside == true) { FoundPolyOutsideThisOne = true; break; } } } if (FoundPolyOutsideThisOne==true) { return false; } else { return true; } } public static List<MapMultiPolygon> ReadPolygonData(XDocument xmlString) { List<MapMultiPolygon> polygonData = new List<MapMultiPolygon>(); var collection = from nod in xmlString.Descendants("MultiPolygon") select nod; foreach (var multiPolygon in collection) { List<LocationCollection> points = new List<LocationCollection>(); var Loops = from poly in multiPolygon.Descendants("Polygon") select poly; foreach (var polygon in Loops) { LocationCollection locations = GetLocationData(polygon.Value); points.Add(locations); } MapMultiPolygon multiP = new MapMultiPolygon(); var IdAtt = multiPolygon.Attribute("ObjectId"); multiP.ObjectId = IdAtt.Value; multiP.Vertices = points; polygonData.Add(multiP); } return polygonData; } private static LocationCollection GetLocationData(string coordinateStringData) { LocationCollection locations = new LocationCollection(); string[] coordVals = coordinateStringData.Split(','); int numberOfCoordEntries = coordVals.Length; double Latitude, Longitude; if ( numberOfCoordEntries % 2 == 0 ) { for (int i = 0; i < coordVals.Length; i++) { if (i % 2 == 0) { Latitude = double.Parse(coordVals[i], CultureInfo.InvariantCulture); Longitude = double.Parse(coordVals[i + 1], CultureInfo.InvariantCulture); Location l = new Location(Latitude, Longitude); locations.Add(l); } } } return locations; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using ZocMonLib; using ZocUtil; namespace Infrastructure { //helper class for cache public class CacheZocMon { //zocmon data cache private static IDictionary<string, CacheZocMon> _cache = new ConcurrentDictionary<string, CacheZocMon>(); public DateTime Newest { get; set; } public ZocMonGraph.BaseReduceLevels ReduceLevel { get; set; } public List<MonitorRecordUnion<double>> Data { get; set; } public TimeSpan Overlap { get; set; } public string Name { get; set; } public bool WarmedUp { get; set; } public DateTime LastRefreshed { get; set; } //TODO public DateTime LastAccessed { get; set; } #region non-static functionality private CacheZocMon(string tableName, ZocMonGraph.BaseReduceLevels reduceLevel) { switch (reduceLevel) { case ZocMonGraph.BaseReduceLevels.Minutely: Overlap = new TimeSpan(0, -4, 0); break; case ZocMonGraph.BaseReduceLevels.FiveMinutely: Overlap = new TimeSpan(0, -10, 0); break; case ZocMonGraph.BaseReduceLevels.Hourly: Overlap = new TimeSpan(-2, 0, 0); break; case ZocMonGraph.BaseReduceLevels.Daily: Overlap = new TimeSpan(-2, 0, 0, 0); break; } Name = tableName; Data = new List<MonitorRecordUnion<double>>(); WarmedUp = false; LastRefreshed = DateTime.MinValue; } private DateTime GetLastUpdatedTime() { return Newest.Add(Overlap); } #endregion #region static functionality private static void RefreshFromDb(IEnumerable<string> tables, ZDSqlConnection conn) { var metas = new List<Tuple<string, TimeRange>>(); try { foreach (string table in tables) { if (!_cache.ContainsKey(table)) { //make sure this is a real table before adding it to the cache var sql = "SELECT Count(1) FROM ReduceLevel WHERE DataTableName = @table"; if (SqlHelper.ExecuteScalarWithConnection<int>(conn, sql, new { table } ) > 0) { _cache.Add(table, new CacheZocMon(table, ZocMonGraph.GetReduceLevelFromTable(table))); } else { continue; } } metas.Add(new Tuple<string, TimeRange>(table, _cache[table].WarmedUp ? new TimeRange { Start = _cache[table].GetLastUpdatedTime(), End = DateTime.Now } : new TimeRange { Start = DateTime.Today.AddDays(-30), End = DateTime.Now })); } if (metas.Count > 0) { var data = ZocMon.GetDataUnion(metas, conn, true); var logString = new StringBuilder(); if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("This Refresh at " + DateTime.Now + " with " + metas.Count + " tables to refresh: \n"); } //if this is a refresh and not a warmup, log long intervals if (_cache[metas[0].Item1].WarmedUp && _cache[metas[0].Item1].LastRefreshed < DateTime.Now.AddMinutes(-2)) { SimpleLogger.logInformation("Time between ZocMon refreshes on " + Environment.MachineName + " was " + (DateTime.Now - _cache[metas[0].Item1].LastRefreshed).TotalMinutes + " minutes.", to: "matthew.murchison@zocdoc.com"); } foreach (var results in data) { if (results.Value.Count > 0) { var table = results.Value.First().Source; List<MonitorRecordUnion<double>> resultsLoc = results.Value; if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("Table: " + table + "\n"); logString.Append("results length before removing overlap: " + _cache[table].Data.Count + "\n"); } //remove overlapping data _cache[table].Data.RemoveAll(x => x.TimeStamp >= resultsLoc.First().TimeStamp); if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("results length after removing overlap: " + _cache[table].Data.Count + "\n"); } //concat new data to old _cache[table].Data = _cache[table].Data.Concat(results.Value).ToList(); if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("old newest: " + _cache[table].Newest ?? "null" + "\n"); } _cache[table].Newest = _cache[table].Data.Last().TimeStamp; if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("new newest: " + _cache[table].Newest ?? "null" + "\n"); } //set warmed up if (!_cache[table].WarmedUp) { if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("this was a warmup \n"); } _cache[table].WarmedUp = true; } else { if (new Flag_ZocMonSuperLog().Enabled()) { logString.Append("this was a refresh \n"); } } _cache[table].LastRefreshed = DateTime.Now; } } if (new Flag_ZocMonSuperLog().Enabled()) { SimpleLogger.logInformation(logString.ToString(), to: "matthew.murchison@zocdoc.com"); } } } catch (Exception e) { SimpleLogger.logException(e, to: "matthew.murchison@zocdoc.com"); } } //tuple represents "name of table" and "time range data is needed for" public static Dictionary<string, List<MonitorRecordUnion<double>>> GetData(List<Tuple<string, TimeRange>> metas, ZDSqlConnection conn) { var needingRefresh = metas.Select(x => x.Item1).Where(s => !_cache.ContainsKey(s)).ToList(); if (needingRefresh.Count > 0) { RefreshFromDb(needingRefresh, conn); } var ret = new Dictionary<string, List<MonitorRecordUnion<double>>>(); foreach (var meta in metas) { if (!_cache.ContainsKey(meta.Item1)) { continue; } var dataForMeta = new List<MonitorRecordUnion<double>>(); for (int i = 0; i < _cache[meta.Item1].Data.Count; i++) { if (_cache[meta.Item1].Data[i].TimeStamp >= meta.Item2.Start && _cache[meta.Item1].Data[i].TimeStamp <= meta.Item2.End) { dataForMeta.Add(_cache[meta.Item1].Data[i]); } } if (ret.ContainsKey(meta.Item1)) { ret[meta.Item1].AddRange(dataForMeta); } else { ret.Add(meta.Item1, dataForMeta); } } return ret; } public static void RefreshAll() { using (ZDSqlConnection conn = Sql.GetLogConnection()) { conn.Open(); var needingRefresh = _cache.Values.Select(x => x.Name).ToList(); if (needingRefresh.Count > 0) { RefreshFromDb(needingRefresh, conn); } } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache.Platform { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; /// <summary> /// Holds platform cache data for a given cache, serves one or more <see cref="CacheImpl{TK,TV}"/> instances. /// </summary> internal sealed class PlatformCache<TK, TV> : IPlatformCache { /** Affinity. */ private readonly CacheAffinityManager _affinity; /** Keep binary flag. */ private readonly bool _keepBinary; /** Topology version func. Returns boxed <see cref="AffinityTopologyVersion"/>. * Boxed copy is passed directly to <see cref="PlatformCacheEntry{T}"/>, avoiding extra allocations. * This way for every unique <see cref="AffinityTopologyVersion"/> we only have one boxed copy, * and we can update <see cref="PlatformCacheEntry{T}.Version"/> atomically without locks. */ private readonly Func<object> _affinityTopologyVersionFunc; /** Underlying map. */ private readonly ConcurrentDictionary<TK, PlatformCacheEntry<TV>> _map = new ConcurrentDictionary<TK, PlatformCacheEntry<TV>>(); /** Stopped flag. */ private volatile bool _stopped; /// <summary> /// Initializes a new instance of the <see cref="PlatformCache{TK,TV}"/> class. /// Called via reflection from <see cref="PlatformCacheManager.CreatePlatformCache"/>. /// </summary> public PlatformCache(Func<object> affinityTopologyVersionFunc, CacheAffinityManager affinity, bool keepBinary) { _affinityTopologyVersionFunc = affinityTopologyVersionFunc; _affinity = affinity; _keepBinary = keepBinary; } /** <inheritdoc /> */ public bool IsStopped { get { return _stopped; } } /** <inheritdoc /> */ public bool TryGetValue<TKey, TVal>(TKey key, out TVal val) { if (_stopped) { val = default(TVal); return false; } PlatformCacheEntry<TV> entry; var key0 = (TK) (object) key; if (_map.TryGetValue(key0, out entry)) { if (IsValid(entry)) { val = (TVal) (object) entry.Value; return true; } // Remove invalid entry to free up memory. // NOTE: We may end up removing a good entry that was inserted concurrently, // but this does not violate correctness, only causes a potential platform cache miss. _map.TryRemove(key0, out entry); } val = default(TVal); return false; } /** <inheritdoc /> */ public int GetSize(int? partition) { if (_stopped) { return 0; } var count = 0; foreach (var e in _map) { if (!IsValid(e.Value)) { continue; } if (partition != null && e.Value.Partition != partition) { continue; } count++; } return count; } /** <inheritdoc /> */ public void Update(IBinaryStream stream, Marshaller marshaller) { Debug.Assert(stream != null); Debug.Assert(marshaller != null); if (_stopped) { return; } var mode = _keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize; var reader = marshaller.StartUnmarshal(stream, mode); var key = reader.ReadObject<TK>(); var hasVal = stream.ReadBool(); if (hasVal) { var val = reader.ReadObject<TV>(); var part = stream.ReadInt(); var ver = new AffinityTopologyVersion(stream.ReadLong(), stream.ReadInt()); _map[key] = new PlatformCacheEntry<TV>(val, GetBoxedAffinityTopologyVersion(ver), part); } else { PlatformCacheEntry<TV> unused; _map.TryRemove(key, out unused); } } /** <inheritdoc /> */ public void UpdateFromThreadLocal(int partition, AffinityTopologyVersion affinityTopologyVersion) { if (_stopped) { return; } var pair = (KeyValuePair<TK, TV>) PlatformCacheManager.ThreadLocalPair.Value; _map[pair.Key] = new PlatformCacheEntry<TV>( pair.Value, GetBoxedAffinityTopologyVersion(affinityTopologyVersion), partition); } /** <inheritdoc /> */ public void Stop() { _stopped = true; Clear(); } /** <inheritdoc /> */ public void Clear() { _map.Clear(); } /** <inheritdoc /> */ public void SetThreadLocalPair<TKey, TVal>(TKey key, TVal val) { PlatformCacheManager.ThreadLocalPair.Value = new KeyValuePair<TK, TV>((TK) (object) key, (TV) (object) val); } /** <inheritdoc /> */ public void ResetThreadLocalPair() { PlatformCacheManager.ThreadLocalPair.Value = null; } /** <inheritdoc /> */ public IEnumerable<ICacheEntry<TKey, TVal>> GetEntries<TKey, TVal>(int? partition) { if (_stopped) { yield break; } foreach (var e in _map) { if (partition != null && e.Value.Partition != partition) { continue; } if (!IsValid(e.Value)) { continue; } yield return new CacheEntry<TKey, TVal>((TKey) (object) e.Key, (TVal) (object) e.Value.Value); } } /// <summary> /// Checks whether specified cache entry is still valid, based on Affinity Topology Version. /// When primary node changes for a key, GridNearCacheEntry stops receiving updates for that key, /// because reader ("subscription") on new primary is not yet established. /// <para /> /// This method is similar to GridNearCacheEntry.valid(). /// </summary> /// <param name="entry">Entry to validate.</param> /// <typeparam name="TVal">Value type.</typeparam> /// <returns>True if entry is valid and can be returned to the user; false otherwise.</returns> private bool IsValid<TVal>(PlatformCacheEntry<TVal> entry) { // See comments on _affinityTopologyVersionFunc about boxed copy approach. var currentVerBoxed = _affinityTopologyVersionFunc(); var entryVerBoxed = entry.Version; if (entryVerBoxed == null || currentVerBoxed == null) { return false; } if (ReferenceEquals(currentVerBoxed, entryVerBoxed)) { // Happy path: true on stable topology. return true; } var entryVer = (AffinityTopologyVersion) entryVerBoxed; var currentVer = (AffinityTopologyVersion) currentVerBoxed; if (entryVer >= currentVer) { return true; } var part = entry.Partition; var valid = _affinity.IsAssignmentValid(entryVer, part); // Update version or mark as invalid (null). entry.CompareExchangeVersion(valid ? currentVerBoxed : null, entryVerBoxed); return valid; } /// <summary> /// Gets boxed affinity version. Reuses existing boxing copy to reduce allocations. /// </summary> private object GetBoxedAffinityTopologyVersion(AffinityTopologyVersion ver) { var currentVerBoxed = _affinityTopologyVersionFunc(); return currentVerBoxed != null && (AffinityTopologyVersion) currentVerBoxed == ver ? currentVerBoxed : ver; } } }
using System; using System.Diagnostics; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using NumericUtils = Lucene.Net.Util.NumericUtils; using SortedDocValues = Lucene.Net.Index.SortedDocValues; /// <summary> /// A range filter built on top of a cached single term field (in <see cref="IFieldCache"/>). /// /// <para/><see cref="FieldCacheRangeFilter"/> builds a single cache for the field the first time it is used. /// Each subsequent <see cref="FieldCacheRangeFilter"/> on the same field then reuses this cache, /// even if the range itself changes. /// /// <para/>this means that <see cref="FieldCacheRangeFilter"/> is much faster (sometimes more than 100x as fast) /// as building a <see cref="TermRangeFilter"/>, if using a <see cref="NewStringRange(string, string, string, bool, bool)"/>. /// However, if the range never changes it is slower (around 2x as slow) than building /// a <see cref="CachingWrapperFilter"/> on top of a single <see cref="TermRangeFilter"/>. /// /// <para/>For numeric data types, this filter may be significantly faster than <see cref="NumericRangeFilter"/>. /// Furthermore, it does not need the numeric values encoded /// by <see cref="Documents.Int32Field"/>, <see cref="Documents.SingleField"/>, /// <see cref="Documents.Int64Field"/> or <see cref="Documents.DoubleField"/>. But /// it has the problem that it only works with exact one value/document (see below). /// /// <para/>As with all <see cref="IFieldCache"/> based functionality, <see cref="FieldCacheRangeFilter"/> is only valid for /// fields which exact one term for each document (except for <see cref="NewStringRange(string, string, string, bool, bool)"/> /// where 0 terms are also allowed). Due to a restriction of <see cref="IFieldCache"/>, for numeric ranges /// all terms that do not have a numeric value, 0 is assumed. /// /// <para/>Thus it works on dates, prices and other single value fields but will not work on /// regular text fields. It is preferable to use a <see cref="Documents.Field.Index.NOT_ANALYZED"/> field to ensure that /// there is only a single term. /// /// <para/>This class does not have an constructor, use one of the static factory methods available, /// that create a correct instance for different data types supported by <see cref="IFieldCache"/>. /// </summary> public static class FieldCacheRangeFilter { #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousStringFieldCacheRangeFilter : FieldCacheRangeFilter<string> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private SortedDocValues fcsi; private int inclusiveLowerPoint; private int inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(SortedDocValues fcsi, int inclusiveLowerPoint, int inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.fcsi = fcsi; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { int docOrd = fcsi.GetOrd(doc); return docOrd >= inclusiveLowerPoint && docOrd <= inclusiveUpperPoint; } } internal AnonymousStringFieldCacheRangeFilter(string field, string lowerVal, string upperVal, bool includeLower, bool includeUpper) : base(field, null, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { SortedDocValues fcsi = FieldCache.DEFAULT.GetTermsIndex(context.AtomicReader, field); int lowerPoint = lowerVal == null ? -1 : fcsi.LookupTerm(new BytesRef(lowerVal)); int upperPoint = upperVal == null ? -1 : fcsi.LookupTerm(new BytesRef(upperVal)); int inclusiveLowerPoint, inclusiveUpperPoint; // Hints: // * binarySearchLookup returns 0, if value was null. // * the value is <0 if no exact hit was found, the returned value // is (-(insertion point) - 1) if (lowerPoint == -1 && lowerVal == null) { inclusiveLowerPoint = 0; } else if (includeLower && lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint; } else if (lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint + 1; } else { inclusiveLowerPoint = Math.Max(0, -lowerPoint - 1); } if (upperPoint == -1 && upperVal == null) { inclusiveUpperPoint = int.MaxValue; } else if (includeUpper && upperPoint >= 0) { inclusiveUpperPoint = upperPoint; } else if (upperPoint >= 0) { inclusiveUpperPoint = upperPoint - 1; } else { inclusiveUpperPoint = -upperPoint - 2; } if (inclusiveUpperPoint < 0 || inclusiveLowerPoint > inclusiveUpperPoint) { return null; } Debug.Assert(inclusiveLowerPoint >= 0 && inclusiveUpperPoint >= 0); return new AnonymousClassFieldCacheDocIdSet(fcsi, inclusiveLowerPoint, inclusiveUpperPoint, context.Reader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousBytesRefFieldCacheRangeFilter : FieldCacheRangeFilter<BytesRef> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private SortedDocValues fcsi; private int inclusiveLowerPoint; private int inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(SortedDocValues fcsi, int inclusiveLowerPoint, int inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.fcsi = fcsi; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { int docOrd = fcsi.GetOrd(doc); return docOrd >= inclusiveLowerPoint && docOrd <= inclusiveUpperPoint; } } internal AnonymousBytesRefFieldCacheRangeFilter(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) : base(field, null, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { SortedDocValues fcsi = FieldCache.DEFAULT.GetTermsIndex(context.AtomicReader, field); int lowerPoint = lowerVal == null ? -1 : fcsi.LookupTerm(lowerVal); int upperPoint = upperVal == null ? -1 : fcsi.LookupTerm(upperVal); int inclusiveLowerPoint, inclusiveUpperPoint; // Hints: // * binarySearchLookup returns -1, if value was null. // * the value is <0 if no exact hit was found, the returned value // is (-(insertion point) - 1) if (lowerPoint == -1 && lowerVal == null) { inclusiveLowerPoint = 0; } else if (includeLower && lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint; } else if (lowerPoint >= 0) { inclusiveLowerPoint = lowerPoint + 1; } else { inclusiveLowerPoint = Math.Max(0, -lowerPoint - 1); } if (upperPoint == -1 && upperVal == null) { inclusiveUpperPoint = int.MaxValue; } else if (includeUpper && upperPoint >= 0) { inclusiveUpperPoint = upperPoint; } else if (upperPoint >= 0) { inclusiveUpperPoint = upperPoint - 1; } else { inclusiveUpperPoint = -upperPoint - 2; } if (inclusiveUpperPoint < 0 || inclusiveLowerPoint > inclusiveUpperPoint) { return null; ; } //assert inclusiveLowerPoint >= 0 && inclusiveUpperPoint >= 0; return new AnonymousClassFieldCacheDocIdSet(fcsi, inclusiveLowerPoint, inclusiveUpperPoint, context.AtomicReader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousSbyteFieldCacheRangeFilter : FieldCacheRangeFilter<sbyte?> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private FieldCache.Bytes values; private sbyte inclusiveLowerPoint; private sbyte inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(FieldCache.Bytes values, sbyte inclusiveLowerPoint, sbyte inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.values = values; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { sbyte value = (sbyte)values.Get(doc); return value >= inclusiveLowerPoint && value <= inclusiveUpperPoint; } } internal AnonymousSbyteFieldCacheRangeFilter(string field, FieldCache.IParser parser, sbyte? lowerVal, sbyte? upperVal, bool includeLower, bool includeUpper) : base(field, parser, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { sbyte inclusiveLowerPoint, inclusiveUpperPoint; if (lowerVal != null) { sbyte i = (sbyte)lowerVal; if (!includeLower && i == sbyte.MaxValue) return null; inclusiveLowerPoint = (sbyte)(includeLower ? i : (i + 1)); } else { inclusiveLowerPoint = sbyte.MinValue; } if (upperVal != null) { sbyte i = (sbyte)upperVal; if (!includeUpper && i == sbyte.MinValue) return null; inclusiveUpperPoint = (sbyte)(includeUpper ? i : (i - 1)); } else { inclusiveUpperPoint = sbyte.MaxValue; } if (inclusiveLowerPoint > inclusiveUpperPoint) return null; #pragma warning disable 612, 618 var values = FieldCache.DEFAULT.GetBytes(context.AtomicReader, field, (FieldCache.IByteParser)parser, false); #pragma warning restore 612, 618 // we only request the usage of termDocs, if the range contains 0 return new AnonymousClassFieldCacheDocIdSet(values, inclusiveLowerPoint, inclusiveUpperPoint, context.AtomicReader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousInt16FieldCacheRangeFilter : FieldCacheRangeFilter<short?> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private FieldCache.Int16s values; private short inclusiveLowerPoint; private short inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(FieldCache.Int16s values, short inclusiveLowerPoint, short inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.values = values; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { short value = values.Get(doc); return value >= inclusiveLowerPoint && value <= inclusiveUpperPoint; } } internal AnonymousInt16FieldCacheRangeFilter(string field, FieldCache.IParser parser, short? lowerVal, short? upperVal, bool includeLower, bool includeUpper) : base(field, parser, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { short inclusiveLowerPoint, inclusiveUpperPoint; if (lowerVal != null) { short i = (short)lowerVal; if (!includeLower && i == short.MaxValue) return null; inclusiveLowerPoint = (short)(includeLower ? i : (i + 1)); } else { inclusiveLowerPoint = short.MinValue; } if (upperVal != null) { short i = (short)upperVal; if (!includeUpper && i == short.MinValue) return null; inclusiveUpperPoint = (short)(includeUpper ? i : (i - 1)); } else { inclusiveUpperPoint = short.MaxValue; } if (inclusiveLowerPoint > inclusiveUpperPoint) return null; #pragma warning disable 612, 618 FieldCache.Int16s values = FieldCache.DEFAULT.GetInt16s(context.AtomicReader, field, (FieldCache.IInt16Parser)parser, false); #pragma warning restore 612, 618 // we only request the usage of termDocs, if the range contains 0 return new AnonymousClassFieldCacheDocIdSet(values, inclusiveLowerPoint, inclusiveUpperPoint, context.Reader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousInt32FieldCacheRangeFilter : FieldCacheRangeFilter<int?> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private FieldCache.Int32s values; private int inclusiveLowerPoint; private int inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(FieldCache.Int32s values, int inclusiveLowerPoint, int inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.values = values; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { int value = values.Get(doc); return value >= inclusiveLowerPoint && value <= inclusiveUpperPoint; } } internal AnonymousInt32FieldCacheRangeFilter(string field, FieldCache.IParser parser, int? lowerVal, int? upperVal, bool includeLower, bool includeUpper) : base(field, parser, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { int inclusiveLowerPoint, inclusiveUpperPoint; if (lowerVal != null) { int i = (int)lowerVal; if (!includeLower && i == int.MaxValue) return null; inclusiveLowerPoint = includeLower ? i : (i + 1); } else { inclusiveLowerPoint = int.MinValue; } if (upperVal != null) { int i = (int)upperVal; if (!includeUpper && i == int.MinValue) return null; inclusiveUpperPoint = includeUpper ? i : (i - 1); } else { inclusiveUpperPoint = int.MaxValue; } if (inclusiveLowerPoint > inclusiveUpperPoint) return null; FieldCache.Int32s values = FieldCache.DEFAULT.GetInt32s(context.AtomicReader, field, (FieldCache.IInt32Parser)parser, false); // we only request the usage of termDocs, if the range contains 0 return new AnonymousClassFieldCacheDocIdSet(values, inclusiveLowerPoint, inclusiveUpperPoint, context.Reader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousInt64FieldCacheRangeFilter : FieldCacheRangeFilter<long?> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private FieldCache.Int64s values; private long inclusiveLowerPoint; private long inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(FieldCache.Int64s values, long inclusiveLowerPoint, long inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.values = values; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { long value = values.Get(doc); return value >= inclusiveLowerPoint && value <= inclusiveUpperPoint; } } internal AnonymousInt64FieldCacheRangeFilter(string field, FieldCache.IParser parser, long? lowerVal, long? upperVal, bool includeLower, bool includeUpper) : base(field, parser, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { long inclusiveLowerPoint, inclusiveUpperPoint; if (lowerVal != null) { long i = (long)lowerVal; if (!includeLower && i == long.MaxValue) return null; inclusiveLowerPoint = includeLower ? i : (i + 1L); } else { inclusiveLowerPoint = long.MinValue; } if (upperVal != null) { long i = (long)upperVal; if (!includeUpper && i == long.MinValue) return null; inclusiveUpperPoint = includeUpper ? i : (i - 1L); } else { inclusiveUpperPoint = long.MaxValue; } if (inclusiveLowerPoint > inclusiveUpperPoint) return null; FieldCache.Int64s values = FieldCache.DEFAULT.GetInt64s(context.AtomicReader, field, (FieldCache.IInt64Parser)parser, false); // we only request the usage of termDocs, if the range contains 0 return new AnonymousClassFieldCacheDocIdSet(values, inclusiveLowerPoint, inclusiveUpperPoint, context.Reader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousSingleFieldCacheRangeFilter : FieldCacheRangeFilter<float?> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private FieldCache.Singles values; private float inclusiveLowerPoint; private float inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(FieldCache.Singles values, float inclusiveLowerPoint, float inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.values = values; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { float value = values.Get(doc); return value >= inclusiveLowerPoint && value <= inclusiveUpperPoint; } } internal AnonymousSingleFieldCacheRangeFilter(string field, FieldCache.IParser parser, float? lowerVal, float? upperVal, bool includeLower, bool includeUpper) : base(field, parser, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { // we transform the floating point numbers to sortable integers // using NumericUtils to easier find the next bigger/lower value float inclusiveLowerPoint; float inclusiveUpperPoint; if (lowerVal != null) { float f = (float)lowerVal; if (!includeUpper && f > 0.0f && float.IsInfinity(f)) return null; int i = NumericUtils.SingleToSortableInt32(f); inclusiveLowerPoint = NumericUtils.SortableInt32ToSingle(includeLower ? i : (i + 1)); } else { inclusiveLowerPoint = float.NegativeInfinity; } if (upperVal != null) { float f = (float)upperVal; if (!includeUpper && f < 0.0f && float.IsInfinity(f)) return null; int i = NumericUtils.SingleToSortableInt32(f); inclusiveUpperPoint = NumericUtils.SortableInt32ToSingle(includeUpper ? i : (i - 1)); } else { inclusiveUpperPoint = float.PositiveInfinity; } if (inclusiveLowerPoint > inclusiveUpperPoint) return null; FieldCache.Singles values = FieldCache.DEFAULT.GetSingles(context.AtomicReader, field, (FieldCache.ISingleParser)parser, false); // we only request the usage of termDocs, if the range contains 0 return new AnonymousClassFieldCacheDocIdSet(values, inclusiveLowerPoint, inclusiveUpperPoint, context.Reader.MaxDoc, acceptDocs); } } #if FEATURE_SERIALIZABLE [Serializable] #endif private class AnonymousDoubleFieldCacheRangeFilter : FieldCacheRangeFilter<double?> { private class AnonymousClassFieldCacheDocIdSet : FieldCacheDocIdSet { private FieldCache.Doubles values; private double inclusiveLowerPoint; private double inclusiveUpperPoint; internal AnonymousClassFieldCacheDocIdSet(FieldCache.Doubles values, double inclusiveLowerPoint, double inclusiveUpperPoint, int maxDoc, IBits acceptDocs) : base(maxDoc, acceptDocs) { this.values = values; this.inclusiveLowerPoint = inclusiveLowerPoint; this.inclusiveUpperPoint = inclusiveUpperPoint; } protected internal override bool MatchDoc(int doc) { double value = values.Get(doc); return value >= inclusiveLowerPoint && value <= inclusiveUpperPoint; } } internal AnonymousDoubleFieldCacheRangeFilter(string field, FieldCache.IParser parser, double? lowerVal, double? upperVal, bool includeLower, bool includeUpper) : base(field, parser, lowerVal, upperVal, includeLower, includeUpper) { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { // we transform the floating point numbers to sortable integers // using NumericUtils to easier find the next bigger/lower value double inclusiveLowerPoint; double inclusiveUpperPoint; if (lowerVal != null) { double f = (double)lowerVal; if (!includeUpper && f > 0.0 && double.IsInfinity(f)) return null; long i = NumericUtils.DoubleToSortableInt64(f); inclusiveLowerPoint = NumericUtils.SortableInt64ToDouble(includeLower ? i : (i + 1L)); } else { inclusiveLowerPoint = double.NegativeInfinity; } if (upperVal != null) { double f = (double)upperVal; if (!includeUpper && f < 0.0 && double.IsInfinity(f)) return null; long i = NumericUtils.DoubleToSortableInt64(f); inclusiveUpperPoint = NumericUtils.SortableInt64ToDouble(includeUpper ? i : (i - 1L)); } else { inclusiveUpperPoint = double.PositiveInfinity; } if (inclusiveLowerPoint > inclusiveUpperPoint) return null; FieldCache.Doubles values = FieldCache.DEFAULT.GetDoubles(context.AtomicReader, field, (FieldCache.IDoubleParser)parser, false); // we only request the usage of termDocs, if the range contains 0 return new AnonymousClassFieldCacheDocIdSet(values, inclusiveLowerPoint, inclusiveUpperPoint, context.Reader.MaxDoc, acceptDocs); } } //The functions (Starting on line 84 in Lucene) /// <summary> /// Creates a string range filter using <see cref="IFieldCache.GetTermsIndex(Index.AtomicReader, string, float)"/>. This works with all /// fields containing zero or one term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> public static FieldCacheRangeFilter<string> NewStringRange(string field, string lowerVal, string upperVal, bool includeLower, bool includeUpper) { return new AnonymousStringFieldCacheRangeFilter(field, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a <see cref="BytesRef"/> range filter using <see cref="IFieldCache.GetTermsIndex(Index.AtomicReader, string, float)"/>. This works with all /// fields containing zero or one term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> // TODO: bogus that newStringRange doesnt share this code... generics hell public static FieldCacheRangeFilter<BytesRef> NewBytesRefRange(string field, BytesRef lowerVal, BytesRef upperVal, bool includeLower, bool includeUpper) { return new AnonymousBytesRefFieldCacheRangeFilter(field, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetBytes(Index.AtomicReader,string,bool)"/>. This works with all /// <see cref="byte"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> [Obsolete, CLSCompliant(false)] // LUCENENET NOTE: marking non-CLS compliant because it is sbyte, but obsolete anyway public static FieldCacheRangeFilter<sbyte?> NewByteRange(string field, sbyte? lowerVal, sbyte? upperVal, bool includeLower, bool includeUpper) { return NewByteRange(field, null, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetBytes(Index.AtomicReader,string,FieldCache.IByteParser,bool)"/>. This works with all /// <see cref="byte"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> [Obsolete, CLSCompliant(false)] // LUCENENET NOTE: marking non-CLS compliant because it is sbyte, but obsolete anyway public static FieldCacheRangeFilter<sbyte?> NewByteRange(string field, FieldCache.IByteParser parser, sbyte? lowerVal, sbyte? upperVal, bool includeLower, bool includeUpper) { return new AnonymousSbyteFieldCacheRangeFilter(field, parser, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetInt16s(Index.AtomicReader,string,bool)"/>. This works with all /// <see cref="short"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newShortRange() in Lucene /// </summary> [Obsolete] public static FieldCacheRangeFilter<short?> NewInt16Range(string field, short? lowerVal, short? upperVal, bool includeLower, bool includeUpper) { return NewInt16Range(field, null, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetInt16s(Index.AtomicReader, string, FieldCache.IInt16Parser, bool)"/>. This works with all /// <see cref="short"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newShortRange() in Lucene /// </summary> [Obsolete] public static FieldCacheRangeFilter<short?> NewInt16Range(string field, FieldCache.IInt16Parser parser, short? lowerVal, short? upperVal, bool includeLower, bool includeUpper) { return new AnonymousInt16FieldCacheRangeFilter(field, parser, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetInt32s(Index.AtomicReader,string,bool)"/>. This works with all /// <see cref="int"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newIntRange() in Lucene /// </summary> public static FieldCacheRangeFilter<int?> NewInt32Range(string field, int? lowerVal, int? upperVal, bool includeLower, bool includeUpper) { return NewInt32Range(field, null, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetInt32s(Index.AtomicReader,string,FieldCache.IInt32Parser,bool)"/>. This works with all /// <see cref="int"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newIntRange() in Lucene /// </summary> public static FieldCacheRangeFilter<int?> NewInt32Range(string field, FieldCache.IInt32Parser parser, int? lowerVal, int? upperVal, bool includeLower, bool includeUpper) { return new AnonymousInt32FieldCacheRangeFilter(field, parser, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetInt64s(Index.AtomicReader,string,bool)"/>. This works with all /// <see cref="long"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> public static FieldCacheRangeFilter<long?> NewInt64Range(string field, long? lowerVal, long? upperVal, bool includeLower, bool includeUpper) { return NewInt64Range(field, null, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetInt64s(Index.AtomicReader,string,FieldCache.IInt64Parser,bool)"/>. This works with all /// <see cref="long"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newLongRange() in Lucene /// </summary> public static FieldCacheRangeFilter<long?> NewInt64Range(string field, FieldCache.IInt64Parser parser, long? lowerVal, long? upperVal, bool includeLower, bool includeUpper) { return new AnonymousInt64FieldCacheRangeFilter(field, parser, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetSingles(Index.AtomicReader,string,bool)"/>. This works with all /// <see cref="float"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newFloatRange() in Lucene /// </summary> public static FieldCacheRangeFilter<float?> NewSingleRange(string field, float? lowerVal, float? upperVal, bool includeLower, bool includeUpper) { return NewSingleRange(field, null, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetSingles(Index.AtomicReader,string,FieldCache.ISingleParser,bool)"/>. This works with all /// <see cref="float"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// <para/> /// NOTE: this was newFloatRange() in Lucene /// </summary> public static FieldCacheRangeFilter<float?> NewSingleRange(string field, FieldCache.ISingleParser parser, float? lowerVal, float? upperVal, bool includeLower, bool includeUpper) { return new AnonymousSingleFieldCacheRangeFilter(field, parser, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetDoubles(Index.AtomicReader,string,bool)"/>. This works with all /// <see cref="double"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> public static FieldCacheRangeFilter<double?> NewDoubleRange(string field, double? lowerVal, double? upperVal, bool includeLower, bool includeUpper) { return NewDoubleRange(field, null, lowerVal, upperVal, includeLower, includeUpper); } /// <summary> /// Creates a numeric range filter using <see cref="IFieldCache.GetDoubles(Index.AtomicReader,string,FieldCache.IDoubleParser,bool)"/>. This works with all /// <see cref="double"/> fields containing exactly one numeric term in the field. The range can be half-open by setting one /// of the values to <c>null</c>. /// </summary> public static FieldCacheRangeFilter<double?> NewDoubleRange(string field, FieldCache.IDoubleParser parser, double? lowerVal, double? upperVal, bool includeLower, bool includeUpper) { return new AnonymousDoubleFieldCacheRangeFilter(field, parser, lowerVal, upperVal, includeLower, includeUpper); } } public abstract class FieldCacheRangeFilter<T> : Filter { internal readonly string field; internal readonly FieldCache.IParser parser; internal readonly T lowerVal; internal readonly T upperVal; internal readonly bool includeLower; internal readonly bool includeUpper; protected internal FieldCacheRangeFilter(string field, FieldCache.IParser parser, T lowerVal, T upperVal, bool includeLower, bool includeUpper) { this.field = field; this.parser = parser; this.lowerVal = lowerVal; this.upperVal = upperVal; this.includeLower = includeLower; this.includeUpper = includeUpper; } /// <summary> /// This method is implemented for each data type </summary> public override abstract DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs); // From line 516 in Lucene public override sealed string ToString() { StringBuilder sb = (new StringBuilder(field)).Append(":"); return sb.Append(includeLower ? '[' : '{').Append((lowerVal == null) ? "*" : lowerVal.ToString()).Append(" TO ").Append((upperVal == null) ? "*" : upperVal.ToString()).Append(includeUpper ? ']' : '}').ToString(); } public override sealed bool Equals(object o) { if (this == o) { return true; } if (!(o is FieldCacheRangeFilter<T>)) { return false; } FieldCacheRangeFilter<T> other = (FieldCacheRangeFilter<T>)o; if (!this.field.Equals(other.field, StringComparison.Ordinal) || this.includeLower != other.includeLower || this.includeUpper != other.includeUpper) { return false; } if (this.lowerVal != null ? !this.lowerVal.Equals(other.lowerVal) : other.lowerVal != null) { return false; } if (this.upperVal != null ? !this.upperVal.Equals(other.upperVal) : other.upperVal != null) { return false; } if (this.parser != null ? !this.parser.Equals(other.parser) : other.parser != null) { return false; } return true; } public override sealed int GetHashCode() { int h = field.GetHashCode(); h ^= (lowerVal != null) ? lowerVal.GetHashCode() : 550356204; h = (h << 1) | ((int)((uint)h >> 31)); // rotate to distinguish lower from upper h ^= (upperVal != null) ? upperVal.GetHashCode() : -1674416163; h ^= (parser != null) ? parser.GetHashCode() : -1572457324; h ^= (includeLower ? 1549299360 : -365038026) ^ (includeUpper ? 1721088258 : 1948649653); return h; } /// <summary> /// Returns the field name for this filter </summary> public virtual string Field { get { return field; } } /// <summary> /// Returns <c>true</c> if the lower endpoint is inclusive </summary> public virtual bool IncludesLower { get { return includeLower; } } /// <summary> /// Returns <c>true</c> if the upper endpoint is inclusive </summary> public virtual bool IncludesUpper { get { return includeUpper; } } /// <summary> /// Returns the lower value of this range filter </summary> public virtual T LowerVal { get { return lowerVal; } } /// <summary> /// Returns the upper value of this range filter </summary> public virtual T UpperVal { get { return upperVal; } } /// <summary> /// Returns the current numeric parser (<c>null</c> for <typeparamref name="T"/> is <see cref="string"/>) </summary> public virtual FieldCache.IParser Parser { get { return parser; } } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Elastic.Clients.Elasticsearch { internal static class Extensions { private static readonly ConcurrentDictionary<string, object> EnumCache = new(); //internal static bool NotWritable(this QueryContainer q) => q == null || !q.IsWritable; //internal static bool NotWritable(this IEnumerable<QueryContainer> qs) => qs == null || qs.All(q => q.NotWritable()); internal static string ToEnumValue<T>(this T enumValue) where T : struct { var enumType = typeof(T); var name = Enum.GetName(enumType, enumValue); var enumMemberAttribute = enumType.GetField(name).GetCustomAttribute<EnumMemberAttribute>(); //if (enumMemberAttribute != null) //return enumMemberAttribute.Value; //var alternativeEnumMemberAttribute = enumType.GetField(name).GetCustomAttribute<AlternativeEnumMemberAttribute>(); return enumMemberAttribute != null ? enumMemberAttribute.Value : enumValue.ToString(); } internal static T? ToEnum<T>(this string str, StringComparison comparison = StringComparison.OrdinalIgnoreCase) where T : struct { if (str == null) return null; var enumType = typeof(T); var key = $"{enumType.Name}.{str}"; if (EnumCache.TryGetValue(key, out var value)) return (T)value; foreach (var name in Enum.GetNames(enumType)) { if (name.Equals(str, comparison)) { var v = (T)Enum.Parse(enumType, name, true); EnumCache.TryAdd(key, v); return v; } var enumFieldInfo = enumType.GetField(name); var enumMemberAttribute = enumFieldInfo.GetCustomAttribute<EnumMemberAttribute>(); if (enumMemberAttribute?.Value.Equals(str, comparison) ?? false) { var v = (T)Enum.Parse(enumType, name); EnumCache.TryAdd(key, v); return v; } //var alternativeEnumMemberAttribute = enumFieldInfo.GetCustomAttribute<AlternativeEnumMemberAttribute>(); //if (alternativeEnumMemberAttribute?.Value.Equals(str, comparison) ?? false) //{ // var v = (T)Enum.Parse(enumType, name); // EnumCache.TryAdd(key, v); // return v; //} } return null; } internal static TReturn InvokeOrDefault<T, TReturn>(this Func<T, TReturn> func, T @default) where T : class, TReturn where TReturn : class => func?.Invoke(@default) ?? @default; internal static TReturn InvokeOrDefault<T1, T2, TReturn>(this Func<T1, T2, TReturn> func, T1 @default, T2 param2) where T1 : class, TReturn where TReturn : class => func?.Invoke(@default, param2) ?? @default; internal static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property) => items.GroupBy(property).Select(x => x.First()); internal static string Utf8String(this byte[] bytes) => bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length); internal static byte[] Utf8Bytes(this string s) => s.IsNullOrEmpty() ? null : Encoding.UTF8.GetBytes(s); internal static bool IsNullOrEmpty(this IndexName value) => value == null || value.GetHashCode() == 0; internal static bool IsNullable(this Type type) => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); internal static void ThrowIfNullOrEmpty(this string @object, string parameterName, string when = null) { @object.ThrowIfNull(parameterName, when); if (string.IsNullOrWhiteSpace(@object)) { throw new ArgumentException( "Argument can't be null or empty" + (when.IsNullOrEmpty() ? "" : " when " + when), parameterName); } } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global internal static void ThrowIfEmpty<T>(this IEnumerable<T> @object, string parameterName) { if (@object == null) throw new ArgumentNullException(parameterName); if (!@object.Any()) throw new ArgumentException("Argument can not be an empty collection", parameterName); } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global internal static T[] NotEmpty<T>(this IEnumerable<T> @object, string parameterName) { if (!@object.HasAny(out var enumerated)) throw new ArgumentException("Argument can not be an empty collection", parameterName); return enumerated; } internal static bool HasAny<T>(this IEnumerable<T> list, out T[] enumerated) { enumerated = list == null ? null : list as T[] ?? list.ToArray(); return enumerated.HasAny(); } internal static List<T> AsInstanceOrToListOrDefault<T>(this IEnumerable<T> list) => list as List<T> ?? list?.ToList() ?? new List<T>(); internal static List<T> AsInstanceOrToListOrNull<T>(this IEnumerable<T> list) => list as List<T> ?? list?.ToList(); internal static List<T> EagerConcat<T>(this IEnumerable<T> list, IEnumerable<T> other) { var first = list.AsInstanceOrToListOrDefault(); if (other == null) return first; var second = other.AsInstanceOrToListOrDefault(); var newList = new List<T>(first.Count + second.Count); newList.AddRange(first); newList.AddRange(second); return newList; } internal static IEnumerable<T> AddIfNotNull<T>(this IEnumerable<T> list, T other) { if (other == null) return list; var l = list.AsInstanceOrToListOrDefault(); l.Add(other); return l; } internal static bool HasAny<T>(this IEnumerable<T> list, Func<T, bool> predicate) => list != null && list.Any(predicate); internal static bool HasAny<T>(this IEnumerable<T> list) => list != null && list.Any(); internal static bool IsEmpty<T>(this IEnumerable<T> list) { if (list == null) return true; var enumerable = list as T[] ?? list.ToArray(); return !enumerable.Any() || enumerable.All(t => t == null); } internal static void ThrowIfNull<T>(this T value, string name, string message = null) { if (value == null && message.IsNullOrEmpty()) throw new ArgumentNullException(name); else if (value == null) throw new ArgumentNullException(name, "Argument can not be null when " + message); } internal static bool IsNullOrEmpty(this string value) => string.IsNullOrWhiteSpace(value); internal static bool IsNullOrEmptyCommaSeparatedList(this string value, out string[] split) { split = null; if (string.IsNullOrWhiteSpace(value)) return true; split = value.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries) .Where(t => !t.IsNullOrEmpty()) .Select(t => t.Trim()) .ToArray(); return split.Length == 0; } internal static List<T> ToListOrNullIfEmpty<T>(this IEnumerable<T> enumerable) { var list = enumerable.AsInstanceOrToListOrNull(); return list != null && list.Count > 0 ? list : null; } internal static void AddIfNotNull<T>(this IList<T> list, T item) where T : class { if (item == null) return; list.Add(item); } internal static void AddRangeIfNotNull<T>(this List<T> list, IEnumerable<T> item) where T : class { if (item == null) return; list.AddRange(item.Where(x => x != null)); } internal static Dictionary<TKey, TValue> NullIfNoKeys<TKey, TValue>(this Dictionary<TKey, TValue> dictionary) { var i = dictionary?.Count; return i.GetValueOrDefault(0) > 0 ? dictionary : null; } internal static async Task ForEachAsync<TSource, TResult>( this IEnumerable<TSource> lazyList, Func<TSource, long, Task<TResult>> taskSelector, Action<TSource, TResult> resultProcessor, Action<Exception> done, int maxDegreeOfParallelism, SemaphoreSlim additionalRateLimiter = null ) { var semaphore = new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism); long page = 0; try { var tasks = new List<Task>(maxDegreeOfParallelism); foreach (var item in lazyList) { tasks.Add(ProcessAsync(item, taskSelector, resultProcessor, semaphore, additionalRateLimiter, page++)); if (tasks.Count < maxDegreeOfParallelism) continue; var task = await Task.WhenAny(tasks).ConfigureAwait(false); if (task.Exception != null && task.IsFaulted && task.Exception.Flatten().InnerExceptions.First() is { } e) { ExceptionDispatchInfo.Capture(e).Throw(); return; } tasks.Remove(task); } await Task.WhenAll(tasks).ConfigureAwait(false); done(null); } catch (Exception e) { done(e); throw; } } private static async Task ProcessAsync<TSource, TResult>( TSource item, Func<TSource, long, Task<TResult>> taskSelector, Action<TSource, TResult> resultProcessor, SemaphoreSlim localRateLimiter, SemaphoreSlim additionalRateLimiter, long page ) { if (localRateLimiter != null) await localRateLimiter.WaitAsync().ConfigureAwait(false); if (additionalRateLimiter != null) await additionalRateLimiter.WaitAsync().ConfigureAwait(false); try { var result = await taskSelector(item, page).ConfigureAwait(false); resultProcessor(item, result); } finally { localRateLimiter?.Release(); additionalRateLimiter?.Release(); } } internal static bool NullOrEquals<T>(this T o, T other) { if (o == null && other == null) return true; if (o == null || other == null) return false; return o.Equals(other); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml.Linq; using Umbraco.Cms.Core; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; namespace Umbraco.Extensions { public static class ContentExtensions { /// <summary> /// Returns the path to a media item stored in a property if the property editor is <see cref="IMediaUrlGenerator"/> /// </summary> /// <param name="content"></param> /// <param name="propertyTypeAlias"></param> /// <param name="mediaUrlGenerators"></param> /// <param name="mediaFilePath"></param> /// <param name="culture"></param> /// <param name="segment"></param> /// <returns>True if the file path can be resolved and the property is <see cref="IMediaUrlGenerator"/></returns> public static bool TryGetMediaPath( this IContentBase content, string propertyTypeAlias, MediaUrlGeneratorCollection mediaUrlGenerators, out string mediaFilePath, string culture = null, string segment = null) { if (!content.Properties.TryGetValue(propertyTypeAlias, out IProperty property)) { mediaFilePath = null; return false; } if (!mediaUrlGenerators.TryGetMediaPath( property.PropertyType.PropertyEditorAlias, property.GetValue(culture, segment), out mediaFilePath)) { return false; } return true; } public static bool IsAnyUserPropertyDirty(this IContentBase entity) { return entity.Properties.Any(x => x.IsDirty()); } public static bool WasAnyUserPropertyDirty(this IContentBase entity) { return entity.Properties.Any(x => x.WasDirty()); } public static bool IsMoving(this IContentBase entity) { // Check if this entity is being moved as a descendant as part of a bulk moving operations. // When this occurs, only Path + Level + UpdateDate are being changed. In this case we can bypass a lot of the below // operations which will make this whole operation go much faster. When moving we don't need to create // new versions, etc... because we cannot roll this operation back anyways. var isMoving = entity.IsPropertyDirty(nameof(entity.Path)) && entity.IsPropertyDirty(nameof(entity.Level)) && entity.IsPropertyDirty(nameof(entity.UpdateDate)); return isMoving; } /// <summary> /// Removes characters that are not valid XML characters from all entity properties /// of type string. See: http://stackoverflow.com/a/961504/5018 /// </summary> /// <returns></returns> /// <remarks> /// If this is not done then the xml cache can get corrupt and it will throw YSODs upon reading it. /// </remarks> /// <param name="entity"></param> public static void SanitizeEntityPropertiesForXmlStorage(this IContentBase entity) { entity.Name = entity.Name.ToValidXmlString(); foreach (var property in entity.Properties) { foreach (var propertyValue in property.Values) { if (propertyValue.EditedValue is string editString) propertyValue.EditedValue = editString.ToValidXmlString(); if (propertyValue.PublishedValue is string publishedString) propertyValue.PublishedValue = publishedString.ToValidXmlString(); } } } /// <summary> /// Checks if the IContentBase has children /// </summary> /// <param name="content"></param> /// <param name="services"></param> /// <returns></returns> /// <remarks> /// This is a bit of a hack because we need to type check! /// </remarks> internal static bool HasChildren(IContentBase content, ServiceContext services) { if (content is IContent) { return services.ContentService.HasChildren(content.Id); } if (content is IMedia) { return services.MediaService.HasChildren(content.Id); } return false; } /// <summary> /// Returns all properties based on the editorAlias /// </summary> /// <param name="content"></param> /// <param name="editorAlias"></param> /// <returns></returns> public static IEnumerable<IProperty> GetPropertiesByEditor(this IContentBase content, string editorAlias) => content.Properties.Where(x => x.PropertyType.PropertyEditorAlias == editorAlias); #region IContent /// <summary> /// Gets the current status of the Content /// </summary> public static ContentStatus GetStatus(this IContent content, string culture = null) { if (content.Trashed) return ContentStatus.Trashed; if (!content.ContentType.VariesByCulture()) culture = string.Empty; else if (culture.IsNullOrWhiteSpace()) throw new ArgumentNullException($"{nameof(culture)} cannot be null or empty"); var expires = content.ContentSchedule.GetSchedule(culture, ContentScheduleAction.Expire); if (expires != null && expires.Any(x => x.Date > DateTime.MinValue && DateTime.Now > x.Date)) return ContentStatus.Expired; var release = content.ContentSchedule.GetSchedule(culture, ContentScheduleAction.Release); if (release != null && release.Any(x => x.Date > DateTime.MinValue && x.Date > DateTime.Now)) return ContentStatus.AwaitingRelease; if (content.Published) return ContentStatus.Published; return ContentStatus.Unpublished; } /// <summary> /// Gets a collection containing the ids of all ancestors. /// </summary> /// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param> /// <returns>An Enumerable list of integer ids</returns> public static IEnumerable<int> GetAncestorIds(this IContent content) => content.Path.Split(Constants.CharArrays.Comma) .Where(x => x != Constants.System.RootString && x != content.Id.ToString(CultureInfo.InvariantCulture)).Select(s => int.Parse(s, CultureInfo.InvariantCulture)); #endregion /// <summary> /// Gets the <see cref="IProfile"/> for the Creator of this content item. /// </summary> public static IProfile GetCreatorProfile(this IContentBase content, IUserService userService) { return userService.GetProfileById(content.CreatorId); } /// <summary> /// Gets the <see cref="IProfile"/> for the Writer of this content. /// </summary> public static IProfile GetWriterProfile(this IContent content, IUserService userService) { return userService.GetProfileById(content.WriterId); } /// <summary> /// Gets the <see cref="IProfile"/> for the Writer of this content. /// </summary> public static IProfile GetWriterProfile(this IMedia content, IUserService userService) { return userService.GetProfileById(content.WriterId); } #region User/Profile methods /// <summary> /// Gets the <see cref="IProfile"/> for the Creator of this media item. /// </summary> public static IProfile GetCreatorProfile(this IMedia media, IUserService userService) { return userService.GetProfileById(media.CreatorId); } #endregion /// <summary> /// Returns properties that do not belong to a group /// </summary> /// <param name="content"></param> /// <returns></returns> public static IEnumerable<IProperty> GetNonGroupedProperties(this IContentBase content) { return content.Properties .Where(x => x.PropertyType.PropertyGroupId == null) .OrderBy(x => x.PropertyType.SortOrder); } /// <summary> /// Returns the Property object for the given property group /// </summary> /// <param name="content"></param> /// <param name="propertyGroup"></param> /// <returns></returns> public static IEnumerable<IProperty> GetPropertiesForGroup(this IContentBase content, PropertyGroup propertyGroup) { //get the properties for the current tab return content.Properties .Where(property => propertyGroup.PropertyTypes .Select(propertyType => propertyType.Id) .Contains(property.PropertyTypeId)); } #region SetValue for setting file contents /// <summary> /// Sets the posted file value of a property. /// </summary> public static void SetValue( this IContentBase content, MediaFileManager mediaFileManager, MediaUrlGeneratorCollection mediaUrlGenerators, IShortStringHelper shortStringHelper, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias, string filename, Stream filestream, string culture = null, string segment = null) { if (filename == null || filestream == null) return; filename = shortStringHelper.CleanStringForSafeFileName(filename); if (string.IsNullOrWhiteSpace(filename)) return; filename = filename.ToLower(); SetUploadFile(content, mediaFileManager, mediaUrlGenerators, contentTypeBaseServiceProvider, propertyTypeAlias, filename, filestream, culture, segment); } private static void SetUploadFile( this IContentBase content, MediaFileManager mediaFileManager, MediaUrlGeneratorCollection mediaUrlGenerators, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias, string filename, Stream filestream, string culture = null, string segment = null) { var property = GetProperty(content, contentTypeBaseServiceProvider, propertyTypeAlias); // Fixes https://github.com/umbraco/Umbraco-CMS/issues/3937 - Assigning a new file to an // existing IMedia with extension SetValue causes exception 'Illegal characters in path' string oldpath = null; if (content.TryGetMediaPath(property.Alias, mediaUrlGenerators, out string mediaFilePath, culture, segment)) { oldpath = mediaFileManager.FileSystem.GetRelativePath(mediaFilePath); } var filepath = mediaFileManager.StoreFile(content, property.PropertyType, filename, filestream, oldpath); // NOTE: Here we are just setting the value to a string which means that any file based editor // will need to handle the raw string value and save it to it's correct (i.e. JSON) // format. I'm unsure how this works today with image cropper but it does (maybe events?) property.SetValue(mediaFileManager.FileSystem.GetUrl(filepath), culture, segment); } // gets or creates a property for a content item. private static IProperty GetProperty(IContentBase content, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias) { var property = content.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(propertyTypeAlias)); if (property != null) return property; var contentType = contentTypeBaseServiceProvider.GetContentTypeOf(content); var propertyType = contentType.CompositionPropertyTypes .FirstOrDefault(x => x.Alias.InvariantEquals(propertyTypeAlias)); if (propertyType == null) throw new Exception("No property type exists with alias " + propertyTypeAlias + "."); property = new Property(propertyType); content.Properties.Add(property); return property; } /// <summary> /// Stores a file. /// </summary> /// <param name="content"><see cref="IContentBase"/>A content item.</param> /// <param name="propertyTypeAlias">The property alias.</param> /// <param name="filename">The name of the file.</param> /// <param name="filestream">A stream containing the file data.</param> /// <param name="filepath">The original file path, if any.</param> /// <returns>The path to the file, relative to the media filesystem.</returns> /// <remarks> /// <para>Does NOT set the property value, so one should probably store the file and then do /// something alike: property.Value = MediaHelper.FileSystem.GetUrl(filepath).</para> /// <para>The original file path is used, in the old media file path scheme, to try and reuse /// the "folder number" that was assigned to the previous file referenced by the property, /// if any.</para> /// </remarks> public static string StoreFile(this IContentBase content, MediaFileManager mediaFileManager, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias, string filename, Stream filestream, string filepath) { var contentType = contentTypeBaseServiceProvider.GetContentTypeOf(content); var propertyType = contentType .CompositionPropertyTypes.FirstOrDefault(x => x.Alias.InvariantEquals(propertyTypeAlias)); if (propertyType == null) throw new ArgumentException("Invalid property type alias " + propertyTypeAlias + "."); return mediaFileManager.StoreFile(content, propertyType, filename, filestream, filepath); } #endregion #region Dirty public static IEnumerable<string> GetDirtyUserProperties(this IContentBase entity) { return entity.Properties.Where(x => x.IsDirty()).Select(x => x.Alias); } #endregion /// <summary> /// Creates the full xml representation for the <see cref="IContent"/> object and all of it's descendants /// </summary> /// <param name="content"><see cref="IContent"/> to generate xml for</param> /// <param name="serializer"></param> /// <returns>Xml representation of the passed in <see cref="IContent"/></returns> internal static XElement ToDeepXml(this IContent content, IEntityXmlSerializer serializer) { return serializer.Serialize(content, false, true); } /// <summary> /// Creates the xml representation for the <see cref="IContent"/> object /// </summary> /// <param name="content"><see cref="IContent"/> to generate xml for</param> /// <param name="serializer"></param> /// <returns>Xml representation of the passed in <see cref="IContent"/></returns> public static XElement ToXml(this IContent content, IEntityXmlSerializer serializer) { return serializer.Serialize(content, false, false); } /// <summary> /// Creates the xml representation for the <see cref="IMedia"/> object /// </summary> /// <param name="media"><see cref="IContent"/> to generate xml for</param> /// <param name="serializer"></param> /// <returns>Xml representation of the passed in <see cref="IContent"/></returns> public static XElement ToXml(this IMedia media, IEntityXmlSerializer serializer) { return serializer.Serialize(media); } /// <summary> /// Creates the xml representation for the <see cref="IMember"/> object /// </summary> /// <param name="member"><see cref="IMember"/> to generate xml for</param> /// <param name="serializer"></param> /// <returns>Xml representation of the passed in <see cref="IContent"/></returns> public static XElement ToXml(this IMember member, IEntityXmlSerializer serializer) { return serializer.Serialize(member); } } }
using NUnit.Framework; using static NSelene.Selene; namespace NSelene.Tests.Integration.SharedDriver.SeleneSpec { using System; using System.Linq; using Harness; [TestFixture] public class SeleneElement_Submit_Specs : BaseTest { [Test] public void Submit_WaitsForVisibility_OfInitiialyAbsent() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedEmptyPage(); var beforeCall = DateTime.Now; Given.OpenedPageWithBodyTimedOut( @" <form action='#second'>go to Heading 2</form> <h2 id='second'>Heading 2</h2> ", 300 ); S("form").Submit(); var afterCall = DateTime.Now; Assert.IsTrue(Configuration.Driver.Url.Contains("second")); Assert.Greater(afterCall, beforeCall.AddSeconds(0.3)); Assert.Less(afterCall, beforeCall.AddSeconds(0.6)); } [Test] public void Submit_IsRenderedInError_OnAbsentElementFailure() { Configuration.Timeout = 0.25; Configuration.PollDuringWaits = 0.1; Given.OpenedEmptyPage(); try { S("form").Submit(); } catch (TimeoutException error) { var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Timed out after 0.25s, while waiting for:", lines); Assert.Contains("Browser.Element(form).ActualWebElement.Submit()", lines); Assert.Contains("Reason:", lines); Assert.Contains( "no such element: Unable to locate element: " + "{\"method\":\"css selector\",\"selector\":\"form\"}" , lines ); } } [Test] public void Submit_IsRenderedInError_OnAbsentElementFailure_WhenCustomizedToWaitForNoOverlapFoundByJs() { Configuration.Timeout = 0.25; Configuration.PollDuringWaits = 0.1; Given.OpenedEmptyPage(); try { S("form").With(waitForNoOverlapFoundByJs: true).Submit(); } catch (TimeoutException error) { var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Timed out after 0.25s, while waiting for:", lines); Assert.Contains("Browser.Element(form).ActualNotOverlappedWebElement.Submit()", lines); Assert.Contains("Reason:", lines); Assert.Contains( "no such element: Unable to locate element: " + "{\"method\":\"css selector\",\"selector\":\"form\"}" , lines ); } } [Test] public void Submit_Works_OnHidden_ByDefault() // TODO: but should it? // public void Submit_WaitsForVisibility_OfInitialyHidden() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <form action='#second' style='display:none'>go to Heading 2</form> <h2 id='second'>Heading 2</h2> " ); var beforeCall = DateTime.Now; // Given.ExecuteScriptWithTimeout( // @" // document.getElementsByTagName('form')[0].style.display = 'block'; // ", // 300 // ); S("form").Submit(); var afterCall = DateTime.Now; Assert.Less(afterCall, beforeCall.AddSeconds(0.3)); // Assert.Greater(afterCall, beforeCall.AddSeconds(0.3)); // Assert.Less(afterCall, beforeCall.AddSeconds(0.6)); Assert.IsTrue(Configuration.Driver.Url.Contains("second")); } [Test] public void Submit_WaitsForVisibility_OfInitialyHidden_WhenCustomizedToWaitForNoOverlapFoundByJs() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <form action='#second' style='display:none'>go to Heading 2</form> <h2 id='second'>Heading 2</h2> " ); var beforeCall = DateTime.Now; Given.ExecuteScriptWithTimeout( @" document.getElementsByTagName('form')[0].style.display = 'block'; ", 300 ); S("form").With(waitForNoOverlapFoundByJs: true).Submit(); var afterCall = DateTime.Now; Assert.Greater(afterCall, beforeCall.AddSeconds(0.3)); Assert.Less(afterCall, beforeCall.AddSeconds(0.6)); Assert.IsTrue(Configuration.Driver.Url.Contains("second")); } [Test] public void Submit_IsRenderedInError_OnHiddenElementFailure_WhenCustomizedToWaitForNoOverlapFoundByJs() { Configuration.Timeout = 0.25; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <form action='#second' style='display:none'>go to Heading 2</form> <h2 id='second'>Heading 2</h2> " ); try { S("form").With(waitForNoOverlapFoundByJs: true).Submit(); } catch (TimeoutException error) { var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Timed out after 0.25s, while waiting for:", lines); Assert.Contains("Browser.Element(form).ActualNotOverlappedWebElement.Submit()", lines); Assert.Contains("Reason:", lines); Assert.Contains("javascript error: element is not visible", lines); } } [Test] public void Submit_Works_UnderOverlay() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <div id='overlay' style=' display:block; position: fixed; display: block; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.1); z-index: 2; cursor: pointer; ' > </div> <form action='#second'>go to Heading 2</form> <h2 id='second'>Heading 2</h2> " ); var beforeCall = DateTime.Now; S("form").Submit(); // TODO: this overlay works only for "overlayying at center of element", handle the "partial overlay" cases too! var afterCall = DateTime.Now; Assert.Less(afterCall, beforeCall.AddSeconds(0.3)); Assert.IsTrue(Configuration.Driver.Url.Contains("second")); } [Test] public void Submit_Waits_For_NoOverlay_WhenCustomized() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <div id='overlay' style=' display:block; position: fixed; display: block; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.1); z-index: 2; cursor: pointer; ' > </div> <form action='#second'>go to Heading 2</form> <h2 id='second'>Heading 2</h2> " ); var beforeCall = DateTime.Now; Given.ExecuteScriptWithTimeout( @" document.getElementById('overlay').style.display = 'none'; ", 300 ); S("form").With(waitForNoOverlapFoundByJs: true).Submit(); // TODO: this overlay works only for "overlayying at center of element", handle the "partial overlay" cases too! var afterCall = DateTime.Now; Assert.Greater(afterCall, beforeCall.AddSeconds(0.3)); Assert.Less(afterCall, beforeCall.AddSeconds(0.6)); Assert.IsTrue(Configuration.Driver.Url.Contains("second")); } [Test] public void Submit_IsRenderedInError_OnOverlappedWithOverlayFailure_WhenCustomizedToWaitForNoOverlapFoundByJs() { Configuration.Timeout = 0.25; Configuration.PollDuringWaits = 0.1; Given.OpenedPageWithBody( @" <div id='overlay' style=' display: block; position: fixed; display: block; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.1); z-index: 2; cursor: pointer; ' > </div> <form action='#second'>go to H2</form> <h2 id='second'>Heading 2</h2> " ); try { S("form").With(waitForNoOverlapFoundByJs: true).Submit(); } catch (TimeoutException error) { var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Timed out after 0.25s, while waiting for:", lines); Assert.Contains("Browser.Element(form).ActualNotOverlappedWebElement.Submit()", lines); Assert.Contains("Reason:", lines); Assert.Contains("Element: <form action=\"#second\">go to H2</form>", lines); Assert.NotNull(lines.Find(item => item.Contains( "is overlapped by: <div id=\"overlay\" " ))); } } [Test] public void Submit_Fails_OnNonFormElement() { Configuration.Timeout = 0.6; Configuration.PollDuringWaits = 0.1; Given.OpenedEmptyPage(); Given.OpenedPageWithBodyTimedOut( @" <a href='#second'>go to Heading 2</a> <h2 id='second'>Heading 2</h2> ", 300 ); try { S("a").Submit(); } catch (TimeoutException error) { var lines = error.Message.Split("\n").Select( item => item.Trim() ).ToList(); Assert.Contains("Reason:", lines); Assert.Contains( "no such element: Unable to locate element: " + "{\"method\":\"xpath\",\"selector\":\"./ancestor-or-self::form\"}" , lines ); Assert.IsFalse(Configuration.Driver.Url.Contains("second")); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableList{T}"/>. /// </summary> public static class ImmutableList { /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>() { return ImmutableList<T>.Empty; } /// <summary> /// Creates a new immutable collection prefilled with the specified item. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="item">The item to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>(T item) { return ImmutableList<T>.Empty.Add(item); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> CreateRange<T>(IEnumerable<T> items) { return ImmutableList<T>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>(params T[] items) { return ImmutableList<T>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable list builder. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableList<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } /// <summary> /// Enumerates a sequence exactly once and produces an immutable list of its contents. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <param name="source">The sequence to enumerate.</param> /// <returns>An immutable list.</returns> [Pure] public static ImmutableList<TSource> ToImmutableList<TSource>(this IEnumerable<TSource> source) { var existingList = source as ImmutableList<TSource>; if (existingList != null) { return existingList; } return ImmutableList<TSource>.Empty.AddRange(source); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> [Pure] public static IImmutableList<T> Replace<T>(this IImmutableList<T> list, T oldValue, T newValue) { Requires.NotNull(list, "list"); return list.Replace(oldValue, newValue, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified value from this list. /// </summary> /// <param name="list">The list to search.</param> /// <param name="value">The value to remove.</param> /// <returns>A new list with the element removed, or this list if the element is not in this list.</returns> [Pure] public static IImmutableList<T> Remove<T>(this IImmutableList<T> list, T value) { Requires.NotNull(list, "list"); return list.Remove(value, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="list">The list to search.</param> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> [Pure] public static IImmutableList<T> RemoveRange<T>(this IImmutableList<T> list, IEnumerable<T> items) { Requires.NotNull(list, "list"); return list.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the ImmutableList&lt;T&gt; /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the ImmutableList&lt;T&gt; that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item) { Requires.NotNull(list, "list"); return list.IndexOf(item, 0, list.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the ImmutableList&lt;T&gt; /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the ImmutableList&lt;T&gt; that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer) { Requires.NotNull(list, "list"); return list.IndexOf(item, 0, list.Count, equalityComparer); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the range of elements in the ImmutableList&lt;T&gt; /// that extends from the specified index to the last element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the search. 0 (zero) is valid in an empty /// list. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the ImmutableList&lt;T&gt; that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex) { Requires.NotNull(list, "list"); return list.IndexOf(item, startIndex, list.Count - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the range of elements in the ImmutableList&lt;T&gt; /// that extends from the specified index to the last element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the search. 0 (zero) is valid in an empty /// list. /// </param> /// <param name="count"> /// The number of elements in the section to search. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the ImmutableList&lt;T&gt; that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count) { Requires.NotNull(list, "list"); return list.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the entire ImmutableList&lt;T&gt;. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the entire the /// ImmutableList&lt;T&gt;, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item) { Requires.NotNull(list, "list"); if (list.Count == 0) { // Avoid argument out of range exceptions. return -1; } return list.LastIndexOf(item, list.Count - 1, list.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the entire ImmutableList&lt;T&gt;. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns> /// The zero-based index of the last occurrence of item within the entire the /// ImmutableList&lt;T&gt;, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer) { Requires.NotNull(list, "list"); if (list.Count == 0) { // Avoid argument out of range exceptions. return -1; } return list.LastIndexOf(item, list.Count - 1, list.Count, equalityComparer); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the range of elements in the ImmutableList&lt;T&gt; /// that extends from the first element to the specified index. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the backward search. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the range of elements /// in the ImmutableList&lt;T&gt; that extends from the first element /// to index, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex) { Requires.NotNull(list, "list"); if (list.Count == 0 && startIndex == 0) { return -1; } return list.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the range of elements in the ImmutableList&lt;T&gt; /// that extends from the first element to the specified index. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the ImmutableList&lt;T&gt;. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the backward search. /// </param> /// <param name="count"> /// The number of elements in the section to search. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the range of elements /// in the ImmutableList&lt;T&gt; that extends from the first element /// to index, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count) { Requires.NotNull(list, "list"); return list.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Encog.Persist; using System.IO; using Encog.ML.Bayesian.Query; using Encog.Util; using Encog.ML.Bayesian.Query.Enumeration; using Encog.ML.Bayesian.Query.Sample; using Encog.ML.Bayesian.Table; namespace Encog.ML.Bayesian { /// <summary> /// Persist a bayes network. /// </summary> public class PersistBayes : IEncogPersistor { /// <summary> /// The file version. /// </summary> public int FileVersion { get { return 1; } } /// <inheritdoc/> public Object Read(Stream istream) { BayesianNetwork result = new BayesianNetwork(); EncogReadHelper input = new EncogReadHelper(istream); EncogFileSection section; String queryType = ""; String queryStr = ""; String contentsStr = ""; while ((section = input.ReadNextSection()) != null) { if (section.SectionName.Equals("BAYES-NETWORK") && section.SubSectionName.Equals("BAYES-PARAM")) { IDictionary<String, String> p = section.ParseParams(); queryType = p["queryType"]; queryStr = p["query"]; contentsStr = p["contents"]; } if (section.SectionName.Equals("BAYES-NETWORK") && section.SubSectionName.Equals("BAYES-TABLE")) { result.Contents = contentsStr; // first, define relationships (1st pass) foreach (String line in section.Lines) { result.DefineRelationship(line); } result.FinalizeStructure(); // now define the probabilities (2nd pass) foreach (String line in section.Lines) { result.DefineProbability(line); } } if (section.SectionName.Equals("BAYES-NETWORK") && section.SubSectionName.Equals("BAYES-PROPERTIES")) { IDictionary<String, String> paras = section.ParseParams(); EngineArray.PutAll(paras, result.Properties); } } // define query, if it exists if (queryType.Length > 0) { IBayesianQuery query = null; if (queryType.Equals("EnumerationQuery")) { query = new EnumerationQuery(result); } else { query = new SamplingQuery(result); } if (query != null && queryStr.Length > 0) { result.Query = query; result.DefineClassificationStructure(queryStr); } } return result; } /// <inheritdoc/> public void Save(Stream os, Object obj) { EncogWriteHelper o = new EncogWriteHelper(os); BayesianNetwork b = (BayesianNetwork)obj; o.AddSection("BAYES-NETWORK"); o.AddSubSection("BAYES-PARAM"); String queryType = ""; String queryStr = b.ClassificationStructure; if (b.Query != null) { queryType = b.Query.GetType().Name; } o.WriteProperty("queryType", queryType); o.WriteProperty("query", queryStr); o.WriteProperty("contents", b.Contents); o.AddSubSection("BAYES-PROPERTIES"); o.AddProperties(b.Properties); o.AddSubSection("BAYES-TABLE"); foreach (BayesianEvent e in b.Events) { foreach (TableLine line in e.Table.Lines) { if (line == null) continue; StringBuilder str = new StringBuilder(); str.Append("P("); str.Append(BayesianEvent.FormatEventName(e, line.Result)); if (e.Parents.Count > 0) { str.Append("|"); } int index = 0; bool first = true; foreach (BayesianEvent parentEvent in e.Parents) { if (!first) { str.Append(","); } first = false; int arg = line.Arguments[index++]; if (parentEvent.IsBoolean) { if (arg == 0) { str.Append("+"); } else { str.Append("-"); } } str.Append(parentEvent.Label); if (!parentEvent.IsBoolean) { str.Append("="); if (arg >= parentEvent.Choices.Count) { throw new BayesianError("Argument value " + arg + " is out of range for event " + parentEvent.ToString()); } str.Append(parentEvent.GetChoice(arg)); } } str.Append(")="); str.Append(line.Probability); str.Append("\n"); o.Write(str.ToString()); } } o.Flush(); } /// <inheritdoc/> public String PersistClassString { get { return "BayesianNetwork"; } } /// <inheritdoc/> public Type NativeType { get { return typeof(BayesianNetwork); } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using NUnit.Framework; namespace Cassandra.Tests { [TestFixture] public class LocalDateTests { private static readonly Tuple<LocalDate, uint>[] Values = { Tuple.Create(new LocalDate(1970, 1, 1), 2147483648U), Tuple.Create(new LocalDate(2010, 8, 5), 2147498474U), Tuple.Create(new LocalDate(1991, 7, 11), 0x80001eb5), Tuple.Create(new LocalDate(1972, 8, 5), 0x800003b3), Tuple.Create(new LocalDate(1969, 12, 31), 2147483647U), Tuple.Create(new LocalDate(1941, 5, 3), 2147473178U), Tuple.Create(new LocalDate(1, 1, 1), 2146764486U), Tuple.Create(new LocalDate(0, 1, 1), 2146764120U), Tuple.Create(new LocalDate(0, 5, 1), 2146764241U), Tuple.Create(new LocalDate(-1, 1, 1), 2146763755U), Tuple.Create(new LocalDate(-1, 12, 31), 0x7ff50557U), Tuple.Create(new LocalDate(-3, 1, 1), 2146763025U), Tuple.Create(new LocalDate(-3, 5, 1), 0x7ff50189U), Tuple.Create(new LocalDate(-4, 1, 1), 2146762659U), Tuple.Create(new LocalDate(-5, 1, 1), 2146762294U), Tuple.Create(new LocalDate(-6, 1, 1), 2146761929U), Tuple.Create(new LocalDate(-7, 5, 1), 2146761684U), Tuple.Create(new LocalDate(-8, 5, 1), 2146761319U), Tuple.Create(new LocalDate(-2, 12, 31), 2146763754U), Tuple.Create(new LocalDate(-100, 12, 31), 0x7ff47818U), Tuple.Create(new LocalDate(-100, 1, 1), 0x7ff476acU), Tuple.Create(new LocalDate(-99, 5, 15), 0x7ff4789fU), Tuple.Create(new LocalDate(-99, 1, 1), 0x7ff47819U), Tuple.Create(new LocalDate(-5877641, 6, 23), 0U), Tuple.Create(new LocalDate(012345, 8, 5), 2151273255), Tuple.Create(new LocalDate(062345, 8, 5), 2169535380), Tuple.Create(new LocalDate(093456, 8, 5), 0x81fdde88), Tuple.Create(new LocalDate(123456, 8, 5), 2191855715), Tuple.Create(new LocalDate(5881580, 7, 10), 4294967294U), Tuple.Create(new LocalDate(5881580, 7, 11), uint.MaxValue), Tuple.Create(new LocalDate(2399, 12, 31), 2147640701), Tuple.Create(new LocalDate(2100, 10, 10), 2147531412), Tuple.Create(new LocalDate(2300, 12, 31), 2147604542), Tuple.Create(new LocalDate(2400, 12, 31), 2147641067) }; [Test] public void Should_Calculate_Days_Centered() { foreach (var v in Values) { Assert.AreEqual(v.Item2, v.Item1.DaysSinceEpochCentered, "For Date " + v.Item1); } } [Test] public void Should_Calculate_Year_Month_Day_Positives_Dates() { foreach (var v in Values) { if (v.Item1.Year < 0) { continue; } var calculated = new LocalDate(v.Item2); Assert.AreEqual(v.Item1.Year, calculated.Year, "Year for Date " + v.Item1); Assert.AreEqual(v.Item1.Month, calculated.Month, "Month for Date " + v.Item1); Assert.AreEqual(v.Item1.Day, calculated.Day, "Day for Date " + v.Item1); } } [Test] public void Should_Calculate_Year_Month_Day_Negative_Dates() { foreach (var v in Values) { if (v.Item1.Year >= 0) { continue; } var calculated = new LocalDate(v.Item2); Assert.AreEqual(v.Item1.Year, calculated.Year, "Year for Date " + v.Item1); Assert.AreEqual(v.Item1.Month, calculated.Month, "Month for Date " + v.Item1); Assert.AreEqual(v.Item1.Day, calculated.Day, "Day for Date " + v.Item1); } } [Test] public void Can_Be_Used_As_Dictionary_Key() { var dictionary = Values.ToDictionary(v => v.Item1, v => v.Item1.ToString()); Assert.AreEqual(Values.Length, dictionary.Count); } [Test] public void Should_Support_Operators() { LocalDate value1 = null; Assert.True(value1 == null); Assert.False(value1 != null); value1 = new LocalDate(2010, 3, 15); Assert.False(value1 == null); Assert.True(value1 != null); Assert.AreEqual(value1, new LocalDate(2010, 3, 15)); } [Test] public void ToString_Should_Return_String_Representation() { var values = new [] { Tuple.Create(2010, 4, 29, "2010-04-29"), Tuple.Create(2005, 8, 5, "2005-08-05"), Tuple.Create(101, 10, 5, "0101-10-05"), Tuple.Create(-10, 10, 5, "-10-10-05"), Tuple.Create(-110, 1, 23, "-110-01-23") }; foreach (var v in values) { Assert.AreEqual(v.Item4, new LocalDate(v.Item1, v.Item2, v.Item3).ToString()); } } [Test] public void Constructor_Should_Validate_Boundaries() { var values = new[] { Tuple.Create(5881581, 1, 1), Tuple.Create(5881580, 7, 12), Tuple.Create(-5877641, 6, 22), Tuple.Create(-5877642, 1, 1) }; foreach (var v in values) { // ReSharper disable once ObjectCreationAsStatement Assert.Throws<ArgumentOutOfRangeException>(() => new LocalDate(v.Item1, v.Item2, v.Item3)); } } [Test] public void ToDateTimeOffset_Should_Convert() { var values = new[] { Tuple.Create(2010, 4, 29), Tuple.Create(2005, 8, 5), Tuple.Create(101, 10, 5) }; foreach (var v in values) { var expected = new DateTimeOffset(v.Item1, v.Item2, v.Item3, 0, 0, 0, TimeSpan.Zero); Assert.AreEqual(expected, new LocalDate(v.Item1, v.Item2, v.Item3).ToDateTimeOffset()); } } [Test] public void ToDateTimeOffset_Should_Throw_When_Can_Not_Represent() { var values = new[] { Tuple.Create(-1, 4, 29), Tuple.Create(0, 8, 5), Tuple.Create(10123, 10, 5) }; foreach (var v in values) { Assert.Throws<ArgumentOutOfRangeException>(() => new LocalDate(v.Item1, v.Item2, v.Item3).ToDateTimeOffset()); } } [Test] public void Parse_From_Integer_Text_Values() { var values = new[] { Tuple.Create("-1", new LocalDate(1969, 12, 31)), Tuple.Create("0", new LocalDate(1970, 1, 1)), Tuple.Create("1", new LocalDate(1970, 1, 2)) }; foreach (var v in values) { Assert.AreEqual(v.Item2, LocalDate.Parse(v.Item1)); } } [Test] public void Parse_From_Standard_Format() { var values = new[] { Tuple.Create("1960-6-12", new LocalDate(1960, 6, 12)), Tuple.Create("1981-09-14", new LocalDate(1981, 9, 14)), Tuple.Create("1-1-1", new LocalDate(1, 1, 1)) }; foreach (var v in values) { Assert.AreEqual(v.Item2, LocalDate.Parse(v.Item1)); } } [Test] public void Parse_With_Wrong_Format_Should_Throw() { var values = new[] { "1960-1", "-1909-14", "-1-1" }; foreach (var v in values) { Assert.Throws<FormatException>(() => LocalDate.Parse(v)); } Assert.Throws<ArgumentNullException>(() => LocalDate.Parse(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using Xunit; namespace System.Reflection.Metadata.Tests { public class DocumentNameTests { [Fact] public unsafe void GetString1() { var blobHeapData = new byte[] { 0, // 0 2, // 1: blob size (byte)'a', // 2 (byte)'b', // 3 3, // 4: blob size (byte)'x', // 5 (byte)'y', // 6 (byte)'z', // 7 3, // 8: blob size (byte)'\\', // 9: separator 1, // 10: part #1 4, // 11: part #2 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(8); var name = blobHeap.GetDocumentName(handle); Assert.Equal(@"ab\xyz", name); Assert.True(blobHeap.DocumentNameEquals(handle, @"ab\xyz", ignoreCase: false)); Assert.True(blobHeap.DocumentNameEquals(handle, @"Ab\xYz", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, @"", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"a", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"ab", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"ab\", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"ab\x", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"ab\xy", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"abc\xyz", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"Ab\xYzz", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, @"Ab\xYz\", ignoreCase: true)); } } [Fact] public unsafe void GetString_EmptyParts() { var blobHeapData = new byte[] { 0, // 0 1, // 1: blob size (byte)'a', // 2 6, // 3: blob size (byte)'\\', // 4: separator 0, // 5: part #1 1, // 6: part #2 0, // 7: part #3 1, // 8: part #4 0, // 9: part #5 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(3); var name = blobHeap.GetDocumentName(handle); Assert.Equal(@"\a\\a\", name); Assert.True(blobHeap.DocumentNameEquals(handle, @"\A\\A\", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, @"", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a\", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a\\", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a\\a", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a\\a\a", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a\\aa\", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"\a\\\", ignoreCase: false)); } } [Fact] public unsafe void GetString_EmptySeparator() { var blobHeapData = new byte[] { 0, // 0 1, // 1: blob size (byte)'a', // 2 6, // 3: blob size 0, // 4: separator 0, // 5: part #1 1, // 6: part #2 0, // 7: part #3 1, // 8: part #4 0, // 9: part #5 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(3); var name = blobHeap.GetDocumentName(handle); Assert.Equal(@"aa", name); Assert.True(blobHeap.DocumentNameEquals(handle, @"aa", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"a", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"aaa", ignoreCase: false)); } } [Fact] public unsafe void GetString_Empty() { var blobHeapData = new byte[] { 0, // 0 1, // 1: blob size (byte)'a', // 2 6, // 3: blob size 0, // 4: separator 0, // 5: part #1 0, // 6: part #2 0, // 7: part #3 0, // 8: part #4 0, // 9: part #5 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(3); var name = blobHeap.GetDocumentName(handle); Assert.Equal(@"", name); Assert.True(blobHeap.DocumentNameEquals(handle, @"", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, @"a", ignoreCase: false)); } } [Fact] public unsafe void GetString_IgnoreSeparatorCase() { var blobHeapData = new byte[] { 0, // 0 1, // 1: blob size (byte)'b', // 2 3, // 3: blob size (byte)'a', // 4: separator 1, // 5: part #1 1, // 6: part #2 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(3); var name = blobHeap.GetDocumentName(handle); Assert.Equal("bab", name); Assert.True(blobHeap.DocumentNameEquals(handle, "bab", ignoreCase: false)); Assert.True(blobHeap.DocumentNameEquals(handle, "BAB", ignoreCase: true)); Assert.True(blobHeap.DocumentNameEquals(handle, "bAb", ignoreCase: true)); Assert.True(blobHeap.DocumentNameEquals(handle, "BaB", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, "", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, "B", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, "bA", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, "bAbA", ignoreCase: true)); } } [Fact] public unsafe void GetString_NonAscii() { var blobHeapData = new byte[] { 0, // 0 3, // 1: blob size 0xe1, // 2: U+1234 in UTF8 0x88, // 3 0xb4, // 4 1, // 5: blob size (byte)'b', // 6 4, // 7: blob size (byte)'a', // 8: separator 5, // 9: part #1 1, // 10: part #2 5, // 11: part #3 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(7); var name = blobHeap.GetDocumentName(handle); Assert.Equal("ba\u1234ab", name); Assert.True(blobHeap.DocumentNameEquals(handle, "ba\u1234ab", ignoreCase: false)); Assert.True(blobHeap.DocumentNameEquals(handle, "BA\u1234AB", ignoreCase: true)); Assert.False(blobHeap.DocumentNameEquals(handle, "b\u1234ab", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, "a\u1234ab", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, "ba\u1234abb", ignoreCase: false)); } } [Fact] public unsafe void GetString_Errors() { var blobHeapData = new byte[] { 0, // 0 2, // 1: blob size 0x80, // 2: separator 0, // 3: part #1 }; fixed (byte* ptr = blobHeapData) { var blobHeap = new BlobHeap(new MemoryBlock(ptr, blobHeapData.Length), MetadataKind.Ecma335); var handle = DocumentNameBlobHandle.FromOffset(1); Assert.Throws<BadImageFormatException>(() => blobHeap.GetDocumentName(handle)); Assert.False(blobHeap.DocumentNameEquals(handle, "", ignoreCase: false)); Assert.False(blobHeap.DocumentNameEquals(handle, "a", ignoreCase: false)); Assert.Throws<BadImageFormatException>(() => blobHeap.GetDocumentName(default(DocumentNameBlobHandle))); Assert.Throws<BadImageFormatException>(() => blobHeap.GetDocumentName(DocumentNameBlobHandle.FromOffset(8))); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RoutesOperations operations. /// </summary> internal partial class RoutesOperations : IServiceOperations<NetworkClient>, IRoutesOperations { /// <summary> /// Initializes a new instance of the RoutesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RoutesOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Route>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (routeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("routeName", routeName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Route>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a route in the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create or update route operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Route>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Route> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all routes in a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Route>>> ListWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Route>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified route from a route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (routeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("routeName", routeName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a route in the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='routeName'> /// The name of the route. /// </param> /// <param name='routeParameters'> /// Parameters supplied to the create or update route operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Route>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (routeName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeName"); } if (routeParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeParameters"); } if (routeParameters != null) { routeParameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("routeName", routeName); tracingParameters.Add("routeParameters", routeParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(routeParameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(routeParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Route>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all routes in a route table. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Route>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Route>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Text; using System.IO; using System.Globalization; namespace fyiReporting.RdlDesign { /// <summary> /// Control supports the properties for DataSet/Rows elements. This is an extension to /// the RDL specification allowing data to be defined within a report. /// </summary> internal class DataSetRowsCtl : System.Windows.Forms.UserControl, IProperty { private DesignXmlDraw _Draw; private DataSetValues _dsv; private XmlNode _dsNode; private DataTable _DataTable; private System.Windows.Forms.Button bDelete; private System.Windows.Forms.DataGridTableStyle dgTableStyle; private System.Windows.Forms.Button bUp; private System.Windows.Forms.Button bDown; private System.Windows.Forms.CheckBox chkRowsFile; private System.Windows.Forms.Button bRowsFile; private System.Windows.Forms.DataGrid dgRows; private System.Windows.Forms.TextBox tbRowsFile; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button bLoad; private System.Windows.Forms.Button bClear; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal DataSetRowsCtl(DesignXmlDraw dxDraw, XmlNode dsNode, DataSetValues dsv) { _Draw = dxDraw; _dsv = dsv; _dsNode = dsNode; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { CreateDataTable(); // create data table based on the existing fields XmlNode rows = _Draw.GetNamedChildNode(_dsNode, "Rows"); if (rows == null) rows = _Draw.GetNamedChildNode(_dsNode, "fyi:Rows"); string file=null; if (rows != null) { file = _Draw.GetElementAttribute(rows, "File", null); PopulateRows(rows); } this.dgRows.DataSource = _DataTable; if (file != null) { tbRowsFile.Text = file; this.chkRowsFile.Checked = true; } chkRowsFile_CheckedChanged(this, new EventArgs()); } private void CreateDataTable() { _DataTable = new DataTable(); dgTableStyle.GridColumnStyles.Clear(); // reset the grid column styles foreach (DataRow dr in _dsv.Fields.Rows) { if (dr[0] == DBNull.Value) continue; if (dr[2] == DBNull.Value) {} else if (((string) dr[2]).Length > 0) continue; string name = (string) dr[0]; DataGridTextBoxColumn dgc = new DataGridTextBoxColumn(); dgTableStyle.GridColumnStyles.Add(dgc); dgc.HeaderText = name; dgc.MappingName = name; dgc.Width = 75; string type = dr["TypeName"] as string; Type t = type == null || type.Length == 0? typeof(string): fyiReporting.RDL.DataType.GetStyleType(type); _DataTable.Columns.Add(new DataColumn(name,t)); } } private void PopulateRows(XmlNode rows) { object[] rowValues = new object[_DataTable.Columns.Count]; bool bSkipMsg = false; foreach (XmlNode rNode in rows.ChildNodes) { if (rNode.Name != "Row") continue; int col=0; bool bBuiltRow=false; // if all columns will be null we won't add the row foreach (DataColumn dc in _DataTable.Columns) { XmlNode dNode = _Draw.GetNamedChildNode(rNode, dc.ColumnName); if (dNode != null) bBuiltRow = true; if (dNode == null) rowValues[col] = null; else if (dc.DataType == typeof(string)) rowValues[col] = dNode.InnerText; else { object box; try { if (dc.DataType == typeof(int)) box = Convert.ToInt32(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (dc.DataType == typeof(decimal)) box = Convert.ToDecimal(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (dc.DataType == typeof(long)) box = Convert.ToInt64(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (DesignerUtility.IsNumeric(dc.DataType)) // catch all numeric box = Convert.ToDouble(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (dc.DataType == typeof(DateTime)) { box = Convert.ToDateTime(dNode.InnerText, System.Globalization.DateTimeFormatInfo.InvariantInfo); } else { box = dNode.InnerText; } rowValues[col] = box; } catch (Exception e) { if (!bSkipMsg) { if (MessageBox.Show(string.Format("Unable to convert {1} to {0}: {2}", dc.DataType.ToString(), dNode.InnerText, e.Message) + Environment.NewLine + "Do you want to see any more errors?", "Error Reading Data Rows", MessageBoxButtons.YesNo) == DialogResult.No) bSkipMsg = true; } rowValues[col] = dNode.InnerText; } } col++; } if (bBuiltRow) _DataTable.Rows.Add(rowValues); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgRows = new System.Windows.Forms.DataGrid(); this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.bDelete = new System.Windows.Forms.Button(); this.bUp = new System.Windows.Forms.Button(); this.bDown = new System.Windows.Forms.Button(); this.chkRowsFile = new System.Windows.Forms.CheckBox(); this.tbRowsFile = new System.Windows.Forms.TextBox(); this.bRowsFile = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.bLoad = new System.Windows.Forms.Button(); this.bClear = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dgRows)).BeginInit(); this.SuspendLayout(); // // dgRows // this.dgRows.CaptionVisible = false; this.dgRows.DataMember = ""; this.dgRows.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgRows.Location = new System.Drawing.Point(8, 48); this.dgRows.Name = "dgRows"; this.dgRows.Size = new System.Drawing.Size(376, 200); this.dgRows.TabIndex = 2; this.dgRows.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.dgTableStyle}); // // dgTableStyle // this.dgTableStyle.AllowSorting = false; this.dgTableStyle.DataGrid = this.dgRows; this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgTableStyle.MappingName = ""; // // bDelete // this.bDelete.Location = new System.Drawing.Point(392, 48); this.bDelete.Name = "bDelete"; this.bDelete.Size = new System.Drawing.Size(48, 23); this.bDelete.TabIndex = 1; this.bDelete.Text = "Delete"; this.bDelete.Click += new System.EventHandler(this.bDelete_Click); // // bUp // this.bUp.Location = new System.Drawing.Point(392, 80); this.bUp.Name = "bUp"; this.bUp.Size = new System.Drawing.Size(48, 23); this.bUp.TabIndex = 3; this.bUp.Text = "Up"; this.bUp.Click += new System.EventHandler(this.bUp_Click); // // bDown // this.bDown.Location = new System.Drawing.Point(392, 112); this.bDown.Name = "bDown"; this.bDown.Size = new System.Drawing.Size(48, 23); this.bDown.TabIndex = 4; this.bDown.Text = "Down"; this.bDown.Click += new System.EventHandler(this.bDown_Click); // // chkRowsFile // this.chkRowsFile.Location = new System.Drawing.Point(8, 8); this.chkRowsFile.Name = "chkRowsFile"; this.chkRowsFile.Size = new System.Drawing.Size(136, 24); this.chkRowsFile.TabIndex = 5; this.chkRowsFile.Text = "Use XML file for data"; this.chkRowsFile.CheckedChanged += new System.EventHandler(this.chkRowsFile_CheckedChanged); // // tbRowsFile // this.tbRowsFile.Location = new System.Drawing.Point(144, 8); this.tbRowsFile.Name = "tbRowsFile"; this.tbRowsFile.Size = new System.Drawing.Size(240, 20); this.tbRowsFile.TabIndex = 6; this.tbRowsFile.Text = ""; // // bRowsFile // this.bRowsFile.Location = new System.Drawing.Point(392, 8); this.bRowsFile.Name = "bRowsFile"; this.bRowsFile.Size = new System.Drawing.Size(24, 23); this.bRowsFile.TabIndex = 7; this.bRowsFile.Text = "..."; this.bRowsFile.Click += new System.EventHandler(this.bRowsFile_Click); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(16, 256); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(368, 23); this.label1.TabIndex = 8; this.label1.Text = "Warning: this panel supports an extension to the RDL specification. This informa" + "tion will be ignored in RDL processors other than in fyiReporting."; // // bLoad // this.bLoad.Location = new System.Drawing.Point(392, 184); this.bLoad.Name = "bLoad"; this.bLoad.Size = new System.Drawing.Size(48, 48); this.bLoad.TabIndex = 9; this.bLoad.Text = "Load From SQL"; this.bLoad.Click += new System.EventHandler(this.bLoad_Click); // // bClear // this.bClear.Location = new System.Drawing.Point(392, 141); this.bClear.Name = "bClear"; this.bClear.Size = new System.Drawing.Size(48, 23); this.bClear.TabIndex = 10; this.bClear.Text = "Clear"; this.bClear.Click += new System.EventHandler(this.bClear_Click); // // DataSetRowsCtl // this.Controls.Add(this.bClear); this.Controls.Add(this.bLoad); this.Controls.Add(this.label1); this.Controls.Add(this.bRowsFile); this.Controls.Add(this.tbRowsFile); this.Controls.Add(this.chkRowsFile); this.Controls.Add(this.bDown); this.Controls.Add(this.bUp); this.Controls.Add(this.bDelete); this.Controls.Add(this.dgRows); this.Name = "DataSetRowsCtl"; this.Size = new System.Drawing.Size(488, 304); this.VisibleChanged += new System.EventHandler(this.DataSetRowsCtl_VisibleChanged); ((System.ComponentModel.ISupportInitialize)(this.dgRows)).EndInit(); this.ResumeLayout(false); } #endregion public bool IsValid() { if (this.chkRowsFile.Checked && this.tbRowsFile.Text.Length == 0) { MessageBox.Show("File name required when 'Use XML file for data checked'"); return false; } return true; } public void Apply() { // Remove the old row XmlNode rows = _Draw.GetNamedChildNode(this._dsNode, "Rows"); if (rows == null) rows = _Draw.GetNamedChildNode(this._dsNode, "fyi:Rows"); if (rows != null) _dsNode.RemoveChild(rows); // different result if we just want the file if (this.chkRowsFile.Checked) { rows = _Draw.GetCreateNamedChildNode(_dsNode, "fyi:Rows"); _Draw.SetElementAttribute(rows, "File", this.tbRowsFile.Text); } else { rows = GetXmlData(); if (rows.HasChildNodes) _dsNode.AppendChild(rows); } } private void bDelete_Click(object sender, System.EventArgs e) { this._DataTable.Rows.RemoveAt(this.dgRows.CurrentRowIndex); } private void bUp_Click(object sender, System.EventArgs e) { int cr = dgRows.CurrentRowIndex; if (cr <= 0) // already at the top return; SwapRow(_DataTable.Rows[cr-1], _DataTable.Rows[cr]); dgRows.CurrentRowIndex = cr-1; } private void bDown_Click(object sender, System.EventArgs e) { int cr = dgRows.CurrentRowIndex; if (cr < 0) // invalid index return; if (cr + 1 >= _DataTable.Rows.Count) return; // already at end SwapRow(_DataTable.Rows[cr+1], _DataTable.Rows[cr]); dgRows.CurrentRowIndex = cr+1; } private void SwapRow(DataRow tdr, DataRow fdr) { // Loop thru all the columns in a row and swap the data for (int ci=0; ci < _DataTable.Columns.Count; ci++) { object save = tdr[ci]; tdr[ci] = fdr[ci]; fdr[ci] = save; } return; } private void chkRowsFile_CheckedChanged(object sender, System.EventArgs e) { this.tbRowsFile.Enabled = chkRowsFile.Checked; this.bRowsFile.Enabled = chkRowsFile.Checked; this.bDelete.Enabled = !chkRowsFile.Checked; this.bUp.Enabled = !chkRowsFile.Checked; this.bDown.Enabled = !chkRowsFile.Checked; this.dgRows.Enabled = !chkRowsFile.Checked; } private void bRowsFile_Click(object sender, System.EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "XML files (*.xml)|*.xml" + "|All files (*.*)|*.*"; ofd.FilterIndex = 1; ofd.FileName = "*.xml"; ofd.Title = "Specify XML File Name"; ofd.DefaultExt = "xml"; ofd.AddExtension = true; try { if (ofd.ShowDialog() == DialogResult.OK) { string file = Path.GetFileName(ofd.FileName); this.tbRowsFile.Text = file; } } finally { ofd.Dispose(); } } private bool DidFieldsChange() { int col=0; foreach (DataRow dr in _dsv.Fields.Rows) { if (col >= _DataTable.Columns.Count) return true; if (dr[0] == DBNull.Value) continue; if (dr[2] == DBNull.Value) {} else if (((string) dr[2]).Length > 0) continue; string name = (string) (dr[1] == DBNull.Value? dr[0]: dr[1]); if (_DataTable.Columns[col].ColumnName != name) return true; col++; } if (col == _DataTable.Columns.Count) return false; else return true; } private XmlNode GetXmlData() { XmlDocumentFragment fDoc = _Draw.ReportDocument.CreateDocumentFragment(); XmlNode rows = _Draw.CreateElement(fDoc, "fyi:Rows", null); foreach (DataRow dr in _DataTable.Rows) { XmlNode row = _Draw.CreateElement(rows, "Row", null); bool bRowBuilt=false; foreach (DataColumn dc in _DataTable.Columns) { if (dr[dc] == DBNull.Value) continue; string val; if (dc.DataType == typeof(DateTime)) { val = Convert.ToString(dr[dc], System.Globalization.DateTimeFormatInfo.InvariantInfo); } else { val = Convert.ToString(dr[dc], NumberFormatInfo.InvariantInfo); } if (val == null) continue; _Draw.CreateElement(row, dc.ColumnName, val); bRowBuilt = true; // we've populated at least one column; so keep row } if (!bRowBuilt) rows.RemoveChild(row); } return rows; } private void DataSetRowsCtl_VisibleChanged(object sender, System.EventArgs e) { if (!DidFieldsChange()) // did the structure of the fields change return; // Need to reset the data; this assumes that some of the data rows are similar XmlNode rows = GetXmlData(); // get old data CreateDataTable(); // this recreates the datatable PopulateRows(rows); // repopulate the datatable this.dgRows.DataSource = _DataTable; // this recreates the datatable so reset grid } private void bClear_Click(object sender, System.EventArgs e) { this._DataTable.Rows.Clear(); } private void bLoad_Click(object sender, System.EventArgs e) { // Load the data from the SQL; we append the data to what already exists try { // Obtain the connection information XmlNode rNode = _Draw.GetReportNode(); XmlNode dsNode = _Draw.GetNamedChildNode(rNode, "DataSources"); if (dsNode == null) return; XmlNode datasource=null; foreach (XmlNode dNode in dsNode) { if (dNode.Name != "DataSource") continue; XmlAttribute nAttr = dNode.Attributes["Name"]; if (nAttr == null) // shouldn't really happen continue; if (nAttr.Value != _dsv.DataSourceName) continue; datasource = dNode; break; } if (datasource == null) { MessageBox.Show(string.Format("Datasource '{0}' not found.", _dsv.DataSourceName), "Load Failed"); return; } // get the connection information string connection = ""; string dataProvider = ""; string dataSourceReference = _Draw.GetElementValue(datasource, "DataSourceReference", null); if (dataSourceReference != null) { // This is not very pretty code since it is assuming the structure of the windows parenting. // But there isn't any other way to get this information from here. Control p = _Draw; MDIChild mc = null; while (p != null && !(p is RdlDesigner)) { if (p is MDIChild) mc = (MDIChild)p; p = p.Parent; } if (p == null || mc == null || mc.SourceFile == null) { MessageBox.Show("Unable to locate DataSource Shared file. Try saving report first"); return; } string filename = Path.GetDirectoryName(mc.SourceFile) + Path.DirectorySeparatorChar + dataSourceReference; if (!DesignerUtility.GetSharedConnectionInfo((RdlDesigner) p, filename, out dataProvider, out connection)) return; } else { XmlNode cpNode = DesignXmlDraw.FindNextInHierarchy(datasource, "ConnectionProperties", "ConnectString"); connection = cpNode == null ? "" : cpNode.InnerText; XmlNode datap = DesignXmlDraw.FindNextInHierarchy(datasource, "ConnectionProperties", "DataProvider"); dataProvider = datap == null ? "" : datap.InnerText; } // Populate the data table DesignerUtility.GetSqlData(dataProvider, connection, _dsv.CommandText, null, _DataTable); } catch (Exception ex) { MessageBox.Show(ex.Message, "Load Failed"); } } } }
#region License, Terms and Author(s) // // Gurtle - IBugTraqProvider for Google Code // Copyright (c) 2011 Sven Strickroth. All rights reserved. // Copyright (c) 2008, 2009 Atif Aziz. All rights reserved. // // Author(s): // // Sven Strickroth, <email@cs-ware.de> // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace Gurtle.Providers.GitHub { #region Imports using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; #endregion internal class GitHubRepository : IProvider { public static readonly Uri HostingUrl = new Uri("https://www.github.com/"); public event EventHandler Loaded; public string Name { get { return "github"; } } private string _projectName = null; public string ProjectName { get { return _projectName; } set { if (value == null) throw new ArgumentNullException("projectName"); if (!IsValidProjectName(value)) throw new ArgumentException("invalid project name.", value); _projectName = value; } } public Uri Url { get { Debug.Assert(ProjectName != null); return new Uri(HostingUrl, ProjectName); } } public IList<string> ClosedStatuses { get; private set; } public bool IsLoaded { get; private set; } public bool IsLoading { get { return false; } } public bool CanHandleIssueUpdates() { return true; } public GitHubRepository() { commonConstructor(); } private void commonConstructor() { ClosedStatuses = new string[1]; ClosedStatuses[0] = "closed"; IsLoaded = true; } public GitHubRepository(string projectName) { ProjectName = projectName; commonConstructor(); } public Uri IssueDetailUrl(int id) { return FormatUrl("/" + ProjectName + "/issues/{0}", id); } public Uri RevisionDetailUrl(int revision) { return FormatUrl("source/detail?r={0}", revision); } public Uri IssuesUrl() { Debug.Assert(ProjectName != null); return new Uri("https://api.github.com/repos/" + ProjectName + "/issues"); } private Uri FormatUrl(string relativeUrl) { Debug.Assert(ProjectName != null); var baseUrl = new Uri("https://github.com/api/v2/json/"); return string.IsNullOrEmpty(relativeUrl) ? baseUrl : new Uri(baseUrl, relativeUrl); } private Uri FormatUrl(string relativeUrl, params object[] args) { return FormatUrl(string.Format(CultureInfo.InvariantCulture, relativeUrl, args)); } public bool IsClosedStatus(string status) { return !string.IsNullOrEmpty(status) && status == "closed"; } public void CancelLoad() { } public void Load() { if (IsLoaded) return; Reload(); } private void OnLoaded() { OnLoaded(null); } private void OnLoaded(EventArgs args) { var handler = Loaded; if (handler != null) handler(this, args ?? EventArgs.Empty); } public void Reload() { Debug.Assert(ProjectName != null); if (IsLoading) return; OnLoaded(null); } public bool IsValidProjectName(string name) { if (name == null) throw new ArgumentNullException("name"); return name.Length > 0 && Regex.IsMatch(name, @"^[A-Za-z][A-Za-z0-9-]*/[A-Za-z][A-Za-z0-9-]*$"); } public Uri CloseIssueUrl(string status, int issueid) { return FormatUrl("issues/close/" + ProjectName + "/" + issueid); } public Uri CommentIssueUrl(int issueid) { return FormatUrl("issues/comment/" + ProjectName + "/" + issueid); } public Action DownloadIssues(string project, int start, bool includeClosedIssues, Func<IEnumerable<Issue>, bool> onData, Action<DownloadProgressChangedEventArgs> onProgress, Action<bool, Exception> onCompleted) { Debug.Assert(project != null); Debug.Assert(onData != null); var client = new Gurtle.WebClient(); client.DownloadStringAsync(this.IssuesUrl()); client.DownloadStringCompleted += (sender, args) => { if (args.Cancelled || args.Error != null) { if (onCompleted != null) onCompleted(args.Cancelled, args.Error); return; } var issues = IssueTableParser.Parse(args.Result).ToArray(); onData(issues); if (onCompleted != null) onCompleted(false, null); }; if (onProgress != null) client.DownloadProgressChanged += (sender, args) => onProgress(args); return client.CancelAsync; } public ListViewSorter<ListViewItem<Issue>, Issue> GenerateListViewSorter(ListView issueListView) { return new ListViewSorter<ListViewItem<Issue>, Issue>(issueListView, item => item.Tag, new Func<Issue, IComparable>[] { issue => (IComparable) issue.Id, issue => (IComparable) issue.Status, issue => (IComparable) issue.Owner, issue => (IComparable) issue.Summary }); } public void GeneratorSubItems(ListViewItem<Issue> item, Issue issue) { var subItems = item.SubItems; subItems.Add(issue.Status); subItems.Add(issue.Owner); subItems.Add(issue.Summary); } public void SetupListView(ListView issueListView) { System.Windows.Forms.ColumnHeader statusColumn = new System.Windows.Forms.ColumnHeader(); System.Windows.Forms.ColumnHeader ownerColumn = new System.Windows.Forms.ColumnHeader(); System.Windows.Forms.ColumnHeader summaryColumn = new System.Windows.Forms.ColumnHeader(); statusColumn.Text = "Status"; statusColumn.Width = 100; ownerColumn.Text = "Owner"; ownerColumn.Width = 100; summaryColumn.Text = "Summary"; summaryColumn.Width = 1000; issueListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { statusColumn, ownerColumn, summaryColumn}); } public void FillSearchItems(ComboBox.ObjectCollection searchSourceItems) { searchSourceItems.Add(new Gurtle.IssueBrowserDialog.MultiFieldIssueSearchSource("All fields", MetaIssue.Properties)); foreach (Issue.IssueField field in Enum.GetValues(typeof(Issue.IssueField))) { searchSourceItems.Add(new Gurtle.IssueBrowserDialog.SingleFieldIssueSearchSource(field.ToString(), MetaIssue.GetPropertyByField(field), field == Issue.IssueField.Summary || field == Issue.IssueField.Id ? Gurtle.IssueBrowserDialog.SearchableStringSourceCharacteristics.None : Gurtle.IssueBrowserDialog.SearchableStringSourceCharacteristics.Predefined)); } } public void UpdateIssue(IssueUpdate update, NetworkCredential credential, Action<string> stdout, Action<string> stderr) { var client = new Gurtle.WebClient(); System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection(1); if (update.Comment.Length > 0) { data.Add("comment", update.Comment); } client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credential.UserName + ":" + credential.Password))); client.UploadValues(CommentIssueUrl(update.Issue.Id), data); data.Clear(); client.UploadValues(CloseIssueUrl(update.Status, update.Issue.Id), data); } public DialogResult ShowOptions(Parameters parameters) { OptionsDialog optionsDialog = new OptionsDialog { Parameters = parameters }; return optionsDialog.ShowDialog(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// HttpClientFailure operations. /// </summary> public partial interface IHttpClientFailure { /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Head400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Get400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Put400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Patch400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Post400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Delete400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 401 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Head401WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 402 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Get402WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 403 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Get403WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 404 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Put404WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 405 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Patch405WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 406 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Post406WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 407 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Delete407WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 409 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Put409WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 410 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Head410WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 411 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Get411WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 412 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Get412WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 413 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Put413WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 414 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Patch414WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 415 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Post415WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 416 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Get416WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 417 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Delete417WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 429 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> Task<HttpOperationResponse<Error>> Head429WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AdGroup</c> resource.</summary> public sealed partial class AdGroupName : gax::IResourceName, sys::IEquatable<AdGroupName> { /// <summary>The possible contents of <see cref="AdGroupName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>customers/{customer_id}/adGroups/{ad_group_id}</c>.</summary> CustomerAdGroup = 1, } private static gax::PathTemplate s_customerAdGroup = new gax::PathTemplate("customers/{customer_id}/adGroups/{ad_group_id}"); /// <summary>Creates a <see cref="AdGroupName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AdGroupName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupName"/> with the pattern <c>customers/{customer_id}/adGroups/{ad_group_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AdGroupName"/> constructed from the provided ids.</returns> public static AdGroupName FromCustomerAdGroup(string customerId, string adGroupId) => new AdGroupName(ResourceNameType.CustomerAdGroup, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupName"/> with pattern /// <c>customers/{customer_id}/adGroups/{ad_group_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupName"/> with pattern /// <c>customers/{customer_id}/adGroups/{ad_group_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId) => FormatCustomerAdGroup(customerId, adGroupId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupName"/> with pattern /// <c>customers/{customer_id}/adGroups/{ad_group_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupName"/> with pattern /// <c>customers/{customer_id}/adGroups/{ad_group_id}</c>. /// </returns> public static string FormatCustomerAdGroup(string customerId, string adGroupId) => s_customerAdGroup.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId))); /// <summary>Parses the given resource name string into a new <see cref="AdGroupName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroups/{ad_group_id}</c></description></item> /// </list> /// </remarks> /// <param name="adGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupName"/> if successful.</returns> public static AdGroupName Parse(string adGroupName) => Parse(adGroupName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroups/{ad_group_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AdGroupName"/> if successful.</returns> public static AdGroupName Parse(string adGroupName, bool allowUnparsed) => TryParse(adGroupName, allowUnparsed, out AdGroupName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroups/{ad_group_id}</c></description></item> /// </list> /// </remarks> /// <param name="adGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupName, out AdGroupName result) => TryParse(adGroupName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroups/{ad_group_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupName, bool allowUnparsed, out AdGroupName result) { gax::GaxPreconditions.CheckNotNull(adGroupName, nameof(adGroupName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroup.TryParseName(adGroupName, out resourceName)) { result = FromCustomerAdGroup(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AdGroupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupName"/> class from the component parts of pattern /// <c>customers/{customer_id}/adGroups/{ad_group_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupName(string customerId, string adGroupId) : this(ResourceNameType.CustomerAdGroup, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroup: return s_customerAdGroup.Expand(CustomerId, AdGroupId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AdGroupName); /// <inheritdoc/> public bool Equals(AdGroupName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupName a, AdGroupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupName a, AdGroupName b) => !(a == b); } public partial class AdGroup { /// <summary> /// <see cref="gagvr::AdGroupName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupName ResourceNameAsAdGroupName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AdGroupName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::AdGroupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal AdGroupName AdGroupName { get => string.IsNullOrEmpty(Name) ? null : gagvr::AdGroupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::AdGroupName"/>-typed view over the <see cref="BaseAdGroup"/> resource name property. /// </summary> internal AdGroupName BaseAdGroupAsAdGroupName { get => string.IsNullOrEmpty(BaseAdGroup) ? null : gagvr::AdGroupName.Parse(BaseAdGroup, allowUnparsed: true); set => BaseAdGroup = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupLabelName"/>-typed view over the <see cref="Labels"/> resource name property. /// </summary> internal gax::ResourceNameList<AdGroupLabelName> LabelsAsAdGroupLabelNames { get => new gax::ResourceNameList<AdGroupLabelName>(Labels, s => string.IsNullOrEmpty(s) ? null : AdGroupLabelName.Parse(s, allowUnparsed: true)); } } }
// Artificial Intelligence for Humans // Volume 2: Nature-Inspired Algorithms // C# Version // http://www.aifh.org // http://www.jeffheaton.com // // Code repository: // https://github.com/jeffheaton/aifh // // Copyright 2014 by Jeff Heaton // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using AIFH_Vol2.Core.Evolutionary.Population; using AIFH_Vol2.Core.Evolutionary.Species; using AIFH_Vol2.Core.Evolutionary.Train; using AIFH_Vol2.Core.Genetic.Crossover; using AIFH_Vol2.Core.Genetic.Genome; using AIFH_Vol2.Core.Genetic.Mutate; using AIFH_Vol2.Core.Learning.Score; using AIFH_Vol2.Core.Randomize; namespace AIFH_Vol2.Examples.GA.TSP { /// <summary> /// Find the shortest path through several cities with a genetic algorithm (GA). /// This example shows how to use it to find a potential solution to the Traveling Salesman Problem (TSP). /// /// Sample output: /// /// Running example: GeneticTSPExample /// Iteration: 1, Best Path Length = 5109 /// Iteration: 2, Best Path Length = 5109 /// Iteration: 3, Best Path Length = 5109 /// Iteration: 4, Best Path Length = 5109 /// Iteration: 5, Best Path Length = 5109 /// ... /// Iteration: 98, Best Path Length = 4816 /// Iteration: 99, Best Path Length = 4816 /// Iteration: 100, Best Path Length = 4816 /// Good solution found: /// 16>15>13>20>37>17>43>49>12>21>14>3>44>42>32>39>18>30>23>36>48>29>26>1>8>33>10>41 /// >31>2>7>0>28>11>6>9>40>34>4>22>47>25>24>35>27>46>5>19>45>38 /// </summary> public class GeneticTSPExample { /// <summary> /// The number of cities to visit. /// </summary> public const int Cities = 50; /// <summary> /// The size of the population. /// </summary> public const int PopulationSize = 1000; /// <summary> /// The square size of the map. /// </summary> public const int MapSize = 256; /// <summary> /// The maximum number of iterations to allow to have the same score before giving up. /// </summary> public const int MaxSameSolution = 50; /// <summary> /// The name of this example. /// </summary> public static string ExampleName = "Use a genetic algorithm (GA) for the travelling salesman problem (TSP)."; /// <summary> /// The chapter this example is from. /// </summary> public static int ExampleChapter = 3; /// <summary> /// The cities to visit. /// </summary> private City[] _cities; /// <summary> /// The genetic algorithm. /// </summary> private BasicEA _genetic; /// <summary> /// Place the cities in random locations. /// </summary> /// <param name="rnd">Random number.</param> private void InitCities(IGenerateRandom rnd) { _cities = new City[Cities]; for (int i = 0; i < _cities.Length; i++) { int xPos = rnd.NextInt(0, MapSize); int yPos = rnd.NextInt(0, MapSize); _cities[i] = new City(xPos, yPos); } } /// <summary> /// Generate a random path through cities. /// </summary> /// <param name="rnd">Random number generator.</param> /// <returns>A genome.</returns> private IntegerArrayGenome RandomGenome(IGenerateRandom rnd) { var result = new IntegerArrayGenome(_cities.Length); int[] organism = result.Data; var taken = new bool[_cities.Length]; for (int i = 0; i < organism.Length - 1; i++) { int icandidate; do { icandidate = rnd.NextInt(0, organism.Length); } while (taken[icandidate]); organism[i] = icandidate; taken[icandidate] = true; if (i == organism.Length - 2) { icandidate = 0; while (taken[icandidate]) { icandidate++; } organism[i + 1] = icandidate; } } return result; } /// <summary> /// Create an initial random population of random paths through the cities. /// </summary> /// <param name="rnd">The random population.</param> /// <returns>The population</returns> private IPopulation InitPopulation(IGenerateRandom rnd) { IPopulation result = new BasicPopulation(PopulationSize, null); var defaultSpecies = new BasicSpecies(); defaultSpecies.Population = result; for (int i = 0; i < PopulationSize; i++) { IntegerArrayGenome genome = RandomGenome(rnd); defaultSpecies.Add(genome); } result.GenomeFactory = new IntegerArrayGenomeFactory(_cities.Length); result.Species.Add(defaultSpecies); return result; } /// <summary> /// Display the cities in the final path. /// </summary> /// <param name="solution">The solution to display.</param> public void DisplaySolution(IntegerArrayGenome solution) { bool first = true; int[] path = solution.Data; foreach (int aPath in path) { if (!first) Console.Write(">"); Console.Write("" + aPath); first = false; } Console.WriteLine(); } /// <summary> /// Setup and solve the TSP. /// </summary> public void Solve() { IGenerateRandom rnd = new MersenneTwisterGenerateRandom(); var builder = new StringBuilder(); InitCities(rnd); IPopulation pop = InitPopulation(rnd); IScoreFunction score = new TSPScore(_cities); _genetic = new BasicEA(pop, score); _genetic.AddOperation(0.9, new SpliceNoRepeat(Cities / 3)); _genetic.AddOperation(0.1, new MutateShuffle()); int sameSolutionCount = 0; int iteration = 1; double lastSolution = double.MaxValue; while (sameSolutionCount < MaxSameSolution) { _genetic.Iteration(); double thisSolution = _genetic.LastError; builder.Length = 0; builder.Append("Iteration: "); builder.Append(iteration++); builder.Append(", Best Path Length = "); builder.Append(thisSolution); Console.WriteLine(builder.ToString()); if (Math.Abs(lastSolution - thisSolution) < 1.0) { sameSolutionCount++; } else { sameSolutionCount = 0; } lastSolution = thisSolution; } Console.WriteLine("Good solution found:"); var best = (IntegerArrayGenome)_genetic.BestGenome; DisplaySolution(best); _genetic.FinishTraining(); } /// <summary> /// The entry point for this example. If you would like to make this example /// stand alone, then add to its own project and rename to Main. /// </summary> /// <param name="args">Not used.</param> public static void ExampleMain(string[] args) { var solve = new GeneticTSPExample(); solve.Solve(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Northwind.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
'From Squeak 1.3 of Jan 16, 1998 on 20 January 1998 at 1:47:18 pm'! ColorSystemView subclass: #BrowserView instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Interface-Browser'! !BrowserView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 13:26'! classBrowser: aBrowser editString: aString "Answer an instance of me on the model, aBrowser. The instance consists of four subviews, starting with the list view of classes in the model's currently selected system category. The initial text view part is a view of the characters in aString." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | browserView classListView messageCategoryListView switchView messageListView browserCodeView | browserView _ self new model: aBrowser. classListView _ self buildClassListView: aBrowser. switchView _ self buildInstanceClassSwitchView: aBrowser. messageCategoryListView _ self buildMessageCategoryListView: aBrowser. messageListView _ self buildMessageListView: aBrowser. browserCodeView _ self buildBrowserCodeView: aBrowser editString: aString. classListView borderWidthLeft: 2 right: 0 top: 2 bottom: 0. classListView scrollingView singleItemMode: true. classListView scrollingView noTopDelimiter. classListView scrollingView noBottomDelimiter. classListView scrollingView list: classListView scrollingView getList. switchView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. browserView addSubView: classListView. browserView addSubView: switchView. browserView addSubView: messageCategoryListView. browserView addSubView: messageListView. browserView addSubView: browserCodeView. messageListView align: messageListView viewport topLeft with: messageCategoryListView viewport topRight. classListView window: classListView window viewport: (messageCategoryListView viewport topLeft - (0 @ 12) corner: messageCategoryListView viewport topRight). switchView window: switchView window viewport: (messageListView viewport topLeft - (0 @ 12) corner: messageListView viewport topRight). browserCodeView window: browserCodeView window viewport: (messageCategoryListView viewport bottomLeft corner: messageListView viewport bottomRight + (0 @ 110)). aString notNil ifTrue: [aBrowser lock]. ^browserView! ! !BrowserView class methodsFor: 'private' stamp: 'ssa 12/11/97 13:13'! buildBrowserCodeView: aBrowser editString: aString "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | aBrowserCodeView | aBrowserCodeView _ SSAScrollBarView on: BrowserCodeView new. aBrowserCodeView scrollingView model: aBrowser. aBrowserCodeView window: (0 @ 0 extent: 200 @ 110). aBrowserCodeView borderWidthLeft: 2 right: 2 top: 0 bottom: 2. aString ~~ nil ifTrue: [aBrowserCodeView scrollingView editString: aString]. ^aBrowserCodeView! ! !BrowserView class methodsFor: 'private' stamp: 'ssa 12/11/97 13:25'! buildClassListView: aBrowser "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | aClassListView | aClassListView _ SSAScrollBarView on:ClassListView new. aClassListView scrollingView model: aBrowser. aClassListView window: (0 @ 0 extent: 50 @ 62). aClassListView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. ^aClassListView! ! !BrowserView class methodsFor: 'private' stamp: 'ssa 12/11/97 13:28'! buildMessageCategoryListView: aBrowser "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | aMessageCategoryListView | aMessageCategoryListView _ SSAScrollBarView on:MessageCategoryListView new. aMessageCategoryListView scrollingView model: aBrowser. aMessageCategoryListView window: (0 @ 0 extent: 50 @ 70). aMessageCategoryListView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. ^aMessageCategoryListView! ! !BrowserView class methodsFor: 'private' stamp: 'ssa 12/11/97 13:29'! buildMessageListView: aBrowser "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | aMessageListView | aMessageListView _ SSAScrollBarView on: MessageListView new. aMessageListView scrollingView model: aBrowser. aMessageListView window: (0 @ 0 extent: 50 @ 70). aMessageListView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. ^ aMessageListView! ! !BrowserView class methodsFor: 'private' stamp: 'ssa 12/11/97 13:29'! buildSystemCategoryListView: aBrowser "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | aSystemCategoryListView | aSystemCategoryListView _ SSAScrollBarView on: SystemCategoryListView new. aSystemCategoryListView scrollingView model: aBrowser. aSystemCategoryListView window: (0 @ 0 extent: 50 @ 70). aSystemCategoryListView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. ^aSystemCategoryListView! ! !ChangeList class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 12:24'! open: aChangeList name: aString withListView: aListView "Create a standard system view for the messageSet, whose label is aString. The listView supplied may be either single or multiple selection type" "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView codeView lv cv | topView _ StandardSystemView new. topView model: aChangeList. topView label: aString. topView minimumSize: 180 @ 120. aListView model: aChangeList. aListView list: aChangeList list. aListView window: (0 @ 0 extent: 180 @ 100). topView addSubView: (lv _ SSAScrollBarView on: aListView ). lv borderWidthLeft: 2 right: 2 top: 2 bottom: 0. codeView _ StringHolderView new. codeView model: aChangeList. codeView window: (0 @ 0 extent: 180 @ 300). topView addSubView: ( cv _ SSAScrollBarView on: codeView ) align: cv viewport topLeft with: lv viewport bottomLeft. cv borderWidthLeft: 2 right: 2 top: 2 bottom: 2. topView controller open ! ! !ChangeSorter methodsFor: 'creation' stamp: 'ssa 12/11/97 12:24'! openView: topView "Create change sorter on one changeSet only. Two of these in a DualChangeSorter." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | classView messageView codeView | buttonView _ SwitchView new. buttonView model: self controller: TriggerController new. buttonView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. buttonView selector: #whatPolarity. buttonView controller selector: #cngSetActivity. buttonView window: (0 @ 0 extent: 360 @ 20). buttonView label: myChangeSet name asParagraph. classView _ SSAScrollBarView on: GeneralListView new. classView scrollingView controllerClass: GeneralListController. classView scrollingView model: classList. classView scrollingView window: (0 @ 0 extent: 180 @ 160). classView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. classView scrollingView controller yellowButtonMenu: ClassMenu yellowButtonMessages: ClassSelectors. classList scrollingView controller: classView controller. messageView _ SSAScrollBarView on: GeneralListView new. messageView scrollingView controllerClass: GeneralListController. messageView scrollingView model: messageList. messageView scrollingView window: (0 @ 0 extent: 180 @ 160). messageView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. messageView scrollingView controller yellowButtonMenu: MsgListMenu yellowButtonMessages: MsgListSelectors. messageList scrollingView controller: messageView controller. codeView _ SSAScrollBarView on: BrowserCodeView new. codeView scrollingView model: self. codeView scrollingView window: (0 @ 0 extent: 360 @ 180). codeView borderWidthLeft: 2 right: 2 top: 0 bottom: 2. topView addSubView: buttonView. topView addSubView: classView below: buttonView. topView addSubView: messageView toRightOf: classView. topView addSubView: codeView below: classView. " classView align: classView viewport topLeft with: buttonView viewport bottomLeft. messageView align: messageView viewport topLeft with: classView viewport topRight. codeView align: codeView viewport topLeft with: classView viewport bottomLeft. "! ! !ChangeSorter methodsFor: 'creation' stamp: 'ssa 12/11/97 16:25'! openView: topView offsetBy: offset "Create change sorter on one changeSet with 0@0. Two of these in a DualChangeSorter, right one is offset by 360@0." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | classView messageView codeView | buttonView _ SwitchView new. buttonView model: self controller: TriggerController new. buttonView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. buttonView selector: #whatPolarity. buttonView controller selector: #cngSetActivity. buttonView window: ((0 @ 0 extent: 360 @ 20) translateBy: offset). buttonView label: myChangeSet name asParagraph. classView _ SSAScrollBarView on: GeneralListView new. classView scrollingView controllerClass: GeneralListController. classView scrollingView model: classList. classView window: (0 @ 0 extent: 180 @ 160). classView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. classView scrollingView controller yellowButtonMenu: ClassMenu yellowButtonMessages: ClassSelectors. classList controller: classView scrollingView controller. messageView _ SSAScrollBarView on: GeneralListView new. messageView scrollingView controllerClass: GeneralListController. messageView scrollingView model: messageList. messageView window: (0 @ 0 extent: 180 @ 160). messageView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. messageView scrollingView controller yellowButtonMenu: MsgListMenu yellowButtonMessages: MsgListSelectors. messageList controller: messageView scrollingView controller. codeView _ SSAScrollBarView on: BrowserCodeView new. codeView scrollingView model: self. codeView window: (0 @ 0 extent: 360 @ 180). codeView borderWidthLeft: 2 right: 2 top: 0 bottom: 2. topView addSubView: buttonView. topView addSubView: classView below: buttonView. topView addSubView: messageView toRightOf: classView. topView addSubView: codeView below: classView. ! ! !DebuggerView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 15:31'! debugger: aDebugger "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" "Answer a DebuggerView whose model is aDebugger. It consists of three subviews, a ContextStackView (the ContextStackListView and ContextStackCodeView), an InspectView of aDebugger's variables, and an InspectView of the variables of the currently selected method context." | topView stackListView stackCodeView rcvrVarView rcvrValView ctxtVarView ctxtValView | aDebugger expandStack. topView _ self new model: aDebugger. stackListView _ SSAScrollBarView on: (ContextStackListView new model: aDebugger). stackListView window: (0 @ 0 extent: 150 @ 50). stackListView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. topView addSubView: stackListView. stackCodeView _ SSAScrollBarView on: (ContextStackCodeView new model: aDebugger). stackCodeView scrollingView controller: ContextStackCodeController new. stackCodeView window: (0 @ 0 extent: 150 @ 75). stackCodeView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. topView addSubView: stackCodeView below: stackListView. rcvrVarView _ SSAScrollBarView on:(InspectListView new model: aDebugger receiverInspector). rcvrVarView window: (0 @ 0 extent: 25 @ 50). rcvrVarView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. topView addSubView: rcvrVarView below: stackCodeView. rcvrValView _ SSAScrollBarView on:(InspectCodeView new model: aDebugger receiverInspector). rcvrValView window: (0 @ 0 extent: 50 @ 50). rcvrValView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. topView addSubView: rcvrValView toRightOf: rcvrVarView. ctxtVarView _ SSAScrollBarView on:(InspectListView new model: aDebugger contextVariablesInspector). ctxtVarView window: (0 @ 0 extent: 25 @ 50). ctxtVarView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. topView addSubView: ctxtVarView toRightOf: rcvrValView. ctxtValView _ SSAScrollBarView on:(InspectCodeView new model: aDebugger contextVariablesInspector). ctxtValView window: (0 @ 0 extent: 50 @ 50). ctxtValView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. topView addSubView: ctxtValView toRightOf: ctxtVarView. ^ topView! ! !DebuggerView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 13:13'! openNotifier: aDebugger contents: msgString label: label "Create and schedule a simple view with a debugger which can be opened later." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | msg aStringHolderView topView nLines displayPoint shv | Cursor normal show. Sensor flushKeyboard. msg _ msgString. (label beginsWith: 'Space is low') ifTrue: [msg _ self lowSpaceChoices, msg]. aStringHolderView _ StringHolderView container: (StringHolder new contents: msg). aStringHolderView controller: (NotifyStringHolderController debugger: aDebugger). topView _ StandardSystemView new. topView model: aStringHolderView model. topView addSubView: (shv _ SSAScrollBarView on: aStringHolderView ). shv borderWidth:2. topView label: label. nLines _ 1 + (msg occurrencesOf: Character cr). topView minimumSize: 350 @ (14 * nLines + 6). displayPoint _ ScheduledControllers activeController == nil ifTrue: [Display boundingBox center] ifFalse: [ScheduledControllers activeController view displayBox center]. topView controller openNoTerminateDisplayAt: displayPoint. ^ topView ! ! !DisplayTextView class methodsFor: 'examples' stamp: 'ssa 12/11/97 12:44'! open: textOrString label: aLabel "Create a system view with a paragraph editor in it. 6/2/96 sw" "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView aDisplayTextView | aDisplayTextView _ SSAScrollBarView on: (DisplayTextView new model: textOrString asDisplayText). aDisplayTextView borderWidth: 2. topView _ StandardSystemView new. topView label: aLabel. topView addSubView: aDisplayTextView. topView controller open "DisplayTextView open: 'Great green gobs' label: 'Gopher Guts'"! ! !FileModel class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 15:43'! open: aFileModel named: aString "Answer a scheduled view whose model is aFileModel and whose label is aString. " "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView aView | topView _ StandardSystemView new. topView model: aFileModel. topView label: aString. topView minimumSize: 180 @ 120. aView _ SSAScrollBarView on: (FileView new model: aFileModel). aView window: (0 @ 0 extent: 180 @ 120). aView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. topView addSubView: aView. topView controller open! ! !FileList class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 12:48'! openWithEditPane: withEdit "FileList open" "Open a view of an instance of me on the default directory. 2/14/96 sw: use standard directory. (6/96 functionality substantially changed by di) 7/12/96 sw: set the label to the pathname" "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView aTemplateView fileListView aFileView aFileList aFileTemplateHolder dir volListView | topView _ StandardSystemView new. aFileList _ self new directory: (dir _ FileDirectory default). topView model: aFileList. topView label: dir pathName. topView minimumSize: 200 @ (withEdit ifTrue: [200] ifFalse: [60]). volListView _ SSAScrollBarView on:ListView new. volListView scrollingView model: aFileList. volListView scrollingView list: aFileList list. volListView window: (0 @ 0 extent: 80 @ 45). volListView borderWidthLeft: 2 right: 1 top: 2 bottom: 1. topView addSubView: volListView. aFileTemplateHolder _ FileTemplateHolder on: aFileList. aTemplateView _ SSAScrollBarView on:StringHolderView new. aTemplateView scrollingView controller: FileTemplateController new. aTemplateView scrollingView model: aFileTemplateHolder. aTemplateView window: (0 @ 0 extent: 80 @ 15). aTemplateView borderWidthLeft: 2 right: 1 top: 1 bottom: 1. topView addSubView: aTemplateView below: volListView. fileListView _ SSAScrollBarView on:FileListView new. fileListView scrollingView model: aFileList. fileListView scrollingView controller: FileListController new. fileListView scrollingView list: aFileList fileList. fileListView window: (0 @ 0 extent: 120 @ 60). fileListView borderWidthLeft: 1 right: 2 top: 2 bottom: 1. topView addSubView: fileListView toRightOf: volListView. withEdit ifTrue: [ aFileView _ SSAScrollBarView on:FileView new. aFileView scrollingView model: aFileList. aFileView window: (0 @ 0 extent: 200 @ 140). aFileView borderWidthLeft: 2 right: 2 top: 1 bottom: 2. topView addSubView: aFileView below: aTemplateView. ]. topView controller open! ! !Inspector methodsFor: 'browser support' stamp: 'ssa 12/11/97 12:50'! buildAndArrangeSubViewsInside: aTopView "2/25/97 ssa - Added to support browse protocol" "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | inspector listView valueView evalView | inspector _ self. aTopView model: inspector. listView _ InspectListView new model: inspector. (inspector isMemberOf: DictionaryInspector) ifTrue: [listView controller: DictionaryListController new]. aTopView addSubView: (SSAScrollBarView on: listView ) in: (0@0 corner: (1/3)@(4/7)) borderWidth: 1. valueView _ InspectCodeView new model: inspector. aTopView addSubView: (SSAScrollBarView on: valueView ) in: ((1/3)@0 corner: 1@(4/7)) borderWidth: 1. evalView _ StringHolderView new model: (InspectorTrash for: inspector object). aTopView addSubView: (SSAScrollBarView on: evalView ) in: (0@(4/7) corner: 1@1) borderWidth: 1. ! ! !Inspector class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 15:40'! openOn: anObject withEvalPane: withEval withLabel: label valueViewClass: valueViewClass "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView inspector listView valueView evalView lv vv ev | inspector _ self inspect: anObject. topView _ StandardSystemView new model: inspector. listView _ InspectListView new model: inspector. (inspector isMemberOf: DictionaryInspector) ifTrue: [listView controller: DictionaryListController new]. topView addSubView: (lv _ SSAScrollBarView on: listView ). lv window: (0 @ 0 extent: 40 @ 40). lv borderWidthLeft: 2 right: 0 top: 2 bottom: 2. valueView _ valueViewClass new model: inspector. topView addSubView: (vv _ SSAScrollBarView on: valueView ) toRightOf: lv. vv window: (0 @ 0 extent: 75 @ 40). vv borderWidthLeft: 2 right: 2 top: 2 bottom: 2. withEval ifTrue: [evalView _ StringHolderView new model: (InspectorTrash for: inspector object). topView addSubView: (ev _ SSAScrollBarView on: evalView ) below: lv. ev window: (0 @ 0 extent: 115 @ 20). ev borderWidthLeft: 2 right: 2 top: 0 bottom: 2]. topView label: label. topView minimumSize: 180 @ 120. topView controller open! ! !InspectorView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 15:39'! dictionaryInspector: anInspector "Answer an instance of me on the model, anInspector. The instance consists of an InspectListView and an InspectCodeView." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | anInspectorView anInspectorListView aCodeView | anInspectorView _ View new. anInspectorView model: anInspector. anInspectorListView _ SSAScrollBarView on:(InspectListView new model: anInspector; controller: DictionaryListController new;yourself). anInspectorListView window: (0 @ 0 extent: 40 @ 40). anInspectorListView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. anInspectorView addSubView: anInspectorListView. aCodeView _ self buildCodeView: anInspector. anInspectorView addSubView: aCodeView align: aCodeView viewport topLeft with: anInspectorListView viewport topRight. ^anInspectorView! ! !InspectorView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 15:41'! formDictionaryInspector: anInspector "Answer an instance of me on the model, anInspector. The instance consists of an InspectListView and an InspectFormView 6/28/96 sw." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | anInspectorView anInspectorListView aFormView | anInspectorView _ View new. anInspectorView model: anInspector. anInspectorListView _ SSAScrollBarView on: (InspectListView new model: anInspector; controller: DictionaryListController new; yourself). anInspectorListView window: (0 @ 0 extent: 40 @ 40). anInspectorListView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. anInspectorView addSubView: anInspectorListView. aFormView _ self buildFormView: anInspector. anInspectorView addSubView: aFormView align: aFormView viewport topLeft with: anInspectorListView viewport topRight. ^anInspectorView! ! !InspectorView class methodsFor: 'private' stamp: 'ssa 12/11/97 15:33'! buildCodeView: anInspector "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | inspectCodeView | inspectCodeView _ SSAScrollBarView on:(InspectCodeView new model: anInspector). inspectCodeView window: (0 @ 0 extent: 75 @ 40). inspectCodeView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. ^ inspectCodeView! ! !InspectorView class methodsFor: 'private' stamp: 'ssa 12/11/97 15:34'! buildInspectListView: anInspector "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | anInspectListView | anInspectListView _ SSAScrollBarView on:(InspectListView new model: anInspector). anInspectListView window: (0 @ 0 extent: 40 @ 40). anInspectListView borderWidthLeft: 2 right: 0 top: 2 bottom: 2. ^ anInspectListView! ! !InspectorView class methodsFor: 'private' stamp: 'ssa 12/11/97 12:56'! buildTrashView: anInspector "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | inspectTrashView | inspectTrashView _ SSAScrollBarView on: StringHolderView new. inspectTrashView scrollingView model: (InspectorTrash for: anInspector object). inspectTrashView scrollingView controller turnLockingOff. inspectTrashView window: (0 @ 0 extent: 115 @ 20). inspectTrashView borderWidthLeft: 2 right: 2 top: 0 bottom: 2. ^ inspectTrashView! ! !MessageSet class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 13:13'! open: aMessageSet name: aString "Create a standard system view for the messageSet, aMessageSet, whose label is aString." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView aListView aBrowserCodeView | topView _ StandardSystemView new. topView model: aMessageSet. topView label: aString. topView minimumSize: 180 @ 120. aListView _ SSAScrollBarView on:MessageListView new. aListView scrollingView model: aMessageSet. aListView scrollingView list: aMessageSet messageList. aListView window: (0 @ 0 extent: 180 @ 100). aListView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. topView addSubView: aListView. aBrowserCodeView _ SSAScrollBarView on: BrowserCodeView new. aBrowserCodeView scrollingView model: aMessageSet. aBrowserCodeView window: (0 @ 0 extent: 180 @ 300). aBrowserCodeView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. topView addSubView: aBrowserCodeView align: aBrowserCodeView viewport topLeft with: aListView viewport bottomLeft. topView controller open! ! !StringHolderView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 12:54'! open: aStringHolder label: aString "Create a standard system view of the model, aStringHolder, as viewed by an instance of me. The label of the view is aString." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | aStringHolderView topView shv | aStringHolderView _ self container: aStringHolder. topView _ StandardSystemView new. topView model: aStringHolderView model. topView addSubView: (shv _ SSAScrollBarView on: aStringHolderView ). shv borderWidth: 2. topView label: aString. topView minimumSize: 100 @ 50. topView controller open! ! !SyntaxError class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 13:13'! open: aSyntaxError "Answer a standard system view whose model is an instance of me. TK 15 May 96" "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView aListView aCodeView | topView _ StandardSystemView new. topView model: aSyntaxError. topView label: 'Syntax Error'. topView minimumSize: 380 @ 220. aListView _ SSAScrollBarView on:SyntaxErrorListView new. aListView scrollingView model: aSyntaxError. aListView window: (0 @ 0 extent: 380 @ 20). aListView borderWidthLeft: 2 right: 2 top: 2 bottom: 0. topView addSubView: aListView. aCodeView _ SSAScrollBarView on:BrowserCodeView new. aCodeView scrollingView model: aSyntaxError. aCodeView window: (0 @ 0 extent: 380 @ 200). aCodeView borderWidthLeft: 2 right: 2 top: 2 bottom: 2. topView addSubView: aCodeView align: aCodeView viewport topLeft with: aListView viewport bottomLeft. topView controller openNoTerminateDisplayAt: Display extent // 2. Processor activeProcess suspend! ! !TextCollectorView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 12:47'! open: aTextCollector label: aString "Answer an instance of me on the argument, aTextCollector. The label of the StandardSystemView should be aString." "VIVA LA JUNTA!! Modified to use SSAScrollBarViews - ssa 12/11/97 12:00" | topView aView | topView _ StandardSystemView new. topView model: aTextCollector. topView label: aString. topView minimumSize: 100 @ 50. aView _ SSAScrollBarView on: (self new model: aTextCollector). aView borderWidth: 2. topView addSubView: aView. topView controller open! !
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Reflection.MethodBase.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Reflection { abstract public partial class MethodBase : MemberInfo, System.Runtime.InteropServices._MethodBase { #region Methods and constructors public static bool operator != (System.Reflection.MethodBase left, System.Reflection.MethodBase right) { Contract.Ensures(Contract.Result<bool>() == ((left.Equals(right)) == false)); return default(bool); } public static bool operator == (System.Reflection.MethodBase left, System.Reflection.MethodBase right) { return default(bool); } public override bool Equals(Object obj) { return default(bool); } public static MethodBase GetCurrentMethod() { return default(MethodBase); } public virtual new Type[] GetGenericArguments() { return default(Type[]); } public override int GetHashCode() { return default(int); } public virtual new MethodBody GetMethodBody() { return default(MethodBody); } public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) { return default(MethodBase); } public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle) { Contract.Ensures(Contract.Result<System.Reflection.MethodBase>() != null); return default(MethodBase); } public abstract MethodImplAttributes GetMethodImplementationFlags(); public abstract ParameterInfo[] GetParameters(); public abstract Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, System.Globalization.CultureInfo culture); public Object Invoke(Object obj, Object[] parameters) { return default(Object); } protected MethodBase() { } void System.Runtime.InteropServices._MethodBase.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { } Type System.Runtime.InteropServices._MethodBase.GetType() { return default(Type); } void System.Runtime.InteropServices._MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { } void System.Runtime.InteropServices._MethodBase.GetTypeInfoCount(out uint pcTInfo) { pcTInfo = default(uint); } void System.Runtime.InteropServices._MethodBase.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { } #endregion #region Properties and indexers public abstract MethodAttributes Attributes { get; } public virtual new CallingConventions CallingConvention { get { return default(CallingConventions); } } public virtual new bool ContainsGenericParameters { get { return default(bool); } } public bool IsAbstract { get { return default(bool); } } public bool IsAssembly { get { return default(bool); } } public bool IsConstructor { get { return default(bool); } } public bool IsFamily { get { return default(bool); } } public bool IsFamilyAndAssembly { get { return default(bool); } } public bool IsFamilyOrAssembly { get { return default(bool); } } public bool IsFinal { get { return default(bool); } } public virtual new bool IsGenericMethod { get { return default(bool); } } public virtual new bool IsGenericMethodDefinition { get { return default(bool); } } public bool IsHideBySig { get { return default(bool); } } public bool IsPrivate { get { return default(bool); } } public bool IsPublic { get { return default(bool); } } public virtual new bool IsSecurityCritical { get { return default(bool); } } public virtual new bool IsSecuritySafeCritical { get { return default(bool); } } public virtual new bool IsSecurityTransparent { get { return default(bool); } } public bool IsSpecialName { get { return default(bool); } } public bool IsStatic { get { return default(bool); } } public bool IsVirtual { get { return default(bool); } } public abstract RuntimeMethodHandle MethodHandle { get; } bool System.Runtime.InteropServices._MethodBase.IsAbstract { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsAssembly { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsConstructor { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsFamily { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsFamilyAndAssembly { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsFamilyOrAssembly { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsFinal { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsHideBySig { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsPrivate { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsPublic { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsSpecialName { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsStatic { get { return default(bool); } } bool System.Runtime.InteropServices._MethodBase.IsVirtual { get { return default(bool); } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; namespace Orleans { /// <summary> /// Observable lifecycle /// Notes: /// - Single use, does not support multiple start/stop cycles. /// - Once started, no other observers can be subscribed. /// - OnStart starts stages in order until first failure or cancelation. /// - OnStop stops states in reverse order starting from highest started stage. /// - OnStop stops all stages regardless of errors even if canceled canceled. /// </summary> public abstract class LifecycleSubject : ILifecycleSubject { private readonly List<OrderedObserver> subscribers; private readonly ILogger logger; private int? highStage = null; protected LifecycleSubject(ILogger logger) { this.logger = logger; this.subscribers = new List<OrderedObserver>(); } protected virtual string GetStageName(int stage) => stage.ToString(); protected static ImmutableDictionary<int, string> GetStageNames(Type type) { try { var result = ImmutableDictionary.CreateBuilder<int, string>(); var fields = type.GetFields( System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); foreach (var field in fields) { if (typeof(int).IsAssignableFrom(field.FieldType)) { try { var value = (int)field.GetValue(null); result[value] = $"{field.Name} ({value})"; } catch { // Ignore. } } } return result.ToImmutable(); } catch { return ImmutableDictionary<int, string>.Empty; } } protected virtual void PerfMeasureOnStart(int stage, TimeSpan elapsed) { if (this.logger != null && this.logger.IsEnabled(LogLevel.Trace)) { this.logger.LogTrace( (int)ErrorCode.SiloStartPerfMeasure, "Starting lifecycle stage {Stage} took {Elapsed} Milliseconds", stage, elapsed.TotalMilliseconds); } } public virtual async Task OnStart(CancellationToken ct) { if (this.highStage.HasValue) throw new InvalidOperationException("Lifecycle has already been started."); try { foreach (IGrouping<int, OrderedObserver> observerGroup in this.subscribers .GroupBy(orderedObserver => orderedObserver.Stage) .OrderBy(group => group.Key)) { if (ct.IsCancellationRequested) { throw new OrleansLifecycleCanceledException("Lifecycle start canceled by request"); } var stage = observerGroup.Key; this.highStage = stage; var stopWatch = ValueStopwatch.StartNew(); await Task.WhenAll(observerGroup.Select(orderedObserver => CallOnStart(orderedObserver, ct))); stopWatch.Stop(); this.PerfMeasureOnStart(stage, stopWatch.Elapsed); this.OnStartStageCompleted(stage); } } catch (Exception ex) when (!(ex is OrleansLifecycleCanceledException)) { this.logger?.LogError( (int)ErrorCode.LifecycleStartFailure, "Lifecycle start canceled due to errors at stage {Stage}: {Exception}", this.highStage, ex); throw; } static Task CallOnStart(OrderedObserver observer, CancellationToken cancellationToken) { try { return observer.Observer?.OnStart(cancellationToken) ?? Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } } protected virtual void OnStartStageCompleted(int stage) { } protected virtual void PerfMeasureOnStop(int stage, TimeSpan elapsed) { if (this.logger != null && this.logger.IsEnabled(LogLevel.Trace)) { this.logger.LogTrace( (int)ErrorCode.SiloStartPerfMeasure, "Stopping lifecycle stage {Stage} took {Elapsed} Milliseconds", stage, elapsed.TotalMilliseconds); } } public virtual async Task OnStop(CancellationToken ct) { // if not started, do nothing if (!this.highStage.HasValue) return; var loggedCancellation = false; foreach (IGrouping<int, OrderedObserver> observerGroup in this.subscribers // include up to highest started stage .Where(orderedObserver => orderedObserver.Stage <= highStage && orderedObserver.Observer != null) .GroupBy(orderedObserver => orderedObserver.Stage) .OrderByDescending(group => group.Key)) { if (ct.IsCancellationRequested && !loggedCancellation) { this.logger?.LogWarning("Lifecycle stop operations canceled by request."); loggedCancellation = true; } var stage = observerGroup.Key; this.highStage = stage; try { var stopwatch = ValueStopwatch.StartNew(); await Task.WhenAll(observerGroup.Select(orderedObserver => CallOnStop(orderedObserver, ct))); stopwatch.Stop(); this.PerfMeasureOnStop(stage, stopwatch.Elapsed); } catch (Exception ex) { this.logger?.LogError( (int)ErrorCode.LifecycleStopFailure, "Stopping lifecycle encountered an error at stage {Stage}. Continuing to stop. Exception: {Exception}", this.highStage, ex); } this.OnStopStageCompleted(stage); } static Task CallOnStop(OrderedObserver observer, CancellationToken cancellationToken) { try { return observer.Observer?.OnStop(cancellationToken) ?? Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } } protected virtual void OnStopStageCompleted(int stage) { } public virtual IDisposable Subscribe(string observerName, int stage, ILifecycleObserver observer) { if (observer == null) throw new ArgumentNullException(nameof(observer)); if (this.highStage.HasValue) throw new InvalidOperationException("Lifecycle has already been started."); var orderedObserver = new OrderedObserver(stage, observer); this.subscribers.Add(orderedObserver); return orderedObserver; } private class OrderedObserver : IDisposable { public ILifecycleObserver Observer { get; private set; } public int Stage { get; } public OrderedObserver(int stage, ILifecycleObserver observer) { this.Stage = stage; this.Observer = observer; } public void Dispose() => Observer = null; } } }
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.DynamicProxy.Generators.Emitters { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; public static class TypeUtil { public static FieldInfo[] GetAllFields(this Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (type.IsClass == false) { throw new ArgumentException(string.Format("Type {0} is not a class type. This method supports only classes", type)); } var fields = new List<FieldInfo>(); var currentType = type; while (currentType != typeof(object)) { Debug.Assert(currentType != null); var currentFields = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); fields.AddRange(currentFields); currentType = currentType.BaseType; } return fields.ToArray(); } /// <summary> /// Returns list of all unique interfaces implemented given types, including their base interfaces. /// </summary> /// <param name = "types"></param> /// <returns></returns> public static ICollection<Type> GetAllInterfaces(params Type[] types) { if (types == null) { return Type.EmptyTypes; } var dummy = new object(); // we should move this to HashSet once we no longer support .NET 2.0 IDictionary<Type, object> interfaces = new Dictionary<Type, object>(); foreach (var type in types) { if (type == null) { continue; } if (type.IsInterface) { interfaces[type] = dummy; } foreach (var @interface in type.GetInterfaces()) { interfaces[@interface] = dummy; } } return Sort(interfaces.Keys); } public static ICollection<Type> GetAllInterfaces(this Type type) { return GetAllInterfaces(new[] { type }); } public static Type GetClosedParameterType(this AbstractTypeEmitter type, Type parameter) { if (parameter.IsGenericTypeDefinition) { return parameter.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArgumentsFor(parameter)); } if (parameter.IsGenericType) { var arguments = parameter.GetGenericArguments(); if (CloseGenericParametersIfAny(type, arguments)) { return parameter.GetGenericTypeDefinition().MakeGenericType(arguments); } } if (parameter.IsGenericParameter) { return type.GetGenericArgument(parameter.Name); } if (parameter.IsArray) { var elementType = GetClosedParameterType(type, parameter.GetElementType()); return elementType.MakeArrayType(); } if (parameter.IsByRef) { var elementType = GetClosedParameterType(type, parameter.GetElementType()); return elementType.MakeByRefType(); } return parameter; } public static bool IsFinalizer(this MethodInfo methodInfo) { return string.Equals("Finalize", methodInfo.Name) && methodInfo.GetBaseDefinition().DeclaringType == typeof(object); } public static bool IsGetType(this MethodInfo methodInfo) { return methodInfo.DeclaringType == typeof(object) && string.Equals("GetType", methodInfo.Name, StringComparison.OrdinalIgnoreCase); } public static bool IsMemberwiseClone(this MethodInfo methodInfo) { return methodInfo.DeclaringType == typeof(object) && string.Equals("MemberwiseClone", methodInfo.Name, StringComparison.OrdinalIgnoreCase); } public static void SetStaticField(this Type type, string fieldName, BindingFlags additionalFlags, object value) { var flags = additionalFlags | BindingFlags.Static | BindingFlags.SetField; try { type.InvokeMember(fieldName, flags, null, null, new[] { value }); } catch (MissingFieldException e) { throw new ProxyGenerationException( string.Format( "Could not find field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.", fieldName, type), e); } catch (TargetException e) { throw new ProxyGenerationException( string.Format( "There was an error trying to set field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.", fieldName, type), e); } catch (TargetInvocationException e) // yes, this is not documented in MSDN. Yay for documentation { if ((e.InnerException is TypeInitializationException) == false) { throw; } throw new ProxyGenerationException( string.Format( "There was an error in static constructor on type {0}. This is likely a bug in DynamicProxy. Please report it.", type), e); } } public static MemberInfo[] Sort(MemberInfo[] members) { var sortedMembers = new MemberInfo[members.Length]; Array.Copy(members, sortedMembers, members.Length); Array.Sort(sortedMembers, (l, r) => string.Compare(l.Name, r.Name, StringComparison.OrdinalIgnoreCase)); return sortedMembers; } private static bool CloseGenericParametersIfAny(AbstractTypeEmitter emitter, Type[] arguments) { var hasAnyGenericParameters = false; for (var i = 0; i < arguments.Length; i++) { var newType = GetClosedParameterType(emitter, arguments[i]); if (!ReferenceEquals(newType, arguments[i])) { arguments[i] = newType; hasAnyGenericParameters = true; } } return hasAnyGenericParameters; } private static Type[] Sort(IEnumerable<Type> types) { var array = types.ToArray(); //NOTE: is there a better, stable way to sort Types. We will need to revise this once we allow open generics Array.Sort(array, (l, r) => string.Compare(l.AssemblyQualifiedName, r.AssemblyQualifiedName, StringComparison.OrdinalIgnoreCase)); return array; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ItemLevelRecoveryConnectionsOperations operations. /// </summary> internal partial class ItemLevelRecoveryConnectionsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IItemLevelRecoveryConnectionsOperations { /// <summary> /// Initializes a new instance of the ItemLevelRecoveryConnectionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ItemLevelRecoveryConnectionsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Revokes an iSCSI connection which can be used to download a script. /// Executing this script opens a file explorer displaying all recoverable /// files and folders. This is an asynchronous operation. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up items. /// </param> /// <param name='containerName'> /// Container name associated with the backed up items. /// </param> /// <param name='protectedItemName'> /// Backed up item name whose files/folders are to be restored. /// </param> /// <param name='recoveryPointId'> /// Recovery point ID which represents backed up data. iSCSI connection will /// be revoked for this backed up data. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RevokeWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName"); } if (recoveryPointId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "recoveryPointId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Revoke", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/revokeInstantItemRecovery").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Provisions a script which invokes an iSCSI connection to the backup data. /// Executing this script opens a file explorer displaying all the /// recoverable files and folders. This is an asynchronous operation. To know /// the status of provisioning, call GetProtectedItemOperationResult API. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up items. /// </param> /// <param name='containerName'> /// Container name associated with the backed up items. /// </param> /// <param name='protectedItemName'> /// Backed up item name whose files/folders are to be restored. /// </param> /// <param name='recoveryPointId'> /// Recovery point ID which represents backed up data. iSCSI connection will /// be provisioned for this backed up data. /// </param> /// <param name='resourceILRRequest'> /// resource ILR request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> ProvisionWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, ILRRequestResource resourceILRRequest, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName"); } if (recoveryPointId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "recoveryPointId"); } if (resourceILRRequest == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceILRRequest"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("resourceILRRequest", resourceILRRequest); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Provision", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/provisionInstantItemRecovery").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceILRRequest != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceILRRequest, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using NetMud.Data.Architectural.PropertyBinding; using NetMud.DataAccess.Cache; using NetMud.DataStructure.Linguistic; using NetMud.Utility; using Newtonsoft.Json; using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Script.Serialization; namespace NetMud.Data.Linguistic { /// <summary> /// Relational word pair rule for sentence construction /// </summary> public class WordRule : IWordRule { /// <summary> /// Rule applies when sentence is in this tense /// </summary> [Display(Name = "Tense", Description = "Rule applies when sentence is in this tense.")] [UIHint("EnumDropDownList")] public LexicalTense Tense { get; set; } /// <summary> /// Rule applies when sentence is in this perspective /// </summary> [Display(Name = "Perspective", Description = "Rule applies when sentence is in this perspective.")] [UIHint("EnumDropDownList")] public NarrativePerspective Perspective { get; set; } [JsonProperty("SpecificWord")] private DictataKey _specificWord { get; set; } /// <summary> /// When the from word is specifically this /// </summary> [ScriptIgnore] [JsonIgnore] [Display(Name = "Specific Word", Description = "When the From word is this or a synonym of this (only native synonyms) this rule applies.")] [UIHint("DictataList")] [DictataDataBinder] public IDictata SpecificWord { get { if (_specificWord == null) { return null; } return ConfigDataCache.Get<ILexeme>(_specificWord.LexemeKey)?.GetForm(_specificWord.FormId); } set { if (value == null) { _specificWord = null; return; } _specificWord = new DictataKey(new ConfigDataCacheKey(value.GetLexeme()).BirthMark, value.FormGroup); } } [JsonProperty("SpecificAddition")] private DictataKey _specificAddition { get; set; } /// <summary> /// When the additional word (like the article) should be this explicitely /// </summary> [ScriptIgnore] [JsonIgnore] [Display(Name = "Specific Addition", Description = "When the additional word (like the article being added) should be this explicitely.")] [UIHint("DictataList")] [DictataDataBinder] public IDictata SpecificAddition { get { if (_specificAddition?.LexemeKey == null) { return null; } return ConfigDataCache.Get<ILexeme>(_specificAddition.LexemeKey)?.GetForm(_specificAddition.FormId); } set { if (value == null) { _specificAddition = null; return; } _specificAddition = new DictataKey(new ConfigDataCacheKey(value.GetLexeme()).BirthMark, value.FormGroup); } } /// <summary> /// Only applies when the context is possessive /// </summary> [Display(Name = "When Possessive", Description = "Only when the word is possessive form.")] [UIHint("Boolean")] public bool WhenPossessive { get; set; } /// <summary> /// Only applies when the context is plural /// </summary> [Display(Name = "When Plural", Description = "Only when the word is pluralized.")] [UIHint("Boolean")] public bool WhenPlural { get; set; } /// <summary> /// Only applies when the context has a position /// </summary> [Display(Name = "When Positional", Description = "Only when the word indicates relative position.")] [UIHint("Boolean")] public bool WhenPositional { get; set; } /// <summary> /// Add this prefix /// </summary> [Display(Name = "Add Prefix", Description = " Add this prefix to the word.")] [DataType(DataType.Text)] public string AddPrefix { get; set; } /// <summary> /// Add this suffix /// </summary> [Display(Name = "Add Suffix", Description = " Add this suffix to the word.")] [DataType(DataType.Text)] public string AddSuffix { get; set; } /// <summary> /// Applies when this type of word is the primary one /// </summary> [Display(Name = "From Type", Description = "Applies when this type of word is the primary one.")] [UIHint("EnumDropDownList")] public LexicalType FromType { get; set; } /// <summary> /// This rule applies when the word is this role /// </summary> [Display(Name = "From Role", Description = "This rule applies when the word is this role.")] [UIHint("EnumDropDownList")] public GrammaticalType FromRole { get; set; } /// <summary> /// When the origin word has this semantic tag /// </summary> [Display(Name = "From Semantic", Description = "When the origin word has this semantic tag. Can be | delimited. (All are required to match.)")] [DataType(DataType.Text)] public string FromSemantics { get; set; } /// <summary> /// Only when the word ends with /// </summary> [Display(Name = "From Ends With", Description = "Only when the origin word ends with this string. Can be | delimited.")] [DataType(DataType.Text)] public string FromEndsWith { get; set; } /// <summary> /// Only when the word begins with /// </summary> [Display(Name = "From Begins With", Description = "Only when the origin word begins with this string. Can be | delimited.")] [DataType(DataType.Text)] public string FromBeginsWith { get; set; } /// <summary> /// Can be made into a list /// </summary> [Display(Name = "Listable", Description = "Can be made into a list.")] [UIHint("Boolean")] public bool Listable { get; set; } /// <summary> /// Where does the To word fit around the From word? (the from word == 0) /// </summary> [Display(Name = "Descriptive Order", Description = "Where does the To word fit around the From word? (the from word == 0)")] [DataType(DataType.Text)] public int ModificationOrder { get; set; } /// <summary> /// Does this word require an Article added (like nouns preceeding or verbs anteceding) /// </summary> [Display(Name = "Add Article", Description = "Does this word require an Article added? (like nouns preceeding or verbs anteceding)")] [UIHint("Boolean")] public bool NeedsArticle { get; set; } /// <summary> /// The presence of these criteria changes the sentence type /// </summary> [Display(Name = "Alters Sentence Type", Description = "The presence of these criteria changes the sentence type.")] [UIHint("EnumDropDownList")] public SentenceType AltersSentence { get; set; } public WordRule() { AltersSentence = SentenceType.None; NeedsArticle = false; WhenPlural = false; WhenPossessive = false; SpecificAddition = null; SpecificWord = null; Tense = LexicalTense.None; Perspective = NarrativePerspective.None; FromType = LexicalType.None; FromRole = GrammaticalType.None; FromSemantics = string.Empty; FromBeginsWith = string.Empty; FromEndsWith = string.Empty; } /// <summary> /// Rate this rule on how specific it is so we can run the more specific rules first /// </summary> /// <returns>Specificity rating, higher = more specific</returns> public int RuleSpecificity() { return (string.IsNullOrWhiteSpace(FromSemantics) ? 0 : FromSemantics.Count(ch => ch == '|') * 3 + 1) + (string.IsNullOrWhiteSpace(FromEndsWith) ? 0 : FromEndsWith.Count(ch => ch == '|') + 3) + (string.IsNullOrWhiteSpace(FromBeginsWith) ? 0 : FromBeginsWith.Count(ch => ch == '|') + 3) + (SpecificWord == null ? 0 : 99) + (Tense == LexicalTense.None ? 0 : 2) + (Perspective == NarrativePerspective.None ? 0 : 2) + (FromType == LexicalType.None ? 0 : 3) + (FromRole == GrammaticalType.None ? 0 : 3) + (WhenPlural ? 2 : 0) + (WhenPositional ? 6 : 0) + (WhenPossessive ? 2 : 0); } /// <summary> /// Does this lexica match the rule /// </summary> /// <param name="word">The lex</param> /// <returns>if it matches</returns> public bool Matches(ILexica lex) { string[] fromBegins = FromBeginsWith.Split('|', StringSplitOptions.RemoveEmptyEntries); string[] fromEnds = FromEndsWith.Split('|', StringSplitOptions.RemoveEmptyEntries); return (fromBegins.Count() == 0 || fromBegins.Any(bw => lex.Phrase.StartsWith(bw))) && (fromEnds.Count() == 0 || fromEnds.Any(bw => lex.Phrase.EndsWith(bw))) && (Tense == LexicalTense.None || lex.Context.Tense == Tense) && (Perspective == NarrativePerspective.None || lex.Context.Perspective == Perspective) && (!WhenPlural || lex.Context.Plural) && (!WhenPossessive || lex.Context.Possessive) && (SpecificWord == null || SpecificWord.Equals(lex.GetDictata())) && (SpecificWord != null || ((FromRole == GrammaticalType.None || FromRole == lex.Role) && (FromType == LexicalType.None || FromType == lex.Type))); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; namespace PanGu.Framework { public class File { //The process cannot access the file because it is being used by another process const uint ERR_PROCESS_CANNOT_ACCESS_FILE = 0x80070020; /// <summary> /// Get file length /// </summary> /// <param name="fileName"></param> /// <returns></returns> static public long GetFileLength(string fileName) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName); return fileInfo.Length; } static public String ReadFileToString(String FileName, Encoding encode) { if (!System.IO.File.Exists(FileName)) { string name = System.IO.Path.GetFileName(FileName); string result = null; var assembly = Assembly.GetExecutingAssembly(); var assemblyName = assembly.GetName().Name; //string[] names = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); using (var textStream = assembly.GetManifestResourceStream(assemblyName + ".Resources." + name)) { //var textStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name); if (textStream != null) { using (var reader = new StreamReader(textStream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } return result; } else { FileStream fs = null; String str; int times = 0; while (true) { try { fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); Stream.ReadStreamToString(fs, out str, encode); fs.Close(); return str; } catch (IOException e) { uint hResult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(e); if (hResult == ERR_PROCESS_CANNOT_ACCESS_FILE) { if (times > 10) { //Maybe another program has some trouble with file //We must exit now throw e; } System.Threading.Thread.Sleep(200); times++; } else { throw e; } } } } } static public MemoryStream ReadFileToStream(String FileName) { if (!System.IO.File.Exists(FileName)) { string name = System.IO.Path.GetFileName(FileName); var assembly = Assembly.GetExecutingAssembly(); var assemblyName = assembly.GetName().Name; MemoryStream stream = (MemoryStream)assembly.GetManifestResourceStream(assemblyName + ".Resources." + name); return stream; } else { byte[] Bytes = new byte[32768]; int read = 0; int offset = 0; FileStream fs = null; int times = 0; while (true) { try { MemoryStream mem = new MemoryStream(); fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); mem.Position = 0; while ((read = fs.Read(Bytes, 0, Bytes.Length)) > 0) { offset += read; mem.Write(Bytes, 0, read); } fs.Close(); return mem; } catch (IOException e) { uint hResult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(e); if (hResult == ERR_PROCESS_CANNOT_ACCESS_FILE) { if (times > 10) { //Maybe another program has some trouble with file //We must exit now throw e; } System.Threading.Thread.Sleep(200); times++; } else { throw e; } } } } } public static void WriteStream(String FileName, MemoryStream In) { FileStream fs = null; int times = 0; while (true) { try { if (System.IO.File.Exists(FileName)) { System.IO.File.Delete(FileName); } fs = new FileStream(FileName, FileMode.CreateNew); In.WriteTo(fs); fs.Close(); return; } catch (IOException e) { uint hResult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(e); if (hResult == ERR_PROCESS_CANNOT_ACCESS_FILE) { if (times > 10) { //Maybe another program has some trouble with file //We must exit now throw e; } System.Threading.Thread.Sleep(200); times++; } else { throw e; } } } } public static void WriteLine(String FileName, String str) { int times = 0; while (true) { try { using (FileStream fs = new FileStream(FileName, FileMode.Append)) { using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) { w.WriteLine(str); } } return; } catch (IOException e) { uint hResult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(e); if (hResult == ERR_PROCESS_CANNOT_ACCESS_FILE) { if (times > 10) { //Maybe another program has some trouble with file //We must exit now throw e; } System.Threading.Thread.Sleep(200); times++; } else { throw e; } } } } public static void WriteString(String FileName, String str, Encoding encode) { TextWriter writer = null; FileStream fs = null; int times = 0; while (true) { try { if (System.IO.File.Exists(FileName)) { System.IO.File.Delete(FileName); } fs = new FileStream(FileName, FileMode.CreateNew); writer = new StreamWriter(fs, encode); writer.Write(str); writer.Close(); fs.Close(); return; } catch (IOException e) { uint hResult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(e); if (hResult == ERR_PROCESS_CANNOT_ACCESS_FILE) { if (times > 10) { //Maybe another program has some trouble with file //We must exit now throw e; } System.Threading.Thread.Sleep(200); times++; } else { throw e; } } } } public static void DeleteFile(string path, string fileName, bool recursive) { if (path[path.Length - 1] != System.IO.Path.DirectorySeparatorChar) { path += System.IO.Path.DirectorySeparatorChar; } if (!recursive) { System.IO.File.Delete(path + fileName); } else { System.IO.File.Delete(path + fileName); string[] subFolders = System.IO.Directory.GetDirectories(path); foreach (string folder in subFolders) { DeleteFile(folder, fileName, recursive); } } } } }
//--------------------------------------------------------------------------- // // <copyright file="SafeNativeMethods.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Unsafe P/Invokes used by UIAutomation // // History: // 05/29/2003 : BrendanM removed commented out code which wasn't very // useful. Will instead add in as-needed from our old Win32.cs // file. // //--------------------------------------------------------------------------- using System.Threading; using System; using System.Runtime.InteropServices; using System.Collections; using System.IO; using System.Text; using Accessibility; using Microsoft.Win32.SafeHandles; namespace MS.Win32 { // This class *MUST* be internal for security purposes internal static class UnsafeNativeMethods { public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // // CloseHandle // [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle(IntPtr handle); // // OpenProcess // public const int PROCESS_VM_READ = 0x0010; public const int PROCESS_DUP_HANDLE = 0x0040; public const int PROCESS_QUERY_INFORMATION = 0x0400; [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr OpenProcess( int dwDesiredAccess, bool fInherit, int dwProcessId ); // // SendInput related // public const int VK_SHIFT = 0x10; public const int VK_CONTROL = 0x11; public const int VK_MENU = 0x12; public const int KEYEVENTF_EXTENDEDKEY = 0x0001; public const int KEYEVENTF_KEYUP = 0x0002; public const int KEYEVENTF_UNICODE = 0x0004; public const int KEYEVENTF_SCANCODE = 0x0008; public const int MOUSEEVENTF_VIRTUALDESK = 0x4000; [StructLayout(LayoutKind.Sequential)] public struct INPUT { public int type; public INPUTUNION union; }; [StructLayout(LayoutKind.Explicit)] public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mouseInput; [FieldOffset(0)] public KEYBDINPUT keyboardInput; }; [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public int dwFlags; public int time; public IntPtr dwExtraInfo; }; [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public short wVk; public short wScan; public int dwFlags; public int time; public IntPtr dwExtraInfo; }; public const int INPUT_MOUSE = 0; public const int INPUT_KEYBOARD = 1; [DllImport("user32.dll", SetLastError = true)] public static extern int SendInput( int nInputs, ref INPUT mi, int cbSize ); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int MapVirtualKey(int nVirtKey, int nMapType); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern short GetAsyncKeyState(int nVirtKey); // // Hotkeys // [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool RegisterHotKey( NativeMethods.HWND hWnd, int id, int fsModifiers, int vk ); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool UnregisterHotKey( NativeMethods.HWND hWnd, int id ); // // Foreground window // [DllImport("user32.dll")] public static extern void SwitchToThisWindow(NativeMethods.HWND hwnd, bool fAltTab); // // IAccessible / OLEACC / WinEvents // public const int CHILDID_SELF = 0; public const int STATE_SYSTEM_UNAVAILABLE = 0x00000001; public const int STATE_SYSTEM_FOCUSED = 0x00000004; public const int OBJID_CARET = -8; public const int OBJID_CLIENT = -4; public const int OBJID_MENU = -3; public const int OBJID_SYSMENU = -1; public const int OBJID_WINDOW = 0; [DllImport("oleacc.dll")] public static extern int AccessibleObjectFromEvent ( IntPtr hwnd, int idObject, int idChild, ref IAccessible ppvObject, ref Object varChild ); [DllImport("oleacc.dll")] public static extern int WindowFromAccessibleObject ( IAccessible acc, ref IntPtr hwnd ); [DllImport("oleacc.dll", SetLastError = true)] internal static extern IntPtr GetProcessHandleFromHwnd(IntPtr hwnd); [DllImport("user32.dll")] internal static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, NativeMethods.WinEventProcDef WinEventReentrancyFilter, uint idProcess, uint idThread, int dwFlags); [DllImport("user32.dll")] internal static extern bool UnhookWinEvent(IntPtr winEventHook); private struct POINTSTRUCT { public int x; public int y; public POINTSTRUCT(int x, int y) { this.x = x; this.y = y; } } [DllImport("user32.dll", EntryPoint = "WindowFromPoint", ExactSpelling = true, CharSet = CharSet.Auto)] private static extern IntPtr IntWindowFromPoint(POINTSTRUCT pt); [DllImport("user32.dll", EntryPoint = "WindowFromPhysicalPoint", ExactSpelling = true, CharSet = CharSet.Auto)] private static extern IntPtr IntWindowFromPhysicalPoint(POINTSTRUCT pt); public static IntPtr WindowFromPhysicalPoint(int x, int y) { POINTSTRUCT ps = new POINTSTRUCT(x, y); if (System.Environment.OSVersion.Version.Major >= 6) return IntWindowFromPhysicalPoint(ps); else return IntWindowFromPoint(ps); } // // SendMessage and related // public const int SMTO_ABORTIFHUNG = 2; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessageTimeout( NativeMethods.HWND hwnd, int Msg, IntPtr wParam, IntPtr lParam, int flags, int uTimeout, out IntPtr pResult ); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessageTimeout( NativeMethods.HWND hwnd, int Msg, IntPtr wParam, ref MINMAXINFO lParam, int flags, int uTimeout, out IntPtr pResult ); // Overload for use with WM_GETTEXT. StringBuilder is the type that P/Invoke maps to an output TCHAR*, see // see MSDN .Net docs on P/Invoke for more details. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr SendMessageTimeout( NativeMethods.HWND hwnd, int Msg, IntPtr wParam, StringBuilder lParam, int flags, int uTimeout, out IntPtr pResult); public const int PM_REMOVE = 0x0001; [StructLayout(LayoutKind.Sequential)] public struct MSG { public NativeMethods.HWND hwnd; public int message; public IntPtr wParam; public IntPtr lParam; public int time; public int pt_x; public int pt_y; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int GetMessage( ref MSG msg, NativeMethods.HWND hwnd, int nMsgFilterMin, int nMsgFilterMax); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern bool PeekMessage( ref MSG msg, NativeMethods.HWND hwnd, int nMsgFilterMin, int nMsgFilterMax, int wRemoveMsg); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern bool TranslateMessage( ref MSG msg); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr DispatchMessage( ref MSG msg); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool PostMessage( NativeMethods.HWND hWnd, int nMsg, IntPtr wParam, IntPtr lParam); // // Messages and related structs / constants // public const int WM_NULL = 0x0000; public const int WM_GETTEXT = 0x000D; public const int WM_GETTEXTLENGTH = 0x000E; public const int WM_QUIT = 0x0012; public const int WM_GETMINMAXINFO = 0x0024; [StructLayout(LayoutKind.Sequential)] public struct MINMAXINFO { public NativeMethods.POINT ptReserved; public NativeMethods.POINT ptMaxSize; public NativeMethods.POINT ptMaxPosition; public NativeMethods.POINT ptMinTrackSize; public NativeMethods.POINT ptMaxTrackSize; }; public const int WM_GETOBJECT = 0x003D; public const int WM_NCHITTEST = 0x0084; public static readonly IntPtr HTTRANSPARENT = new IntPtr(-1); public static readonly IntPtr HTCLIENT = new IntPtr(1); public const int WM_SYSCOMMAND = 0x0112; public const int WM_MDIACTIVATE = 0x0222; public const int SC_SIZE = 0xF000; public const int SC_MOVE = 0xF010; public const int SC_MINIMIZE = 0xF020; public const int SC_MAXIMIZE = 0xF030; public const int SC_CLOSE = 0xF060; public const int SC_RESTORE = 0xF120; public const int WM_HOTKEY = 0x0312; public const int LB_GETCURSEL = 0x0188; // // MsgWaitForMultipleObjects... // public const int QS_KEY = 0x0001, QS_MOUSEMOVE = 0x0002, QS_MOUSEBUTTON = 0x0004, QS_POSTMESSAGE = 0x0008, QS_TIMER = 0x0010, QS_PAINT = 0x0020, QS_SENDMESSAGE = 0x0040, QS_HOTKEY = 0x0080, QS_ALLPOSTMESSAGE = 0x0100, QS_MOUSE = QS_MOUSEMOVE | QS_MOUSEBUTTON, QS_INPUT = QS_MOUSE | QS_KEY, QS_ALLEVENTS = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY, QS_ALLINPUT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE; public const int INFINITE = unchecked((int)0xFFFFFFFF); [DllImport("user32.dll", SetLastError = true)] public static extern int MsgWaitForMultipleObjects(int nCount, IntPtr[] handles, bool fWaitAll, int dwMilliseconds, int dwWakeMask); public const int WAIT_FAILED = unchecked((int)0xFFFFFFFF); public const int WAIT_TIMEOUT = 0x00000102; // // Window Placement // public const int WPF_SETMINPOSITION = 0x0001; public const int SW_RESTORE = 0x0009; public const int SWP_NOACTIVATE = 0x0010; [StructLayout(LayoutKind.Sequential)] public struct WINDOWPLACEMENT { public int length; public int flags; public int showCmd; public NativeMethods.POINT ptMinPosition; public NativeMethods.POINT ptMaxPosition; public NativeMethods.RECT rcNormalPosition; }; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool SetWindowPlacement( NativeMethods.HWND hwnd, ref WINDOWPLACEMENT wp ); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool GetWindowPlacement( NativeMethods.HWND hwnd, ref WINDOWPLACEMENT wp ); public const int SWP_NOSIZE = 0x0001; public const int SWP_NOZORDER = 0x0004; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool SetWindowPos(NativeMethods.HWND hWnd, NativeMethods.HWND hWndInsertAfter, int x, int y, int cx, int cy, int flags); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] internal static extern int GetMenuState(IntPtr hMenu, int uId, int uFlags); internal const int MF_BYCOMMAND = 0x00000000; internal const int MF_BYPOSITION = 0x00000400; internal const int MF_GRAYED = 0x00000001; internal const int MF_DISABLED = 0x00000002; [StructLayout(LayoutKind.Sequential)] internal struct MENUBARINFO { internal int cbSize; internal NativeMethods.RECT rcBar; internal IntPtr hMenu; internal NativeMethods.HWND hwndMenu; internal int focusFlags; } // // GDI // [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool DeleteObject(IntPtr hrgn); } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using MindTouch.Deki.Data; using MindTouch.Dream; using MindTouch.Xml; namespace MindTouch.Deki.Logic { public static class TagBL { public static IList<TagBE> GetTagsForPage(PageBE page) { // retrieve tags associated with a specified page id IList<TagBE> tags = DbUtils.CurrentSession.Tags_GetByPageId(page.ID); // populate the defined to and related pages information List<uint> ids = new List<uint>(); foreach(TagBE tag in tags) { if(TagType.DEFINE == tag.Type) { tag.DefinedTo = page; } ids.Add(tag.Id); } Dictionary<uint, IList<PageBE>> relatedPageMap = ids.Count > 0 ? DbUtils.CurrentSession.Tags_GetRelatedPages(ids) : new Dictionary<uint, IList<PageBE>>(); foreach(TagBE tag in tags) { if((TagType.DEFINE == tag.Type) || (TagType.TEXT == tag.Type)) { IList<PageBE> relatedPagesList; relatedPageMap.TryGetValue(tag.Id, out relatedPagesList); if(null != relatedPagesList) { PageBE[] relatedPages = PermissionsBL.FilterDisallowed(DekiContext.Current.User, relatedPagesList, false, Permissions.BROWSE); if(TagType.DEFINE == tag.Type) { tag.RelatedPages = relatedPages; } else if((TagType.TEXT == tag.Type) && (0 < relatedPages.Length)) { tag.DefinedTo = relatedPages[0]; } } } } return tags; } public static IList<TagBE> GetTags(string partialName, TagType type, DateTime from, DateTime to) { return FilterDisallowed(DbUtils.CurrentSession.Tags_GetByQuery(partialName, type, from, to)); } public static TagBE GetTagFromUrl() { TagBE tag = GetTagFromPathSegment(DreamContext.Current.GetParam("tagid")); return tag; } public static TagBE GetTagFromPathSegment(string tagPathSegment) { TagBE tag = null; uint id = 0; string tagId = tagPathSegment; if(uint.TryParse(tagId, out id)) tag = DbUtils.CurrentSession.Tags_GetById(id); else { if(tagId.StartsWith("=")) { string prefixedName = tagId.Substring(1); prefixedName = XUri.Decode(prefixedName); TagBE tmpTag = ParseTag(prefixedName); tag = DbUtils.CurrentSession.Tags_GetByNameAndType(tmpTag.Name, tmpTag.Type); } } if(tag != null) { IList<TagBE> tags = new List<TagBE>(); tags.Add(tag); tags = FilterDisallowed(tags); if(tags.Count == 0) tag = null; } if(tag == null) throw new DreamAbortException(DreamMessage.NotFound(DekiResources.CANNOT_FIND_REQUESTED_TAG)); return tag; } public static TagBE ParseTag(string prefixedName) { TagBE tag = null; // retrieve the tag type prefixedName = prefixedName.Trim(); if(0 < prefixedName.Length) { tag = new TagBE(); if(StringUtil.StartsWithInvariantIgnoreCase(prefixedName, TagPrefix.DEFINE)) { tag.Type = TagType.DEFINE; } else if(StringUtil.StartsWithInvariantIgnoreCase(prefixedName, TagPrefix.DATE)) { tag.Type = TagType.DATE; } else if(StringUtil.StartsWithInvariantIgnoreCase(prefixedName, TagPrefix.USER)) { tag.Type = TagType.USER; } // remove the prefix from the tag int prefixLength = tag.Prefix.Length; if(prefixLength < prefixedName.Length) { tag.Name = prefixedName.Substring(prefixLength); } else { throw new DreamAbortException(DreamMessage.BadRequest(string.Format(DekiResources.TAG_INVALID, prefixedName))); } // the tag is a date and not valid, change its type to text if(TagType.DATE == tag.Type) { DateTime date; if(!DateTime.TryParseExact(tag.Name, "yyyy-MM-dd", DreamContext.Current.Culture, System.Globalization.DateTimeStyles.None, out date)) { tag.Type = TagType.TEXT; tag.Name = prefixedName; } } } return tag; } public static void PutTagsFromXml(PageBE pageToUpdate, XDoc tagsDoc) { List<TagBE> newTags = ReadTagsListXml(tagsDoc); PutTags(pageToUpdate, newTags); } public static void PutTags(PageBE page, string[] tags) { List<TagBE> newTags = new List<TagBE>(); foreach(string tagName in tags) { TagBE tag = TagBL.ParseTag(tagName); if(null != tag) { newTags.Add(tag); } } if(newTags.Count == 0) { return; } PutTags(page, newTags); } private static void PutTags(PageBE page, List<TagBE> newTags) { List<TagBE> existingTags = GetTagsForPage(page).ToList(); DateTime timestamp = DateTime.UtcNow; // retrieve a diff of the existing and new tags List<TagBE> added; List<uint> removed; string diffSummary = CompareTagSets(existingTags, newTags, out added, out removed); // add and delete tags as determined from the diff added = InsertTags(page.ID, added); DbUtils.CurrentSession.TagMapping_Delete(page.ID, removed); if((0 < added.Count) || (0 < removed.Count)) { RecentChangeBL.AddTagsRecentChange(timestamp, page, DekiContext.Current.User, diffSummary); } PageBL.Touch(page, timestamp); DekiContext.Current.Instance.EventSink.PageTagsUpdate(DreamContext.Current.StartTime, page, DekiContext.Current.User); } public static List<TagBE> InsertTags(ulong pageId, IList<TagBE> tags) { var result = new List<TagBE>(); foreach(TagBE tag in tags) { uint tagId = DbUtils.CurrentSession.Tags_Insert(tag); // If the tag already exists, retrieve it if(tagId == 0) { var matchingTag = DbUtils.CurrentSession.Tags_GetByNameAndType(tag.Name, tag.Type); // if the tag is a define tag, check that it's still a valid one if(tag.Type == TagType.DEFINE && DbUtils.CurrentSession.Tags_ValidateDefineTagMapping(matchingTag)) { // if the define tag is valid, insert this tag as text tag.Type = TagType.TEXT; result.AddRange(InsertTags(pageId, new[] { tag })); continue; } tagId = matchingTag.Id; } DbUtils.CurrentSession.TagMapping_Insert(pageId, tagId); result.Add(tag); } return result; } private static IList<TagBE> AssignDefinePages(IList<TagBE> tags) { foreach(TagBE tag in tags) { if(tag.Type == TagType.DEFINE) { ulong pageId = DbUtils.CurrentSession.Tags_GetPageIds(tag.Id).FirstOrDefault(); if(0 != pageId) { tag.DefinedTo = PageBL.GetPageById(pageId); } } } return tags; } private static IList<PageBE> GetTaggedPages(TagBE tag) { IList<ulong> pageIds = DbUtils.CurrentSession.Tags_GetPageIds(tag.Id); IList<PageBE> pages = PageBL.GetPagesByIdsPreserveOrder(pageIds); return PermissionsBL.FilterDisallowed(DekiContext.Current.User, pages, false, Permissions.BROWSE); } private static IList<TagBE> FilterDisallowed(IList<TagBE> tags) { List<TagBE> tagsToRemove = new List<TagBE>(); tags = AssignDefinePages(tags); foreach(TagBE tag in tags) { if(tag.Type == TagType.DEFINE) { if(tag.DefinedTo == null || PermissionsBL.FilterDisallowed(DekiContext.Current.User, new PageBE[] { tag.DefinedTo }, false, Permissions.BROWSE).Length != 1) { tagsToRemove.Add(tag); } tag.OccuranceCount = 1; } else { // filter the tags based on permissions IList<ulong> pageIds = DbUtils.CurrentSession.Tags_GetPageIds(tag.Id); IList<PageBE> pages = PageBL.GetPagesByIdsPreserveOrder(pageIds); if(pages == null) { // this should never happen tagsToRemove.Add(tag); } else { // apply permissions int count = PermissionsBL.FilterDisallowed(DekiContext.Current.User, pages, false, Permissions.BROWSE).Length; if(count == 0) tagsToRemove.Add(tag); tag.OccuranceCount = count; } } } foreach(TagBE tag in tagsToRemove) { tags.Remove(tag); } return tags; } private static string CompareTagSets(List<TagBE> current, List<TagBE> proposed, out List<TagBE> added, out List<uint> removed) { // perform a subtraction of tags (in both directions) to determine which tags were added and removed from one set to another added = new List<TagBE>(); removed = new List<uint>(); TagComparer tagComparer = new TagComparer(); current.Sort(tagComparer); proposed.Sort(tagComparer); // determine which pages have been added StringBuilder addedSummary = new StringBuilder(); List<TagBE> addedList = new List<TagBE>(); foreach(TagBE proposedTag in proposed) { if((current.BinarySearch(proposedTag, tagComparer) < 0)) { // only add the tag if is not already being added bool includeTag = (added.BinarySearch(proposedTag, tagComparer) < 0); if(includeTag && (TagType.TEXT == proposedTag.Type)) { TagBE proposedTagDefine = new TagBE(); proposedTagDefine.Type = TagType.DEFINE; proposedTagDefine.Name = proposedTag.Name; if(0 <= proposed.BinarySearch(proposedTagDefine, tagComparer)) { includeTag = false; } } if(includeTag) { added.Add(proposedTag); if(1 < added.Count) { addedSummary.Append(", "); } addedSummary.Append(proposedTag.PrefixedName); } } } // determine which pages have been removed StringBuilder removedSummary = new StringBuilder(); foreach(TagBE currentTag in current) { if(proposed.BinarySearch(currentTag, tagComparer) < 0) { removed.Add(currentTag.Id); if(1 < removed.Count) { removedSummary.Append(", "); } removedSummary.Append(currentTag.PrefixedName); } } // create a diff summary string string diffSummary = String.Empty; if(0 < addedSummary.Length) { diffSummary += String.Format(DekiResources.TAG_ADDED, addedSummary.ToString()) + " "; } if(0 < removedSummary.Length) { diffSummary += String.Format(DekiResources.TAG_REMOVED, removedSummary.ToString()); } return diffSummary; } private class TagComparer : IComparer<TagBE> { public int Compare(TagBE tag1, TagBE tag2) { // compares one tag to another int result = (int)tag1.Type - (int)tag2.Type; if(0 == result) { result = StringUtil.CompareInvariant(tag1.Name, tag2.Name); } return result; } } #region XML Helpers private static List<TagBE> ReadTagsListXml(XDoc tagsDoc) { List<TagBE> result = new List<TagBE>(); foreach(XDoc tagDoc in tagsDoc["tag/@value"]) { TagBE tag = TagBL.ParseTag(tagDoc.Contents); if(null != tag) { result.Add(tag); } } return result; } public static XDoc GetTagXml(TagBE tag, bool showPages, string pageFilterLanguage) { string uriText = null, titleText = null; switch(tag.Type) { case TagType.DEFINE: uriText = Utils.AsPublicUiUri(tag.DefinedTo.Title); titleText = tag.Name; break; case TagType.DATE: uriText = DekiContext.Current.UiUri.Uri.AtPath("Special:Events").With("from", tag.Name).ToString(); DateTime date = DateTime.ParseExact(tag.Name, "yyyy-MM-dd", DreamContext.Current.Culture, System.Globalization.DateTimeStyles.None); titleText = date.ToString("D", DreamContext.Current.Culture); break; case TagType.TEXT: if(null != tag.DefinedTo) { uriText = Utils.AsPublicUiUri(tag.DefinedTo.Title); } else { uriText = DekiContext.Current.UiUri.AtPath("Special:Tags").With("tag", tag.Name).ToString(); } titleText = tag.Name; break; } XDoc result = new XDoc("tag"); result.Attr("value", tag.PrefixedName); result.Attr("id", tag.Id); result.Attr("href", DekiContext.Current.ApiUri.At("site", "tags", tag.Id.ToString()).ToString()); if(tag.OccuranceCount > 0) result.Attr("count", tag.OccuranceCount); result.Elem("type", tag.Type.ToString().ToLowerInvariant()); result.Elem("uri", uriText); result.Elem("title", titleText); if(null != tag.RelatedPages) { result.Add(PageBL.GetPageListXml(tag.RelatedPages, "related")); } if(showPages) { IList<PageBE> pages = TagBL.GetTaggedPages(tag); if(pageFilterLanguage != null) { // filter pages by language pages = (from page in pages where page.Language == pageFilterLanguage select page).ToList(); } result.Add(PageBL.GetPageListXml(pages, "pages")); } return result; } public static XDoc GetTagListXml(IEnumerable<TagBE> listItems, string listName, XUri href, bool showPages) { XDoc ret = null; if(!string.IsNullOrEmpty(listName)) ret = new XDoc(listName); else ret = new XDoc("list"); int count = 0; if(listItems != null) count = new List<TagBE>(listItems).Count; ret.Attr("count", count); if(href != null) { ret.Attr("href", href); } if(listItems != null) { foreach(TagBE tag in listItems) ret.Add(TagBL.GetTagXml(tag, showPages, null)); } return ret; } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Maps a JSON property to a .NET member or constructor parameter. /// </summary> public class JsonProperty { internal Required? _required; internal bool _hasExplicitDefaultValue; private object _defaultValue; private bool _hasGeneratedDefaultValue; private string _propertyName; internal bool _skipPropertyNameEscape; private Type _propertyType; // use to cache contract during deserialization internal JsonContract PropertyContract { get; set; } /// <summary> /// Gets or sets the name of the property. /// </summary> /// <value>The name of the property.</value> public string PropertyName { get { return _propertyName; } set { _propertyName = value; _skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags); } } /// <summary> /// Gets or sets the type that declared this property. /// </summary> /// <value>The type that declared this property.</value> public Type DeclaringType { get; set; } /// <summary> /// Gets or sets the order of serialization and deserialization of a member. /// </summary> /// <value>The numeric order of serialization or deserialization.</value> public int? Order { get; set; } /// <summary> /// Gets or sets the name of the underlying member or parameter. /// </summary> /// <value>The name of the underlying member or parameter.</value> public string UnderlyingName { get; set; } /// <summary> /// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization. /// </summary> /// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value> public IValueProvider ValueProvider { get; set; } /// <summary> /// Gets or sets the type of the property. /// </summary> /// <value>The type of the property.</value> public Type PropertyType { get { return _propertyType; } set { if (_propertyType != value) { _propertyType = value; _hasGeneratedDefaultValue = false; } } } /// <summary> /// Gets or sets the <see cref="JsonConverter" /> for the property. /// If set this converter takes presidence over the contract converter for the property type. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } /// <summary> /// Gets or sets the member converter. /// </summary> /// <value>The member converter.</value> public JsonConverter MemberConverter { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored. /// </summary> /// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value> public bool Ignored { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable. /// </summary> /// <value><c>true</c> if readable; otherwise, <c>false</c>.</value> public bool Readable { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable. /// </summary> /// <value><c>true</c> if writable; otherwise, <c>false</c>.</value> public bool Writable { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute. /// </summary> /// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value> public bool HasMemberAttribute { get; set; } /// <summary> /// Gets the default value. /// </summary> /// <value>The default value.</value> public object DefaultValue { get { if (!_hasExplicitDefaultValue) return null; return _defaultValue; } set { _hasExplicitDefaultValue = true; _defaultValue = value; } } internal object GetResolvedDefaultValue() { if (_propertyType == null) return null; if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue) { _defaultValue = ReflectionUtils.GetDefaultValue(PropertyType); _hasGeneratedDefaultValue = true; } return _defaultValue; } /// <summary> /// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required. /// </summary> /// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value> public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } /// <summary> /// Gets or sets a value indicating whether this property preserves object references. /// </summary> /// <value> /// <c>true</c> if this instance is reference; otherwise, <c>false</c>. /// </value> public bool? IsReference { get; set; } /// <summary> /// Gets or sets the property null value handling. /// </summary> /// <value>The null value handling.</value> public NullValueHandling? NullValueHandling { get; set; } /// <summary> /// Gets or sets the property default value handling. /// </summary> /// <value>The default value handling.</value> public DefaultValueHandling? DefaultValueHandling { get; set; } /// <summary> /// Gets or sets the property reference loop handling. /// </summary> /// <value>The reference loop handling.</value> public ReferenceLoopHandling? ReferenceLoopHandling { get; set; } /// <summary> /// Gets or sets the property object creation handling. /// </summary> /// <value>The object creation handling.</value> public ObjectCreationHandling? ObjectCreationHandling { get; set; } /// <summary> /// Gets or sets or sets the type name handling. /// </summary> /// <value>The type name handling.</value> public TypeNameHandling? TypeNameHandling { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialize. /// </summary> /// <value>A predicate used to determine whether the property should be serialize.</value> public Predicate<object> ShouldSerialize { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialized. /// </summary> /// <value>A predicate used to determine whether the property should be serialized.</value> public Predicate<object> GetIsSpecified { get; set; } /// <summary> /// Gets or sets an action used to set whether the property has been deserialized. /// </summary> /// <value>An action used to set whether the property has been deserialized.</value> public Action<object, object> SetIsSpecified { get; set; } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override string ToString() { return PropertyName; } /// <summary> /// Gets or sets the converter used when serializing the property's collection items. /// </summary> /// <value>The collection's items converter.</value> public JsonConverter ItemConverter { get; set; } /// <summary> /// Gets or sets whether this property's collection items are serialized as a reference. /// </summary> /// <value>Whether this property's collection items are serialized as a reference.</value> public bool? ItemIsReference { get; set; } /// <summary> /// Gets or sets the the type name handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items type name handling.</value> public TypeNameHandling? ItemTypeNameHandling { get; set; } /// <summary> /// Gets or sets the the reference loop handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items reference loop handling.</value> public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; } internal void WritePropertyName(JsonWriter writer) { if (_skipPropertyNameEscape) writer.WritePropertyName(PropertyName, false); else writer.WritePropertyName(PropertyName); } } }
using System; using System.Collections.Generic; using System.Text; using CslaGenerator.Metadata; namespace CslaGenerator.Util { /// <summary> /// Summary description for TypeHelper. /// </summary> public static class TypeHelper { public static TypeCodeEx GetTypeCodeEx(this Type type) { if (type == null) return TypeCodeEx.Empty; if (type == typeof(Boolean)) return TypeCodeEx.Boolean; if (type == typeof(Byte)) return TypeCodeEx.Byte; if (type == typeof(Char)) return TypeCodeEx.Char; if (type == typeof(DateTime)) { if (GeneratorController.Current.CurrentUnit.Params.SmartDateDefault) return TypeCodeEx.SmartDate; return TypeCodeEx.DateTime; } if (type == typeof(DateTimeOffset)) { if (GeneratorController.Current.CurrentUnit.Params.SmartDateDefault) return TypeCodeEx.SmartDate; return TypeCodeEx.DateTimeOffset; } if (type == typeof(TimeSpan)) return TypeCodeEx.TimeSpan; if (type == typeof(DBNull)) return TypeCodeEx.DBNull; if (type == typeof(Decimal)) return TypeCodeEx.Decimal; if (type == typeof(Double)) return TypeCodeEx.Double; if (type == typeof(Guid)) return TypeCodeEx.Guid; if (type == typeof(Int16)) return TypeCodeEx.Int16; if (type == typeof(Int32)) return TypeCodeEx.Int32; if (type == typeof(Int64)) return TypeCodeEx.Int64; if (type == typeof(SByte)) return TypeCodeEx.SByte; if (type == typeof(Single)) return TypeCodeEx.Single; if (type == typeof(String)) return TypeCodeEx.String; if (type == typeof(UInt16)) return TypeCodeEx.UInt16; if (type == typeof(UInt32)) return TypeCodeEx.UInt32; if (type == typeof(UInt64)) return TypeCodeEx.UInt64; if (type == typeof(byte[])) return TypeCodeEx.ByteArray; return TypeCodeEx.Object; } public static bool IsNullAllowedOnType(this TypeCodeEx type) { switch (type) { case TypeCodeEx.Boolean: case TypeCodeEx.Byte: case TypeCodeEx.Char: case TypeCodeEx.Decimal: case TypeCodeEx.Double: case TypeCodeEx.Guid: case TypeCodeEx.Int16: case TypeCodeEx.Int32: case TypeCodeEx.Int64: case TypeCodeEx.SByte: case TypeCodeEx.Single: case TypeCodeEx.UInt16: case TypeCodeEx.UInt32: case TypeCodeEx.UInt64: case TypeCodeEx.TimeSpan: case TypeCodeEx.DateTimeOffset: case TypeCodeEx.DateTime: case TypeCodeEx.SmartDate: case TypeCodeEx.String: return true; /* * These are not nullable: case TypeCodeEx.ByteArray: case TypeCodeEx.CustomType: case TypeCodeEx.DBNull: case TypeCodeEx.Empty: case TypeCodeEx.Object: */ } return false; } public static bool IsNumeric(this TypeCodeEx type) { switch (type) { case TypeCodeEx.Byte: case TypeCodeEx.Decimal: case TypeCodeEx.Double: case TypeCodeEx.Int16: case TypeCodeEx.Int32: case TypeCodeEx.Int64: case TypeCodeEx.SByte: case TypeCodeEx.Single: case TypeCodeEx.UInt16: case TypeCodeEx.UInt32: case TypeCodeEx.UInt64: return true; /* * These are not numeric: case TypeCodeEx.Boolean: case TypeCodeEx.ByteArray: case TypeCodeEx.Char: case TypeCodeEx.CustomType: case TypeCodeEx.DBNull: case TypeCodeEx.Empty: case TypeCodeEx.Guid: case TypeCodeEx.Object: case TypeCodeEx.TimeSpan: case TypeCodeEx.DateTimeOffset: case TypeCodeEx.DateTime: case TypeCodeEx.SmartDate: case TypeCodeEx.String: */ } return false; } public static bool IsDualInheritor(this CslaObjectType cslaType) { if (cslaType.IsEditableRootCollection() || cslaType.IsEditableChildCollection() || cslaType.IsDynamicEditableRootCollection() || cslaType.IsReadOnlyCollection()) { return true; } return false; } public static bool IsDualInheritor(this CslaObjectInfo info) { return info.ObjectType.IsDualInheritor(); } public static bool IsCollectionType(this CslaObjectType cslaType) { if (cslaType.IsEditableRootCollection() || cslaType.IsEditableChildCollection() || cslaType.IsDynamicEditableRootCollection() || cslaType.IsReadOnlyCollection()) { return true; } return false; } public static bool IsCollectionType(this CslaObjectInfo info) { return info.ObjectType.IsCollectionType(); } public static bool IsObjectType(this CslaObjectType cslaType) { if (cslaType.IsEditableRoot() || cslaType.IsEditableChild() || cslaType.IsEditableSwitchable() || cslaType.IsDynamicEditableRoot() || cslaType.IsReadOnlyObject()) return true; return false; } public static bool IsObjectType(this CslaObjectInfo info) { return info.ObjectType.IsObjectType(); } public static bool IsEditableType(this CslaObjectType cslaType) { if (cslaType.IsEditableChild() || cslaType.IsEditableChildCollection() || cslaType.IsEditableRoot() || cslaType.IsEditableRootCollection() || cslaType.IsEditableSwitchable() || cslaType.IsDynamicEditableRoot() || cslaType.IsDynamicEditableRootCollection()) return true; return false; } public static bool IsEditableType(this CslaObjectInfo info) { return info.ObjectType.IsEditableType(); } public static bool IsReadOnlyType(this CslaObjectType cslaType) { if (cslaType.IsReadOnlyCollection() || cslaType.IsReadOnlyObject()) return true; return false; } public static bool IsReadOnlyType(this CslaObjectInfo info) { return info.ObjectType.IsReadOnlyType(); } // TODO Same "IsChildType" name but different results!!! When fixing, check also templates. public static bool IsChildType(this CslaObjectType cslaType) { if (cslaType.IsEditableChild() || cslaType.IsEditableChildCollection()) return true; return false; } // TODO Same "IsChildType" name but different results!!! When fixing, check also templates. public static bool IsChildType(this CslaObjectInfo info) { if (info.IsEditableSwitchable() || info.IsEditableChild() || info.IsEditableChildCollection() || ((info.IsReadOnlyObject() || info.IsReadOnlyCollection()) && info.ParentType != string.Empty)) return true; return false; } public static bool IsDynamicList(this CslaObjectInfo info) { return info.IsDynamicEditableRootCollection() || info.IsBaseClass() && info.CslaBaseClass.IsDynamicEditableRootCollection(); } public static bool IsNotDynamicList(this CslaObjectInfo info) { return !info.IsDynamicList(); } public static bool IsRootType(this CslaObjectInfo info) { if (info.IsEditableRoot() || info.IsEditableRootCollection() || info.IsDynamicEditableRoot() || info.IsDynamicEditableRootCollection() || info.IsEditableSwitchable() || ((info.IsReadOnlyObject() || info.IsReadOnlyCollection()) && info.ParentType == string.Empty)) return true; return false; } public static bool IsNotRootType(this CslaObjectInfo info) { if (info.IsEditableChild() || (info.IsReadOnlyObject() && info.ParentType != string.Empty)) return true; return false; } public static bool IsItemType(this CslaObjectInfo info) { var cslaType = info.ObjectType; if (cslaType.IsEditableRoot() || cslaType.IsEditableChild() || cslaType.IsDynamicEditableRoot() || cslaType.IsReadOnlyObject()) { var parent = info.Parent.CslaObjects.Find(info.ParentType); if (parent != null && parent.ObjectType.IsCollectionType()) return true; } return false; } public static bool IsRootOrRootItem(this CslaObjectInfo info) { var result = !info.IsChildType(); if (!result) { var parentInfo = info.Parent.CslaObjects.Find(info.ParentType); if (parentInfo != null) result = !parentInfo.IsChildType(); } return result; } public static bool IsNotDbConsumer(this CslaObjectInfo info) { return info.IsUnitOfWork() || info.IsBaseClass() || info.IsCriteriaClass(); } public static bool CanHaveParentProperties(this CslaObjectInfo info) { if (info.ObjectType.IsCollectionType()) return false; // Object is a collection and thus has no Properties if (info.IsEditableRoot() || info.IsDynamicEditableRoot()) return false; // Object is root and thus has no ParentType var parent = info.Parent.CslaObjects.Find(info.ParentType); if (parent == null) return info.IsReadOnlyObject(); // Object is ReadOnly and might have ParentProperties if (parent.ObjectType.IsCollectionType()) // ParentType is a collection and thus has no Properties { if (parent.IsEditableRootCollection() || parent.IsDynamicEditableRootCollection() || (parent.IsReadOnlyCollection() && parent.ParentType == string.Empty)) return false; // ParentType is a root collection; end of line return true; // There should be a grand-parent with properties } if (parent.ObjectType.IsObjectType()) return true; // ParentType exists and has properties return false; } public static CslaObjectInfo FindParentObject(this CslaObjectInfo info) { CslaObjectInfo parentInfo = null; if (string.IsNullOrEmpty(info.ParentType)) { // no parent specified; find the object whose child is this object foreach (var cslaObject in info.Parent.CslaObjects) { foreach (var childProperty in cslaObject.GetAllChildProperties()) { if (childProperty.TypeName == info.ObjectName) parentInfo = cslaObject; } if (parentInfo != null) break; } } else { parentInfo = info.Parent.CslaObjects.Find(info.ParentType); } if (parentInfo != null) { if (parentInfo.ItemType == info.ObjectName) return parentInfo.FindParentObject(); if (parentInfo.GetAllChildProperties().FindType(info.ObjectName) != null) return parentInfo; /*if (parentInfo.GetCollectionChildProperties().FindType(info.ObjectName) != null) return parentInfo;*/ } return null; } public static CslaObjectInfo FindAncestor(this CslaObjectInfo info) { while (true) { if (info.ParentType == string.Empty) // no parent specified; this is the last ancestor return info; var parentInfo = info.Parent.CslaObjects.Find(info.ParentType); if (parentInfo == null) // the parent wasn't found; for practical purposes, this is the last ancestor return info; var notFound = true; foreach (var child in parentInfo.AllChildProperties) { if (child.TypeName == info.ParentType) { notFound = false; break; } } if (notFound) // the parent doesn't know the child; for practical purposes, this is the last ancestor return info; info = parentInfo; } } public static List<string> GetObjectTree(this CslaObjectInfo info) { return info.FindAncestor().GetDescendants(); } public static List<string> GetDescendants(this CslaObjectInfo info) { var result = new List<string> {info.ObjectName}; if (info.ObjectType.IsCollectionType()) { result.AddRange(info.Parent.CslaObjects.Find(info.ItemType).GetDescendants()); } foreach (var child in info.GetCollectionChildProperties()) { var childTypeName = child.TypeName; if (childTypeName == string.Empty) continue; result.Add(childTypeName); var childInfo = info.Parent.CslaObjects.Find(childTypeName); result.AddRange(info.Parent.CslaObjects.Find(childInfo.ItemType).GetDescendants()); } foreach (var child in info.GetNonCollectionChildProperties()) { var childTypeName = child.TypeName; if (childTypeName == string.Empty) continue; result.AddRange(info.Parent.CslaObjects.Find(childTypeName).GetDescendants()); } return result; } public static string AddSpaceBeforeUpperCase(this string text) { //http://stackoverflow.com/questions/272633/add-spaces-before-capital-letters if (string.IsNullOrWhiteSpace(text)) return string.Empty; var newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (var i = 1; i < text.Length; i++) { var currentUpper = char.IsUpper(text[i]); var prevUpper = char.IsUpper(text[i - 1]); var nextUpper = (text.Length > i + 1) ? char.IsUpper(text[i + 1]) || char.IsWhiteSpace(text[i + 1]) : prevUpper; var spaceExists = char.IsWhiteSpace(text[i - 1]); if (currentUpper && !spaceExists && (!nextUpper || !prevUpper)) newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } #region EditableRoot public static bool IsEditableRoot(this CslaObjectType cslaType) { return cslaType == CslaObjectType.EditableRoot; } public static bool IsEditableRoot(this CslaObjectInfo info) { return info.ObjectType.IsEditableRoot(); } public static bool IsNotEditableRoot(this CslaObjectType cslaType) { return !cslaType.IsEditableRoot(); } public static bool IsNotEditableRoot(this CslaObjectInfo info) { return !info.IsEditableRoot(); } #endregion #region EditableChild public static bool IsEditableChild(this CslaObjectType cslaType) { return cslaType == CslaObjectType.EditableChild; } public static bool IsEditableChild(this CslaObjectInfo info) { return info.ObjectType.IsEditableChild(); } public static bool IsNotEditableChild(this CslaObjectType cslaType) { return !cslaType.IsEditableChild(); } public static bool IsNotEditableChild(this CslaObjectInfo info) { return !info.IsEditableChild(); } #endregion #region EditableSwitchable public static bool IsEditableSwitchable(this CslaObjectType cslaType) { return cslaType == CslaObjectType.EditableSwitchable; } public static bool IsEditableSwitchable(this CslaObjectInfo info) { return info.ObjectType.IsEditableSwitchable(); } public static bool IsNotEditableSwitchable(this CslaObjectType cslaType) { return !cslaType.IsEditableSwitchable(); } public static bool IsNotEditableSwitchable(this CslaObjectInfo info) { return !info.IsEditableSwitchable(); } #endregion #region DynamicEditableRoot public static bool IsDynamicEditableRoot(this CslaObjectType cslaType) { return cslaType == CslaObjectType.DynamicEditableRoot; } public static bool IsDynamicEditableRoot(this CslaObjectInfo info) { return info.ObjectType.IsDynamicEditableRoot(); } public static bool IsNotDynamicEditableRoot(this CslaObjectType cslaType) { return !cslaType.IsDynamicEditableRoot(); } public static bool IsNotDynamicEditableRoot(this CslaObjectInfo info) { return !info.IsDynamicEditableRoot(); } #endregion #region EditableRootCollection public static bool IsEditableRootCollection(this CslaObjectType cslaType) { return cslaType == CslaObjectType.EditableRootCollection; } public static bool IsEditableRootCollection(this CslaObjectInfo info) { return info.ObjectType.IsEditableRootCollection(); } public static bool IsNotEditableRootCollection(this CslaObjectType cslaType) { return !cslaType.IsEditableRootCollection(); } public static bool IsNotEditableRootCollection(this CslaObjectInfo info) { return !info.IsEditableRootCollection(); } #endregion #region DynamicEditableRootCollection public static bool IsDynamicEditableRootCollection(this CslaObjectType cslaType) { return cslaType == CslaObjectType.DynamicEditableRootCollection; } public static bool IsDynamicEditableRootCollection(this CslaObjectInfo info) { return info.ObjectType.IsDynamicEditableRootCollection(); } public static bool IsNotDynamicEditableRootCollection(this CslaObjectType cslaType) { return !cslaType.IsDynamicEditableRootCollection(); } public static bool IsNotDynamicEditableRootCollection(this CslaObjectInfo info) { return !info.IsDynamicEditableRootCollection(); } #endregion #region EditableChildCollection public static bool IsEditableChildCollection(this CslaObjectType cslaType) { return cslaType == CslaObjectType.EditableChildCollection; } public static bool IsEditableChildCollection(this CslaObjectInfo info) { return info.ObjectType.IsEditableChildCollection(); } public static bool IsNotEditableChildCollection(this CslaObjectType cslaType) { return !cslaType.IsEditableChildCollection(); } public static bool IsNotEditableChildCollection(this CslaObjectInfo info) { return !info.IsEditableChildCollection(); } #endregion #region ReadOnlyObject public static bool IsReadOnlyObject(this CslaObjectType cslaType) { return cslaType == CslaObjectType.ReadOnlyObject; } public static bool IsReadOnlyObject(this CslaObjectInfo info) { return info.ObjectType.IsReadOnlyObject(); } public static bool IsNotReadOnlyObject(this CslaObjectType cslaType) { return !cslaType.IsReadOnlyObject(); } public static bool IsNotReadOnlyObject(this CslaObjectInfo info) { return !info.IsReadOnlyObject(); } #endregion #region ReadOnlyCollection public static bool IsReadOnlyCollection(this CslaObjectType cslaType) { return cslaType == CslaObjectType.ReadOnlyCollection; } public static bool IsReadOnlyCollection(this CslaObjectInfo info) { return info.ObjectType.IsReadOnlyCollection(); } public static bool IsNotReadOnlyCollection(this CslaObjectType cslaType) { return !cslaType.IsReadOnlyCollection(); } public static bool IsNotReadOnlyCollection(this CslaObjectInfo info) { return !info.IsReadOnlyCollection(); } #endregion #region NameValueList public static bool IsNameValueList(this CslaObjectType cslaType) { return cslaType == CslaObjectType.NameValueList; } public static bool IsNameValueList(this CslaObjectInfo info) { return info.ObjectType.IsNameValueList(); } public static bool IsNotNameValueList(this CslaObjectType cslaType) { return !cslaType.IsNameValueList(); } public static bool IsNotNameValueList(this CslaObjectInfo info) { return !info.IsNameValueList(); } #endregion #region UnitOfWork public static bool IsUnitOfWork(this CslaObjectType cslaType) { return cslaType == CslaObjectType.UnitOfWork; } public static bool IsUnitOfWork(this CslaObjectInfo info) { return info.ObjectType.IsUnitOfWork(); } public static bool IsNotUnitOfWork(this CslaObjectType cslaType) { return !cslaType.IsUnitOfWork(); } public static bool IsNotUnitOfWork(this CslaObjectInfo info) { return !info.IsUnitOfWork(); } #endregion #region CriteriaClass public static bool IsCriteriaClass(this CslaObjectType cslaType) { return cslaType == CslaObjectType.CriteriaClass; } public static bool IsCriteriaClass(this CslaObjectInfo info) { return info.ObjectType.IsCriteriaClass(); } public static bool IsNotCriteriaClass(this CslaObjectType cslaType) { return !cslaType.IsCriteriaClass(); } public static bool IsNotCriteriaClass(this CslaObjectInfo info) { return !info.IsCriteriaClass(); } #endregion #region BaseClass public static bool IsBaseClass(this CslaObjectType cslaType) { return cslaType == CslaObjectType.BaseClass; } public static bool IsBaseClass(this CslaObjectInfo info) { return info.ObjectType.IsBaseClass(); } public static bool IsNotBaseClass(this CslaObjectType cslaType) { return !cslaType.IsBaseClass(); } public static bool IsNotBaseClass(this CslaObjectInfo info) { return !info.IsBaseClass(); } #endregion #region PlaceHolder public static bool IsPlaceHolder(this CslaObjectType cslaType) { return cslaType == CslaObjectType.PlaceHolder; } public static bool IsPlaceHolder(this CslaObjectInfo info) { return info.ObjectType.IsPlaceHolder(); } public static bool IsNotPlaceHolder(this CslaObjectType cslaType) { return !cslaType.IsPlaceHolder(); } public static bool IsNotPlaceHolder(this CslaObjectInfo info) { return !info.IsPlaceHolder(); } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using Verse.DecoderDescriptors.Tree; namespace Verse.Schemas.Protobuf { internal class DecoderConverter : IDecoderConverter<ProtobufValue> { private readonly Dictionary<Type, object> converters = new Dictionary<Type, object> { { typeof (bool), new Converter<ProtobufValue, bool>(DecoderConverter.ToBoolean) }, { typeof (char), new Converter<ProtobufValue, char>(DecoderConverter.ToCharacter) }, { typeof (decimal), new Converter<ProtobufValue, decimal>(DecoderConverter.ToDecimal) }, { typeof (float), new Converter<ProtobufValue, float>(DecoderConverter.ToFloat32) }, { typeof (double), new Converter<ProtobufValue, double>(DecoderConverter.ToFloat64) }, { typeof (sbyte), new Converter<ProtobufValue, sbyte>(DecoderConverter.ToInteger8s) }, { typeof (byte), new Converter<ProtobufValue, byte>(DecoderConverter.ToInteger8u) }, { typeof (short), new Converter<ProtobufValue, short>(DecoderConverter.ToInteger16s) }, { typeof (ushort), new Converter<ProtobufValue, ushort>(DecoderConverter.ToInteger16u) }, { typeof (int), new Converter<ProtobufValue, int>(DecoderConverter.ToInteger32s) }, { typeof (uint), new Converter<ProtobufValue, uint>(DecoderConverter.ToInteger32u) }, { typeof (long), new Converter<ProtobufValue, long>(DecoderConverter.ToInteger64s) }, { typeof (ulong), new Converter<ProtobufValue, ulong>(DecoderConverter.ToInteger64u) }, { typeof (string), new Converter<ProtobufValue, string>(DecoderConverter.ToString) }, { typeof (ProtobufValue), new Converter<ProtobufValue, ProtobufValue>(v => v) } }; public Converter<ProtobufValue, TTo> Get<TTo>() { if (!this.converters.TryGetValue(typeof (TTo), out var box)) { throw new InvalidCastException( string.Format( CultureInfo.InvariantCulture, "no available converter from Protobuf value to type '{0}'", typeof (TTo))); } return (Converter<ProtobufValue, TTo>)box; } public void Set<TTo>(Converter<ProtobufValue, TTo> converter) { this.converters[typeof (TTo)] = converter ?? throw new ArgumentNullException(nameof(converter)); } private static bool ToBoolean(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean; case ProtobufType.Float32: return Math.Abs(value.Float32) >= float.Epsilon; case ProtobufType.Float64: return Math.Abs(value.Float64) >= float.Epsilon; case ProtobufType.Signed: return value.Signed != 0; case ProtobufType.String: return !string.IsNullOrEmpty(value.String); case ProtobufType.Unsigned: return value.Unsigned != 0; default: return default; } } private static char ToCharacter(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? '1' : '0'; case ProtobufType.Float32: return (char) value.Float32; case ProtobufType.Float64: return (char) value.Float64; case ProtobufType.Signed: return (char) value.Signed; case ProtobufType.String: return value.String.Length > 0 ? value.String[0] : default; case ProtobufType.Unsigned: return (char) value.Unsigned; default: return default; } } private static decimal ToDecimal(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1 : 0; case ProtobufType.Float32: return (decimal) value.Float32; case ProtobufType.Float64: return (decimal) value.Float64; case ProtobufType.Signed: return value.Signed; case ProtobufType.String: return decimal.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (char) value.Unsigned; default: return default; } } private static float ToFloat32(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1 : 0; case ProtobufType.Float32: return value.Float32; case ProtobufType.Float64: return (float) value.Float64; case ProtobufType.Signed: return value.Signed; case ProtobufType.String: return float.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return value.Unsigned; default: return default; } } private static double ToFloat64(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1 : 0; case ProtobufType.Float32: return value.Float32; case ProtobufType.Float64: return value.Float64; case ProtobufType.Signed: return value.Signed; case ProtobufType.String: return double.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return value.Unsigned; default: return default; } } private static sbyte ToInteger8s(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? (sbyte) 1 : (sbyte) 0; case ProtobufType.Float32: return (sbyte) value.Float32; case ProtobufType.Float64: return (sbyte) value.Float64; case ProtobufType.Signed: return (sbyte) value.Signed; case ProtobufType.String: return sbyte.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (sbyte) value.Unsigned; default: return default; } } private static byte ToInteger8u(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? (byte) 1 : (byte) 0; case ProtobufType.Float32: return (byte) value.Float32; case ProtobufType.Float64: return (byte) value.Float64; case ProtobufType.Signed: return (byte) value.Signed; case ProtobufType.String: return byte.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (byte) value.Unsigned; default: return default; } } private static short ToInteger16s(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? (short) 1 : (short) 0; case ProtobufType.Float32: return (short) value.Float32; case ProtobufType.Float64: return (short) value.Float64; case ProtobufType.Signed: return (short) value.Signed; case ProtobufType.String: return short.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (short) value.Unsigned; default: return default; } } private static ushort ToInteger16u(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? (ushort) 1 : (ushort) 0; case ProtobufType.Float32: return (ushort) value.Float32; case ProtobufType.Float64: return (ushort) value.Float64; case ProtobufType.Signed: return (ushort) value.Signed; case ProtobufType.String: return ushort.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (ushort) value.Unsigned; default: return default; } } private static int ToInteger32s(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1 : 0; case ProtobufType.Float32: return (int) value.Float32; case ProtobufType.Float64: return (int) value.Float64; case ProtobufType.Signed: return (int) value.Signed; case ProtobufType.String: return int.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (int) value.Unsigned; default: return default; } } private static uint ToInteger32u(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1u : 0u; case ProtobufType.Float32: return (uint) value.Float32; case ProtobufType.Float64: return (uint) value.Float64; case ProtobufType.Signed: return (uint) value.Signed; case ProtobufType.String: return uint.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (uint) value.Unsigned; default: return default; } } private static long ToInteger64s(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1 : 0; case ProtobufType.Float32: return (long) value.Float32; case ProtobufType.Float64: return (long) value.Float64; case ProtobufType.Signed: return value.Signed; case ProtobufType.String: return long.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return (long) value.Unsigned; default: return default; } } private static ulong ToInteger64u(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? 1u : 0u; case ProtobufType.Float32: return (ulong) value.Float32; case ProtobufType.Float64: return (ulong) value.Float64; case ProtobufType.Signed: return (ulong) value.Signed; case ProtobufType.String: return ulong.TryParse(value.String, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : default; case ProtobufType.Unsigned: return value.Unsigned; default: return default; } } private static string ToString(ProtobufValue value) { switch (value.Type) { case ProtobufType.Boolean: return value.Boolean ? "1" : string.Empty; case ProtobufType.Float32: return value.Float32.ToString(CultureInfo.InvariantCulture); case ProtobufType.Float64: return value.Float64.ToString(CultureInfo.InvariantCulture); case ProtobufType.Signed: return value.Signed.ToString(CultureInfo.InvariantCulture); case ProtobufType.String: return value.String; case ProtobufType.Unsigned: return value.Unsigned.ToString(CultureInfo.InvariantCulture); default: return string.Empty; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Talent.V4Beta1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedCompanyServiceClientSnippets { /// <summary>Snippet for CreateCompany</summary> public void CreateCompanyRequestObject() { // Snippet: CreateCompany(CreateCompanyRequest, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) CreateCompanyRequest request = new CreateCompanyRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Company = new Company(), }; // Make the request Company response = companyServiceClient.CreateCompany(request); // End snippet } /// <summary>Snippet for CreateCompanyAsync</summary> public async Task CreateCompanyRequestObjectAsync() { // Snippet: CreateCompanyAsync(CreateCompanyRequest, CallSettings) // Additional: CreateCompanyAsync(CreateCompanyRequest, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) CreateCompanyRequest request = new CreateCompanyRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Company = new Company(), }; // Make the request Company response = await companyServiceClient.CreateCompanyAsync(request); // End snippet } /// <summary>Snippet for CreateCompany</summary> public void CreateCompany() { // Snippet: CreateCompany(string, Company, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/tenants/[TENANT]"; Company company = new Company(); // Make the request Company response = companyServiceClient.CreateCompany(parent, company); // End snippet } /// <summary>Snippet for CreateCompanyAsync</summary> public async Task CreateCompanyAsync() { // Snippet: CreateCompanyAsync(string, Company, CallSettings) // Additional: CreateCompanyAsync(string, Company, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/tenants/[TENANT]"; Company company = new Company(); // Make the request Company response = await companyServiceClient.CreateCompanyAsync(parent, company); // End snippet } /// <summary>Snippet for CreateCompany</summary> public void CreateCompanyResourceNames1() { // Snippet: CreateCompany(TenantName, Company, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); Company company = new Company(); // Make the request Company response = companyServiceClient.CreateCompany(parent, company); // End snippet } /// <summary>Snippet for CreateCompanyAsync</summary> public async Task CreateCompanyResourceNames1Async() { // Snippet: CreateCompanyAsync(TenantName, Company, CallSettings) // Additional: CreateCompanyAsync(TenantName, Company, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); Company company = new Company(); // Make the request Company response = await companyServiceClient.CreateCompanyAsync(parent, company); // End snippet } /// <summary>Snippet for CreateCompany</summary> public void CreateCompanyResourceNames2() { // Snippet: CreateCompany(ProjectName, Company, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Company company = new Company(); // Make the request Company response = companyServiceClient.CreateCompany(parent, company); // End snippet } /// <summary>Snippet for CreateCompanyAsync</summary> public async Task CreateCompanyResourceNames2Async() { // Snippet: CreateCompanyAsync(ProjectName, Company, CallSettings) // Additional: CreateCompanyAsync(ProjectName, Company, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Company company = new Company(); // Make the request Company response = await companyServiceClient.CreateCompanyAsync(parent, company); // End snippet } /// <summary>Snippet for GetCompany</summary> public void GetCompanyRequestObject() { // Snippet: GetCompany(GetCompanyRequest, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) GetCompanyRequest request = new GetCompanyRequest { CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), }; // Make the request Company response = companyServiceClient.GetCompany(request); // End snippet } /// <summary>Snippet for GetCompanyAsync</summary> public async Task GetCompanyRequestObjectAsync() { // Snippet: GetCompanyAsync(GetCompanyRequest, CallSettings) // Additional: GetCompanyAsync(GetCompanyRequest, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) GetCompanyRequest request = new GetCompanyRequest { CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), }; // Make the request Company response = await companyServiceClient.GetCompanyAsync(request); // End snippet } /// <summary>Snippet for GetCompany</summary> public void GetCompany() { // Snippet: GetCompany(string, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]"; // Make the request Company response = companyServiceClient.GetCompany(name); // End snippet } /// <summary>Snippet for GetCompanyAsync</summary> public async Task GetCompanyAsync() { // Snippet: GetCompanyAsync(string, CallSettings) // Additional: GetCompanyAsync(string, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]"; // Make the request Company response = await companyServiceClient.GetCompanyAsync(name); // End snippet } /// <summary>Snippet for GetCompany</summary> public void GetCompanyResourceNames() { // Snippet: GetCompany(CompanyName, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"); // Make the request Company response = companyServiceClient.GetCompany(name); // End snippet } /// <summary>Snippet for GetCompanyAsync</summary> public async Task GetCompanyResourceNamesAsync() { // Snippet: GetCompanyAsync(CompanyName, CallSettings) // Additional: GetCompanyAsync(CompanyName, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"); // Make the request Company response = await companyServiceClient.GetCompanyAsync(name); // End snippet } /// <summary>Snippet for UpdateCompany</summary> public void UpdateCompanyRequestObject() { // Snippet: UpdateCompany(UpdateCompanyRequest, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) UpdateCompanyRequest request = new UpdateCompanyRequest { Company = new Company(), UpdateMask = new FieldMask(), }; // Make the request Company response = companyServiceClient.UpdateCompany(request); // End snippet } /// <summary>Snippet for UpdateCompanyAsync</summary> public async Task UpdateCompanyRequestObjectAsync() { // Snippet: UpdateCompanyAsync(UpdateCompanyRequest, CallSettings) // Additional: UpdateCompanyAsync(UpdateCompanyRequest, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) UpdateCompanyRequest request = new UpdateCompanyRequest { Company = new Company(), UpdateMask = new FieldMask(), }; // Make the request Company response = await companyServiceClient.UpdateCompanyAsync(request); // End snippet } /// <summary>Snippet for UpdateCompany</summary> public void UpdateCompany() { // Snippet: UpdateCompany(Company, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) Company company = new Company(); // Make the request Company response = companyServiceClient.UpdateCompany(company); // End snippet } /// <summary>Snippet for UpdateCompanyAsync</summary> public async Task UpdateCompanyAsync() { // Snippet: UpdateCompanyAsync(Company, CallSettings) // Additional: UpdateCompanyAsync(Company, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) Company company = new Company(); // Make the request Company response = await companyServiceClient.UpdateCompanyAsync(company); // End snippet } /// <summary>Snippet for DeleteCompany</summary> public void DeleteCompanyRequestObject() { // Snippet: DeleteCompany(DeleteCompanyRequest, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) DeleteCompanyRequest request = new DeleteCompanyRequest { CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), }; // Make the request companyServiceClient.DeleteCompany(request); // End snippet } /// <summary>Snippet for DeleteCompanyAsync</summary> public async Task DeleteCompanyRequestObjectAsync() { // Snippet: DeleteCompanyAsync(DeleteCompanyRequest, CallSettings) // Additional: DeleteCompanyAsync(DeleteCompanyRequest, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) DeleteCompanyRequest request = new DeleteCompanyRequest { CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), }; // Make the request await companyServiceClient.DeleteCompanyAsync(request); // End snippet } /// <summary>Snippet for DeleteCompany</summary> public void DeleteCompany() { // Snippet: DeleteCompany(string, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]"; // Make the request companyServiceClient.DeleteCompany(name); // End snippet } /// <summary>Snippet for DeleteCompanyAsync</summary> public async Task DeleteCompanyAsync() { // Snippet: DeleteCompanyAsync(string, CallSettings) // Additional: DeleteCompanyAsync(string, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/tenants/[TENANT]/companies/[COMPANY]"; // Make the request await companyServiceClient.DeleteCompanyAsync(name); // End snippet } /// <summary>Snippet for DeleteCompany</summary> public void DeleteCompanyResourceNames() { // Snippet: DeleteCompany(CompanyName, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"); // Make the request companyServiceClient.DeleteCompany(name); // End snippet } /// <summary>Snippet for DeleteCompanyAsync</summary> public async Task DeleteCompanyResourceNamesAsync() { // Snippet: DeleteCompanyAsync(CompanyName, CallSettings) // Additional: DeleteCompanyAsync(CompanyName, CancellationToken) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) CompanyName name = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"); // Make the request await companyServiceClient.DeleteCompanyAsync(name); // End snippet } /// <summary>Snippet for ListCompanies</summary> public void ListCompaniesRequestObject() { // Snippet: ListCompanies(ListCompaniesRequest, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) ListCompaniesRequest request = new ListCompaniesRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), RequireOpenJobs = false, }; // Make the request PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(request); // Iterate over all response items, lazily performing RPCs as required foreach (Company item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCompaniesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompaniesAsync</summary> public async Task ListCompaniesRequestObjectAsync() { // Snippet: ListCompaniesAsync(ListCompaniesRequest, CallSettings) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) ListCompaniesRequest request = new ListCompaniesRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), RequireOpenJobs = false, }; // Make the request PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Company item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCompaniesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompanies</summary> public void ListCompanies() { // Snippet: ListCompanies(string, string, int?, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/tenants/[TENANT]"; // Make the request PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Company item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCompaniesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompaniesAsync</summary> public async Task ListCompaniesAsync() { // Snippet: ListCompaniesAsync(string, string, int?, CallSettings) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/tenants/[TENANT]"; // Make the request PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Company item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCompaniesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompanies</summary> public void ListCompaniesResourceNames1() { // Snippet: ListCompanies(TenantName, string, int?, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); // Make the request PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Company item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCompaniesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompaniesAsync</summary> public async Task ListCompaniesResourceNames1Async() { // Snippet: ListCompaniesAsync(TenantName, string, int?, CallSettings) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) TenantName parent = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"); // Make the request PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Company item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCompaniesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompanies</summary> public void ListCompaniesResourceNames2() { // Snippet: ListCompanies(ProjectName, string, int?, CallSettings) // Create client CompanyServiceClient companyServiceClient = CompanyServiceClient.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompanies(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Company item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCompaniesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListCompaniesAsync</summary> public async Task ListCompaniesResourceNames2Async() { // Snippet: ListCompaniesAsync(ProjectName, string, int?, CallSettings) // Create client CompanyServiceClient companyServiceClient = await CompanyServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListCompaniesResponse, Company> response = companyServiceClient.ListCompaniesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Company item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCompaniesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Company item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Company> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Company item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
using System; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Windows.Forms; namespace ProgressDialogs { public class OperationsProgressDialog : Component { const string CLSID_ProgressDialog = "{F8383852-FCD3-11d1-A6B9-006097DF5BD4}"; const string IDD_ProgressDialog = "0C9FB851-E5C9-43EB-A370-F0677B13874C"; const string CLSID_IShellItem = "{2559a1f3-21d7-11d4-bdaf-00c04f60b9f0}"; private Type _progressDialogType; private Type _IShellItemType; private IOperationsProgressDialog _nativeProgressDialog; private PROGDLG dialogFlags; private SPACTION operationFlags; private PDMODE modeFlags; private long currentProgress; private long totalProgress; private long currentSize; private long totalSize; private long currentItems; private long totalItems; private bool estimateValue; private IShellItem sourceItem; private IShellItem destItem; private IShellItem currentItem; private DIALOGSTATUS dialogStatus; public enum DIALOGSTATUS { DLG_NOTSTARTED = 0, DLG_RUNNING = 1, DLG_DISPOSED = 2, DLG_ERRORED = 3, } public DIALOGSTATUS IsDialogActive { get { return dialogStatus; } } public PROGDLG DialogFlags { set { dialogFlags = value; } get { return dialogFlags; } } public SPACTION OperationFlags { set { operationFlags = value; } get { return operationFlags; } } public PDMODE ModeFlags { set { modeFlags = value; } get { return modeFlags; } } public long ProgressBarValue { get { return currentProgress; } set { currentProgress = value; UpdateProgress(); } } public long ProgressBarMaxValue { get { return totalProgress; } set { totalProgress = value; UpdateProgress(); } } public long ProgressDialogSizeValue { get { return currentSize; } set { currentSize = value; UpdateProgress(); } } public long ProgressDialogSizeMaxValue { get { return totalSize; } set { totalSize = value; UpdateProgress(); } } public long ProgressDialogItemsValue { get { return currentItems; } set { currentItems = value; UpdateProgress(); } } public long ProgressDialogItemsMaxValue { get { return totalItems; } set { totalItems = value; UpdateProgress(); } } /// <summary> /// Checks if the dialog has reached 100%. /// </summary> public bool isFinished { get { return currentProgress == totalProgress; } } /// <summary> /// Returns a boolean of if the user has cancelled or not. /// </summary> public bool hasUserCancelled { get { if (_nativeProgressDialog != null) { return _nativeProgressDialog.GetOperationStatus() == PDOPSTATUS.PDOPS_CANCELLED; } else { return false; } } } /// <summary> /// Estimates the progress based on the item count. /// </summary> public bool EstimateValue { set { estimateValue = value; } } /// <summary> /// Closes the dialog. /// </summary> public async void Close() { if (_nativeProgressDialog != null && dialogStatus != DIALOGSTATUS.DLG_DISPOSED) { _nativeProgressDialog.StopProgressDialog(); dialogStatus = DIALOGSTATUS.DLG_DISPOSED; await Task.Delay(900); Marshal.FinalReleaseComObject(_nativeProgressDialog); _nativeProgressDialog = null; } } private void UpdateProgress() { if (estimateValue) { currentProgress = currentItems; totalProgress = totalItems; } if (_nativeProgressDialog != null && dialogStatus != DIALOGSTATUS.DLG_DISPOSED) { _nativeProgressDialog.UpdateProgress((ulong)currentProgress, (ulong)totalProgress, (ulong)currentSize, (ulong)totalSize, (ulong)currentItems, (ulong)totalItems); _nativeProgressDialog.UpdateLocations(sourceItem, destItem, currentItem); } } /// <summary> /// Initializes the dialog. /// </summary> public OperationsProgressDialog() { dialogStatus = DIALOGSTATUS.DLG_NOTSTARTED; _progressDialogType = Type.GetTypeFromCLSID(new Guid(CLSID_ProgressDialog)); _IShellItemType = Type.GetTypeFromCLSID(new Guid(CLSID_IShellItem)); dialogFlags = PROGDLG.PROGDLG_NORMAL; operationFlags = SPACTION.SPACTION_NONE; modeFlags = PDMODE.PDM_DEFAULT; currentProgress = 0; totalProgress = 100; currentSize = 0; totalSize = 100; currentItems = 0; totalItems = 100; estimateValue = false; SHCreateItemFromParsingName("https://andai.heliohost.org/packages.php", IntPtr.Zero, typeof(IShellItem).GUID, out sourceItem); SHCreateItemFromParsingName(Environment.CurrentDirectory, IntPtr.Zero, typeof(IShellItem).GUID, out destItem); SHCreateItemFromParsingName(Environment.CurrentDirectory, IntPtr.Zero, typeof(IShellItem).GUID, out currentItem); } public OperationsProgressDialog(IContainer container) : this() { container.Add(this); } /// <summary> /// Shows the dialog with the specified parent. If the parent is null, uses the active form. /// </summary> /// <param name="parent"></param> public void Show(IWin32Window parent) { if (parent == null) parent = Form.ActiveForm; IntPtr handle = (parent == null) ? IntPtr.Zero : parent.Handle; _nativeProgressDialog = (IOperationsProgressDialog)Activator.CreateInstance(_progressDialogType); _nativeProgressDialog.StartProgressDialog(handle, dialogFlags); _nativeProgressDialog.SetOperation(operationFlags); _nativeProgressDialog.SetMode(modeFlags); UpdateProgress(); dialogStatus = DIALOGSTATUS.DLG_RUNNING; } [ComImport, Guid(IDD_ProgressDialog), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IOperationsProgressDialog { void StartProgressDialog(IntPtr hwndOwner, PROGDLG flags); void StopProgressDialog(); void SetOperation(SPACTION action); void SetMode(PDMODE mode); void UpdateProgress(ulong ullPointsCurrent, ulong ullPointsTotal, ulong ullSizeCurrent, ulong ullSizeTotal, ulong ullItemsCurrent, ulong ullItemsTotal); void UpdateLocations(IShellItem psiSource, IShellItem psiTarget, IShellItem psiItem); void ResetTimer(); void PauseTimer(); void ResumeTimer(); void GetMilliseconds(ulong pullElapsed, ulong pullRemaining); PDOPSTATUS GetOperationStatus(); } /// <summary> /// Shows the dialog (if no settings were modified, uses default). /// </summary> internal void Show() { Show(null); } /// <summary> /// Specifies what the dialog is currently doing. /// </summary> /// <param name="operation"></param> internal void SetOperation(SPACTION operation) { if(_nativeProgressDialog != null && dialogStatus != DIALOGSTATUS.DLG_DISPOSED) { _nativeProgressDialog.SetOperation(operation); } } /// <summary> /// Specifies the status of the current operation. /// </summary> /// <param name="mode"></param> internal void SetMode(PDMODE mode) { if (_nativeProgressDialog != null && dialogStatus!=DIALOGSTATUS.DLG_DISPOSED) { _nativeProgressDialog.SetMode(mode); } } /// <summary> /// Specifies the items being used. /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="item"></param> internal void UpdateLocations(string source, string destination, string item) { try { SHCreateItemFromParsingName(source, IntPtr.Zero, typeof(IShellItem).GUID, out sourceItem); SHCreateItemFromParsingName(destination, IntPtr.Zero, typeof(IShellItem).GUID, out destItem); SHCreateItemFromParsingName(item, IntPtr.Zero, typeof(IShellItem).GUID, out currentItem); } catch (FileNotFoundException ex) { throw new IOperationsProgressDialogException("One or more of the locations do not exist.", ex); } UpdateProgress(); } internal void UpdateLocations(string source, string destination) { try { System.Diagnostics.Debug.Print(Environment.CurrentDirectory + " " + source + " " + destination); SHCreateItemFromParsingName(source, IntPtr.Zero, typeof(IShellItem).GUID, out sourceItem); SHCreateItemFromParsingName(destination, IntPtr.Zero, typeof(IShellItem).GUID, out destItem); } catch (FileNotFoundException ex) { throw new IOperationsProgressDialogException("One or more of the locations do not exist.", ex); } UpdateProgress(); } internal void UpdateLocations(string item) { try { SHCreateItemFromParsingName(item.Replace("/", "\\"), IntPtr.Zero, typeof(IShellItem).GUID, out currentItem); } catch (FileNotFoundException ex) { try { SHCreateItemFromParsingName(Environment.CurrentDirectory + "\\" + item.Replace("/", "\\"), IntPtr.Zero, typeof(IShellItem).GUID, out currentItem); } catch (FileNotFoundException) { throw new IOperationsProgressDialogException("One or more of the locations do not exist.", ex); } } UpdateProgress(); } public enum PROGDLG : uint { /// <summary> /// Default, normal progress dialog behavior. /// </summary> PROGDLG_NORMAL = 0x00000000, /// <summary> /// The dialog is modal to its hwndOwner. The default setting is modeless. /// </summary> PROGDLG_MODAL = 0x00000001, /// <summary> /// Update "Line3" text with the time remaining. This flag does not need to be implicitly set because progress dialogs started by IOperationsProgressDialog::StartProgressDialog automatically display the time remaining. /// </summary> PROGDLG_AUTOTIME = 0x00000002, /// <summary> /// Do not show the time remaining. We do not recommend setting this flag through IOperationsProgressDialog because it goes against the purpose of the dialog. /// </summary> PROGDLG_NOTIME = 0x00000004, /// <summary> /// Do not display the minimize button. /// </summary> PROGDLG_NOMINIMIZE = 0x00000008, /// <summary> /// Do not display the progress bar. /// </summary> PROGDLG_NOPROGRESSBAR = 0x00000010, /// <summary> /// This flag is invalid in this method. To set the progress bar to marquee mode, use the flags in IOperationsProgressDialog::SetMode. /// </summary> PROGDLG_MARQUEEPROGRESS = 0x00000020, /// <summary> /// Do not display a cancel button because the operation cannot be canceled. Use this value only when absolutely necessary. /// </summary> PROGDLG_NOCANCEL = 0x00000040, /// <summary> /// Windows 7 and later. Indicates default, normal operation progress dialog behavior. /// </summary> OPPROGDLG_DEFAULT = 0x00000000, /// <summary> /// Display a pause button. Use this only in situations where the operation can be paused. /// </summary> OPPROGDLG_ENABLEPAUSE = 0x00000080, /// <summary> /// The operation can be undone through the dialog. The Stop button becomes Undo. If pressed, the Undo button then reverts to Stop. /// </summary> OPPROGDLG_ALLOWUNDO = 0x00000100, /// <summary> /// Do not display the path of source file in the progress dialog. /// </summary> OPPROGDLG_DONTDISPLAYSOURCEPATH = 0x00000200, /// <summary> /// Do not display the path of the destination file in the progress dialog. /// </summary> OPPROGDLG_DONTDISPLAYDESTPATH = 0x00000400, /// <summary> /// Windows 7 and later. If the estimated time to completion is greater than one day, do not display the time. /// </summary> OPPROGDLG_NOMULTIDAYESTIMATES = 0x00000800, /// <summary> /// Windows 7 and later. Do not display the location line in the progress dialog. /// </summary> OPPROGDLG_DONTDISPLAYLOCATIONS = 0x00001000 } public enum PDMODE : uint { /// <summary> /// Use the default progress dialog operations mode. /// </summary> PDM_DEFAULT = 0x00000000, /// <summary> /// The operation is running. /// </summary> PDM_RUN = 0x00000001, /// <summary> /// The operation is gathering data before it begins, such as calculating the predicted operation time. /// </summary> PDM_PREFLIGHT = 0x00000002, /// <summary> /// The operation is rolling back due to an Undo command from the user. /// </summary> PDM_UNDOING = 0x00000004, /// <summary> /// Error dialogs are blocking progress from continuing. /// </summary> /// <remarks> /// Appears to only work when progress has already begun. /// </remarks> PDM_ERRORSBLOCKING = 0x00000008, /// <summary> /// The length of the operation is indeterminate. Do not show a timer and display the progress bar in marquee mode. /// </summary> PDM_INDETERMINATE = 0x00000010 } public enum SPACTION : uint { /// <summary> /// No action is being performed. /// </summary> SPACTION_NONE = 0, /// <summary> /// Files are being moved. /// </summary> SPACTION_MOVING, /// <summary> /// Files are being copied. /// </summary> SPACTION_COPYING, /// <summary> /// Files are being deleted. /// </summary> SPACTION_RECYCLING, /// <summary> /// A set of attributes are being applied to files. /// </summary> SPACTION_APPLYINGATTRIBS, /// <summary> /// A file is being downloaded from a remote source. /// </summary> SPACTION_DOWNLOADING, /// <summary> /// An Internet search is being performed. /// </summary> SPACTION_SEARCHING_INTERNET, /// <summary> /// A calculation is being performed. /// </summary> SPACTION_CALCULATING, /// <summary> /// A file is being uploaded to a remote source. /// </summary> SPACTION_UPLOADING, /// <summary> /// A local search is being performed. /// </summary> SPACTION_SEARCHING_FILES, /// <summary> /// Windows Vista and later. A deletion is being performed. /// </summary> SPACTION_DELETING, /// <summary> /// Windows Vista and later. A renaming action is being performed. /// </summary> SPACTION_RENAMING, /// <summary> /// Windows Vista and later. A formatting action is being performed. /// </summary> SPACTION_FORMATTING, /// <summary> /// Windows 7 and later. A copy or move action is being performed. /// </summary> SPACTION_COPY_MOVING } public enum PDOPSTATUS : uint { /// <summary> /// Operation is running, no user intervention. /// </summary> PDOPS_RUNNING = 1, /// <summary> /// Operation has been paused by the user. /// </summary> PDOPS_PAUSED = 2, /// <summary> /// Operation has been canceled by the user - now go undo. /// </summary> PDOPS_CANCELLED = 3, /// <summary> /// Operation has been stopped by the user - terminate completely. /// </summary> PDOPS_STOPPED = 4, /// <summary> /// Operation has gone as far as it can go without throwing error dialogs. /// </summary> PDOPS_ERRORS = 5 } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")] public interface IShellItem { void BindToHandler(IntPtr pbc, [MarshalAs(UnmanagedType.LPStruct)]Guid bhid, [MarshalAs(UnmanagedType.LPStruct)]Guid riid, out IntPtr ppv); void GetParent(out IShellItem ppsi); void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName); void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs); void Compare(IShellItem psi, uint hint, out int piOrder); }; [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] public static extern void SHCreateItemFromParsingName([In][MarshalAs(UnmanagedType.LPWStr)] string pszPath, [In] IntPtr pbc, [In][MarshalAs(UnmanagedType.LPStruct)]Guid riid, [Out][MarshalAs(UnmanagedType.Interface, IidParameterIndex = 2)] out IShellItem ppv); public enum SIGDN : uint { NORMALDISPLAY = 0, PARENTRELATIVEPARSING = 0x80018001, PARENTRELATIVEFORADDRESSBAR = 0x8001c001, DESKTOPABSOLUTEPARSING = 0x80028000, PARENTRELATIVEEDITING = 0x80031001, DESKTOPABSOLUTEEDITING = 0x8004c000, FILESYSPATH = 0x80058000, URL = 0x80068000 } } [Serializable] internal class IOperationsProgressDialogException : Exception { public IOperationsProgressDialogException() { } public IOperationsProgressDialogException(string message) : base(message) { } public IOperationsProgressDialogException(string message, Exception innerException) : base(message, innerException) { } protected IOperationsProgressDialogException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Copyright (c) 2017 Jan Pluskal, Miroslav Slivka, Viliam Letavay // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Linq; using System.Text; using Netfox.Framework.Models.Enums; using Netfox.Framework.Models.PmLib; using Netfox.Framework.Models.PmLib.Frames; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Macs; using Org.BouncyCastle.Crypto.Parameters; namespace Netfox.Framework.ApplicationProtocolExport.PDUProviders { public class PDUDecrypter { public enum WriteKeySpec { Client, Server } // Version Minor public const Byte Ssl3 = 0; public const Byte Tls10 = 1; public const Byte Tls11 = 2; public const Byte Tls12 = 3; public Byte[] ClientDirection; public Byte[] ClientHMacKey; public Byte[] ClientRnd; public Byte[] ContinuationData; public Byte[] ServerHMacKey; public Byte[] ServerRnd; internal KeyDecrypter KeyDecrypter { get; set; } internal DataDecrypter DataDecrypter { get; set; } public void ChangeCipherSuite(Byte[] data, out ConversationCipherSuite cipherSuite) { try { var len = new Byte[2]; Array.Copy(data, 3, len, 0, 2); Array.Reverse(len); // 1 byte for type // 2 bytes tls/ssl version // 2 bytes PDU length var offset = 5; len = new Byte[4]; // only 3 bytes are used so offset is 1 Array.Copy(data, offset + 1, len, 1, 3); Array.Reverse(len); // Should be server hello message // 71-72 position of bytes in Server hello message that inform about ciphersuite len = new Byte[2]; Array.Copy(data, offset + 71, len, 0, 2); Array.Reverse(len); var cs = BitConverter.ToInt16(len, 0); cipherSuite = (ConversationCipherSuite) cs; } catch(IndexOutOfRangeException e) { PmConsolePrinter.PrintError("PDUDecrypter : Problem when parsing ServerHello : " + e.Message); cipherSuite = ConversationCipherSuite.TlsNullWithNullNull; } } public Boolean DoDecryption(Byte[] pdu, PmFrameBase frame, ref Byte[] decryptedBytes) { var source = frame.SrcAddress.GetAddressBytes(); var bytes = pdu; var hmac = new HMac(this.DataDecrypter.Digest); // get content type - protocol id var ct = new Byte[1]; Array.Copy(bytes, 0, ct, 0, 1); // get version - tls version next two bytes var version = new Byte[2]; Array.Copy(bytes, 1, version, 0, 2); // get data length var len = new Byte[2]; Array.Copy(bytes, 3, len, 0, 2); Array.Reverse(len); Int32 dataLen = BitConverter.ToInt16(len, 0); // get data var data = new Byte[dataLen]; // not whole data - continuation in next frame if(bytes.Length < dataLen + 5) { this.ContinuationData = new Byte[bytes.Length]; Array.Copy(bytes, this.ContinuationData, this.ContinuationData.Length); return false; } // more than enough data - new frame starts here if(bytes.Length > dataLen + 5) { this.ContinuationData = new Byte[bytes.Length - dataLen - 5]; Array.Copy(bytes, dataLen + 5, this.ContinuationData, 0, this.ContinuationData.Length); } Array.Copy(bytes, 5, data, 0, dataLen); /* decryption */ var sequenceNum = 0; Byte[] decrypted = null; try { switch(this.DataDecrypter.Mode) { case CipherMode.Cbc: decrypted = this.BlockDecryption(source, data, hmac, out sequenceNum); break; case CipherMode.Stream: decrypted = this.StreamDecryption(source, data, hmac, out sequenceNum); break; case CipherMode.Ccm: return false; case CipherMode.Gcm: decrypted = this.AeadDecryption(source, data); break; } } catch(InvalidCipherTextException e) { ("PDUDecryter : " + e.Message).PrintInfo(); return false; } /* check if decrypted data are correct */ /* GCM has no mac */ if(this.DataDecrypter.Mode == CipherMode.Gcm) return true; var msgLen = decrypted.Length; // strip padding - if CBC if(this.DataDecrypter.Mode == CipherMode.Cbc) { var pad = decrypted[decrypted.Length - 1]; msgLen -= pad + 1; } // strip mac msgLen -= this.DataDecrypter.Digest.GetDigestSize(); if(msgLen < 1) return false; var msg = new Byte[msgLen]; Array.Copy(decrypted, msg, msgLen); var recvDigest = new Byte[this.DataDecrypter.Digest.GetDigestSize()]; Array.Copy(decrypted, msgLen, recvDigest, 0, recvDigest.Length); var ignoreHmac = true; if(this.tls_hmac_check(sequenceNum, hmac, ct, version, msgLen, msg, recvDigest) || ignoreHmac) { Byte[] tmp = null; if(decryptedBytes != null) { tmp = new Byte[decryptedBytes.Length]; Array.Copy(decryptedBytes, tmp, tmp.Length); decryptedBytes = new Byte[tmp.Length + msg.Length]; Array.Copy(tmp, decryptedBytes, tmp.Length); Array.Copy(msg, 0, decryptedBytes, tmp.Length, msg.Length); } else { decryptedBytes = new Byte[msg.Length]; Array.Copy(msg, decryptedBytes, msg.Length); } return true; } // If bad decrypted decrease sequence number if(Enumerable.SequenceEqual(source, this.ClientDirection)) { this.DataDecrypter.DecreaseClientSeq(); } else { this.DataDecrypter.DecreaseServerSeq(); } return false; } public Byte[] Prf(Byte[] secret, String label, Byte[] rnd1, Byte[] rnd2, Int32 size, Byte version) { var ret = new Byte[size]; var bLabel = Encoding.ASCII.GetBytes(label); var seed = new Byte[bLabel.Length + rnd1.Length + rnd2.Length]; Array.Copy(bLabel, 0, seed, 0, bLabel.Length); Array.Copy(rnd1, 0, seed, bLabel.Length, rnd1.Length); Array.Copy(rnd2, 0, seed, bLabel.Length + rnd1.Length, rnd2.Length); switch(version) { case Ssl3: // TODO throw new NotImplementedException(); case Tls10: case Tls11: /* PRF is result of mixing two hashes */ var s1 = new Byte[(Int32) Math.Ceiling(secret.Length / 2.0)]; Array.Copy(secret, s1, s1.Length); var s2 = new Byte[s1.Length]; Array.Copy(secret, secret.Length - s2.Length, s2, 0, s2.Length); var md5Hash = new Byte[ret.Length]; var sha1Hash = new Byte[ret.Length]; md5Hash = this.P_hash(s1, seed, size, new MD5Digest()); sha1Hash = this.P_hash(s2, seed, size, new Sha1Digest()); for(var i = 0; i < size; i++) ret[i] = (Byte) (md5Hash[i]^sha1Hash[i]); break; case Tls12: /* All Cipher suites defined in TLS 1.2 RFC * uses sha256 in this function */ ret = this.P_hash(secret, seed, size, new Sha256Digest()); break; } return ret; } private Byte[] AeadDecryption(Byte[] source, Byte[] data) { Byte[] decrypted; var exNonce = new Byte[8]; var content = new Byte[data.Length - 8]; Array.Copy(data, 0, exNonce, 0, 8); Array.Copy(data, 8, content, 0, content.Length); if(source.SequenceEqual(this.ClientDirection)) { this.DataDecrypter.SetGcmParameters(exNonce, WriteKeySpec.Client); var d = this.DataDecrypter.DecryptData(content, WriteKeySpec.Client); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); } else { this.DataDecrypter.SetGcmParameters(exNonce, WriteKeySpec.Server); var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Server); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); } return decrypted; } private Byte[] BlockDecryption(Byte[] source, Byte[] data, HMac hmac, out Int32 sequenceNum) { // RFC 5246 in tls 1.2 ciphertext consits of // iv, ciphered_content { content, mac, padding, padding_length } // the IV length is of length // record_iv_length, which is equal to the // block_size. var content = new Byte[data.Length - this.DataDecrypter.IvLength]; var iv = new Byte[this.DataDecrypter.IvLength]; Array.Copy(data, 0, iv, 0, this.DataDecrypter.IvLength); Array.Copy(data, this.DataDecrypter.IvLength, content, 0, content.Length); Byte[] decrypted; if(source.SequenceEqual(this.ClientDirection)) { this.DataDecrypter.SetIv(iv, WriteKeySpec.Client); var d = this.DataDecrypter.DecryptData(content, WriteKeySpec.Client); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); var key = new KeyParameter(this.ClientHMacKey); hmac.Init(key); sequenceNum = this.DataDecrypter.ClientSeq; } else { this.DataDecrypter.SetIv(iv, WriteKeySpec.Server); var d = this.DataDecrypter.DecryptData(content, WriteKeySpec.Server); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); var key = new KeyParameter(this.ServerHMacKey); hmac.Init(key); sequenceNum = this.DataDecrypter.ServerSeq; } return decrypted; } private Byte[] P_hash(Byte[] secret, Byte[] seed, Int32 size, IDigest digest) { var needed = size; var md = new HMac(digest); var key = new KeyParameter(secret); md.Init(key); // A_0 is initialized with seed var a0 = new Byte[seed.Length]; Array.Copy(seed, 0, a0, 0, a0.Length); // A_i is HMAC of previous A var aI = new Byte[md.GetMacSize()]; md.BlockUpdate(a0, 0, a0.Length); md.DoFinal(aI, 0); md.Reset(); var ret = new Byte[needed]; var outBuff = new Byte[md.GetMacSize()]; while(needed > 0) { md.Init(key); // Add to return value md.BlockUpdate(aI, 0, aI.Length); md.BlockUpdate(seed, 0, seed.Length); md.DoFinal(outBuff, 0); md.Reset(); var lenToCopy = needed < md.GetMacSize()? needed : md.GetMacSize(); Array.Copy(outBuff, 0, ret, size - needed, lenToCopy); // Update new A md.Init(key); md.BlockUpdate(aI, 0, aI.Length); md.DoFinal(aI, 0); md.Reset(); // Update needed field needed -= md.GetMacSize(); } return ret; } private Byte[] StreamDecryption(Byte[] source, Byte[] data, HMac hmac, out Int32 sequenceNum) { // ciphered text consist of data and mac Byte[] decrypted; if(source.SequenceEqual(this.ClientDirection)) { var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Client); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); var key = new KeyParameter(this.ClientHMacKey); hmac.Init(key); sequenceNum = this.DataDecrypter.ClientSeq; } else { var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Server); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); var key = new KeyParameter(this.ServerHMacKey); hmac.Init(key); sequenceNum = this.DataDecrypter.ServerSeq; } return decrypted; } private Boolean tls_hmac_check(Int32 sequenceNum, HMac hmac, Byte[] ct, Byte[] version, Int32 msgLen, Byte[] msg, Byte[] recvDigest) { var seq = BitConverter.GetBytes(sequenceNum); var exSeq = new Byte[8]; if(BitConverter.IsLittleEndian) { Array.Reverse(seq); } Array.Copy(seq, 0, exSeq, 4, 4); hmac.BlockUpdate(exSeq, 0, 8); // hash content type hmac.BlockUpdate(ct, 0, 1); // hash version //Array.Reverse(version); hmac.BlockUpdate(version, 0, version.Length); // hash data length var dl = BitConverter.GetBytes(msgLen); var dataLength = new Byte[2]; Array.Copy(dl, 0, dataLength, 0, 2); if(BitConverter.IsLittleEndian) { Array.Reverse(dataLength); } hmac.BlockUpdate(dataLength, 0, 2); // hash data //Array.Reverse(msg); hmac.BlockUpdate(msg, 0, msgLen); // final digest var digest = new Byte[hmac.GetMacSize()]; hmac.DoFinal(digest, 0); return digest.SequenceEqual(recvDigest); } } }
using System; using System.Collections.Generic; using LynnaLib; namespace LynnaLab { public class ValueReferenceEditor : Gtk.Alignment { ValueReferenceGroup valueReferenceGroup; IList<int> maxBounds; // List of "grid" objects corresponding to each widget IList<Gtk.Grid> widgetGrids; // X/Y positions where the widgets are in the grid IList<Tuple<int,int>> widgetPositions; // The widgets by index. IList<IList<Gtk.Widget>> widgetLists; event System.Action dataModifiedExternalEvent; event System.Action dataModifiedInternalEvent; Project Project {get; set;} public ValueReferenceGroup ValueReferenceGroup { get { return valueReferenceGroup; } } public ValueReferenceEditor(Project p, ValueReferenceGroup vrg, string frameText=null) : this(p, vrg, 50, frameText) { } public ValueReferenceEditor(Project p, ValueReferenceGroup vrg, int rows, string frameText=null) : base(1.0F,1.0F,1.0F,1.0F) { Project = p; valueReferenceGroup = vrg; maxBounds = new int[valueReferenceGroup.GetNumValueReferences()]; widgetGrids = new List<Gtk.Grid>(); widgetPositions = new Tuple<int,int>[maxBounds.Count]; widgetLists = new List<IList<Gtk.Widget>>(); Gtk.Box hbox = new Gtk.HBox(); hbox.Spacing = 6; Func<Gtk.Grid> newGrid = () => { Gtk.Grid g = new Gtk.Grid(); g.ColumnSpacing = 6; g.RowSpacing = 2; hbox.Add(g); return g; }; Gtk.Grid grid = newGrid(); int x=0,y=0; // Do not use "foreach" here. The "valueReferenceGroup" may be changed. So, whenever we // access a ValueReference from within an event handler, we must do so though the // "valueReferenceGroup" class variable, and NOT though an alias (like with foreach). for (int tmpCounter=0; tmpCounter < valueReferenceGroup.Count; tmpCounter++) { int i = tmpCounter; // Variable must be distinct within each closure if (y >= rows) { y = 0; x = 0; grid = newGrid(); } // Each ValueReference may use up to 3 widgets in the grid row Gtk.Widget[] widgetList = new Gtk.Widget[3]; widgetPositions[i] = new Tuple<int,int>(x,y); Action<Gtk.SpinButton> setSpinButtonLimits = (spinButton) => { if (valueReferenceGroup[i].MaxValue < 0x10) spinButton.Digits = 1; else if (valueReferenceGroup[i].MaxValue < 0x100) spinButton.Digits = 2; else if (valueReferenceGroup[i].MaxValue < 0x1000) spinButton.Digits = 3; else spinButton.Digits = 4; spinButton.Adjustment.Lower = valueReferenceGroup[i].MinValue; spinButton.Adjustment.Upper = valueReferenceGroup[i].MaxValue; }; int entryWidgetWidth = 1; // If it has a ConstantsMapping, use a combobox instead of anything else if (valueReferenceGroup[i].ConstantsMapping != null) { ComboBoxFromConstants comboBox = new ComboBoxFromConstants(showHelp:true, vertical:true); comboBox.SetConstantsMapping(valueReferenceGroup[i].ConstantsMapping); // Must put this before the "Changed" handler below to avoid // it being fired (for some reason?) setSpinButtonLimits(comboBox.SpinButton); comboBox.Changed += delegate(object sender, EventArgs e) { valueReferenceGroup[i].SetValue(comboBox.ActiveValue); OnDataModifiedInternal(); }; dataModifiedExternalEvent += delegate() { comboBox.ActiveValue = valueReferenceGroup[i].GetIntValue (); }; /* comboBox.MarginTop = 4; comboBox.MarginBottom = 4; */ widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); widgetList[1] = comboBox; entryWidgetWidth = 2; goto loopEnd; } // ConstantsMapping == null switch(valueReferenceGroup[i].ValueType) { case ValueReferenceType.String: { widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); Gtk.Entry entry = new Gtk.Entry(); if (!valueReferenceGroup[i].Editable) entry.Sensitive = false; dataModifiedExternalEvent += delegate() { entry.Text = valueReferenceGroup[i].GetStringValue(); OnDataModifiedInternal(); }; widgetList[1] = entry; break; } case ValueReferenceType.Int: { widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); SpinButtonHexadecimal spinButton = new SpinButtonHexadecimal(valueReferenceGroup[i].MinValue, valueReferenceGroup[i].MaxValue); if (!valueReferenceGroup[i].Editable) spinButton.Sensitive = false; setSpinButtonLimits(spinButton); spinButton.ValueChanged += delegate(object sender, EventArgs e) { Gtk.SpinButton button = sender as Gtk.SpinButton; if (maxBounds[i] == 0 || button.ValueAsInt <= maxBounds[i]) { valueReferenceGroup[i].SetValue(button.ValueAsInt); } else button.Value = maxBounds[i]; OnDataModifiedInternal(); }; dataModifiedExternalEvent += delegate() { spinButton.Value = valueReferenceGroup[i].GetIntValue(); }; widgetList[1] = spinButton; } break; case ValueReferenceType.Bool: { widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); Gtk.CheckButton checkButton = new Gtk.CheckButton(); checkButton.FocusOnClick = false; if (!valueReferenceGroup[i].Editable) checkButton.Sensitive = false; checkButton.Toggled += delegate(object sender, EventArgs e) { Gtk.CheckButton button = sender as Gtk.CheckButton; valueReferenceGroup[i].SetValue(button.Active ? 1 : 0); OnDataModifiedInternal(); }; dataModifiedExternalEvent += delegate() { checkButton.Active = valueReferenceGroup[i].GetIntValue() == 1; }; widgetList[1] = checkButton; } break; } loopEnd: grid.Attach(widgetList[0], x, y, 1, 1); grid.Attach(widgetList[1], x+1, y, entryWidgetWidth, 1); widgetList[2] = new Gtk.Alignment(0, 0.5f, 0, 0); // Container for help button widgetList[2].Hexpand = true; // Let this absorb any extra space grid.Attach(widgetList[2], x+2, y, 1, 1); widgetGrids.Add(grid); widgetLists.Add(widgetList); if (valueReferenceGroup[i].Tooltip != null) { SetTooltip(i, valueReferenceGroup[i].Tooltip); } y++; } if (frameText != null) { var frame = new Gtk.Frame(frameText); frame.Add(hbox); this.Add(frame); } else this.Add(hbox); this.ShowAll(); // Initial values if (dataModifiedExternalEvent != null) dataModifiedExternalEvent(); UpdateHelpButtons(); AddModifiedHandlers(); this.Destroyed += (sender, args) => RemoveModifiedHandlers(); } void AddModifiedHandlers() { foreach (ValueReference vref in valueReferenceGroup.GetValueReferences()) { vref.AddValueModifiedHandler(OnDataModifiedExternal); } } void RemoveModifiedHandlers() { foreach (ValueReference vref in valueReferenceGroup.GetValueReferences()) { vref.RemoveValueModifiedHandler(OnDataModifiedExternal); } } // ONLY call this function if the new ValueReferenceGroup matches the exact structure of the // old one. If there is any mismatch, a new ValueReferenceEditor should be created instead. // But when the structures do match exactly, this is preferred, so that we don't need to // recreate all of the necessary widgets again. public void ReplaceValueReferenceGroup(ValueReferenceGroup vrg) { RemoveModifiedHandlers(); this.valueReferenceGroup = vrg; AddModifiedHandlers(); // Even if we're not rebuilding the widgets we can at least check for minor changes like // to the "editable" variable for (int i=0; i<ValueReferenceGroup.Count; i++) { Gtk.Widget w = widgetLists[i][1]; w.Sensitive = ValueReferenceGroup[i].Editable; SetTooltip(i, ValueReferenceGroup[i].Tooltip); } // Initial values if (dataModifiedExternalEvent != null) dataModifiedExternalEvent(); UpdateHelpButtons(); } public void SetMaxBound(int i, int max) { if (i == -1) return; maxBounds[i] = max; } // Substitute the widget for a value (index "i") with the new widget. (Currently unused) public void ReplaceWidget(string name, Gtk.Widget newWidget) { int i = GetValueIndex(name); widgetLists[i][1].Dispose(); var pos = widgetPositions[i]; widgetGrids[i].Attach(newWidget, pos.Item1+1, pos.Item2, 1, 1); widgetLists[i][1] = newWidget; } // Can replace the help button widget with something else. However if you put a container // there it could get overwritten with a help button again. public void AddWidgetToRight(string name, Gtk.Widget widget) { int i = GetValueIndex(name); widgetLists[i][2].Dispose(); // Removes help button widgetLists[i][2] = widget; var pos = widgetPositions[i]; widgetGrids[i].Attach(widget, pos.Item1+2, pos.Item2, 1, 1); } int GetValueIndex(string name) { for (int i = 0; i < valueReferenceGroup.Count; i++) { if (valueReferenceGroup[i].Name == name) return i; } throw new ArgumentException("Couldn't find '" + name + "' in ValueReferenceGroup."); } public void SetTooltip(int i, string tooltip) { for (int j=0; j<widgetLists[i].Count; j++) widgetLists[i][j].TooltipText = tooltip; } public void SetTooltip(ValueReference r, string tooltip) { SetTooltip(valueReferenceGroup.GetIndexOf(r), tooltip); } public void SetTooltip(string name, string tooltip) { SetTooltip(valueReferenceGroup.GetValueReference(name), tooltip); } public void AddDataModifiedHandler(System.Action handler) { dataModifiedInternalEvent += handler; } public void RemoveDataModifiedHandler(System.Action handler) { dataModifiedInternalEvent -= handler; } // Data modified externally void OnDataModifiedExternal(object sender, ValueModifiedEventArgs e) { if (dataModifiedExternalEvent != null) dataModifiedExternalEvent(); } // Data modified internally void OnDataModifiedInternal() { if (dataModifiedInternalEvent != null) dataModifiedInternalEvent(); } // Check if there are entries that should have help buttons public void UpdateHelpButtons() { IList<ValueReference> refs = valueReferenceGroup.GetValueReferences(); for (int i=0; i<refs.Count; i++) { if (widgetLists[i][1] is ComboBoxFromConstants) // These deal with documentation themselves continue; Gtk.Container container = widgetLists[i][2] as Gtk.Container; if (container == null) continue; bool isHelpButton = true; // Remove previous help button foreach (Gtk.Widget widget in container.Children) { // Really hacky way to check whether this is the help button as we expect, or // whether the "AddWidgetToRight" function was called to replace it, in which // case we don't try to add the help button at all if (!(widget is Gtk.Button && (widget as Gtk.Button).Label == "?")) { isHelpButton = false; continue; } container.Remove(widget); widget.Dispose(); } if (!isHelpButton) continue; ValueReference r = refs[i]; if (r.Documentation != null) { Gtk.Button helpButton = new Gtk.Button("?"); helpButton.FocusOnClick = false; helpButton.Clicked += delegate(object sender, EventArgs e) { DocumentationDialog d = new DocumentationDialog(r.Documentation); }; container.Add(helpButton); } } this.ShowAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE4.2 hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public abstract class Sse42 : Sse41 { internal Sse42() { } public new static bool IsSupported { get => IsSupported; } /// <summary> /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareImplicitLength(Vector128<sbyte> left, Vector128<sbyte> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); /// <summary> /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareImplicitLength(Vector128<byte> left, Vector128<byte> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); /// <summary> /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareImplicitLength(Vector128<short> left, Vector128<short> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); /// <summary> /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareImplicitLength(Vector128<ushort> left, Vector128<ushort> right, ResultsFlag flag, StringComparisonMode mode) => CompareImplicitLength(left, right, flag, mode); /// <summary> /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareExplicitLength(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); /// <summary> /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareExplicitLength(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); /// <summary> /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareExplicitLength(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); /// <summary> /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static bool CompareExplicitLength(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) => CompareExplicitLength(left, leftLength, right, rightLength, flag, mode); /// <summary> /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareImplicitLengthIndex(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); /// <summary> /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareImplicitLengthIndex(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); /// <summary> /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareImplicitLengthIndex(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); /// <summary> /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8) /// PCMPISTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareImplicitLengthIndex(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) => CompareImplicitLengthIndex(left, right, mode); /// <summary> /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareExplicitLengthIndex(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); /// <summary> /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareExplicitLengthIndex(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); /// <summary> /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareExplicitLengthIndex(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); /// <summary> /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRI xmm, xmm/m128, imm8 /// </summary> public static int CompareExplicitLengthIndex(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthIndex(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) => CompareImplicitLengthBitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8) /// PCMPISTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) => CompareImplicitLengthUnitMask(left, right, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthBitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8) /// PCMPESTRM xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) => CompareExplicitLengthUnitMask(left, leftLength, right, rightLength, mode); /// <summary> /// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b) /// PCMPGTQ xmm, xmm/m128 /// </summary> public static Vector128<long> CompareGreaterThan(Vector128<long> left, Vector128<long> right) => CompareGreaterThan(left, right); /// <summary> /// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v) /// CRC32 reg, reg/m8 /// </summary> public static uint Crc32(uint crc, byte data) => Crc32(crc, data); /// <summary> /// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v) /// CRC32 reg, reg/m16 /// </summary> public static uint Crc32(uint crc, ushort data) => Crc32(crc, data); /// <summary> /// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v) /// CRC32 reg, reg/m32 /// </summary> public static uint Crc32(uint crc, uint data) => Crc32(crc, data); /// <summary> /// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v) /// CRC32 reg, reg/m64 /// </summary> public static ulong Crc32(ulong crc, ulong data) => Crc32(crc, data); } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2019 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq.Test { using System; using NUnit.Framework; using Reactive; [TestFixture] public class SubjectTest { static IDisposable Subscribe<T>(IObservable<T> subject, Action<T> onNext = null, Action<Exception> onError = null, Action onCompleted = null) => subject.Subscribe(onNext ?? BreakingAction.Of<T>(), onError ?? BreakingAction.Of<Exception>(), onCompleted ?? BreakingAction.WithoutArguments); [Test] public void SubscribeWithNullObserverThrows() { var subject = new Subject<int>(); var e = Assert.Throws<ArgumentNullException>(() => subject.Subscribe(null)); Assert.That(e.ParamName, Is.EqualTo("observer")); } [Test] public void OnNextObservations() { var a = 0; var b = 0; var subject = new Subject<int>(); Subscribe(subject, x => a = x); Subscribe(subject, x => b = x); subject.OnNext(42); Assert.That(a, Is.EqualTo(42)); Assert.That(b, Is.EqualTo(42)); } [Test] public void OnErrorObservations() { Exception error1 = null; Exception error2 = null; var subject = new Subject<int>(); Subscribe(subject, onError: e => error1 = e); Subscribe(subject, onError: e => error2 = e); var error = new TestException(); subject.OnError(error); Assert.That(error1, Is.SameAs(error)); Assert.That(error2, Is.SameAs(error)); } [Test] public void OnCompletedObservations() { var completed1 = false; var completed2 = false; var subject = new Subject<int>(); Subscribe(subject, onCompleted: () => completed1 = true); Subscribe(subject, onCompleted: () => completed2 = true); subject.OnCompleted(); Assert.That(completed1, Is.True); Assert.That(completed2, Is.True); } [Test] public void SubscriptionDisposal() { var a = 0; var b = 0; var subject = new Subject<int>(); Subscribe(subject).Dispose(); Subscribe(subject, x => a = x); Subscribe(subject).Dispose(); Subscribe(subject, x => b = x); Subscribe(subject).Dispose(); subject.OnNext(42); Assert.That(a, Is.EqualTo(42)); Assert.That(b, Is.EqualTo(42)); } [Test] public void SubscriptionReDisposalIsHarmless() { var subject = new Subject<int>(); var subscription = Subscribe(subject); subscription.Dispose(); subscription.Dispose(); subject.OnNext(42); } [Test] public void SubscriptionPostCompletion() { var completed = false; var subject = new Subject<int>(); subject.OnCompleted(); Subscribe(subject, onCompleted: () => completed = true); Assert.That(completed, Is.True); } [Test] public void SubscriptionPostError() { Exception observedError = null; var subject = new Subject<int>(); var error = new TestException(); subject.OnError(error); Subscribe(subject, onError: e => observedError = e); Assert.That(observedError, Is.SameAs(error)); } [Test] public void OnNextMutedWhenCompleted() { var subject = new Subject<int>(); Subscribe(subject, onCompleted: delegate { }); subject.OnCompleted(); subject.OnNext(42); } [Test] public void OnErrorMutedWhenCompleted() { var subject = new Subject<int>(); Subscribe(subject, onCompleted: delegate { }); subject.OnCompleted(); subject.OnError(new TestException()); } [Test] public void OnNextMutedWhenErrored() { var subject = new Subject<int>(); Subscribe(subject, onError: delegate { }); subject.OnError(new TestException()); subject.OnNext(42); } [Test] public void OnCompleteMutedWhenErrored() { var subject = new Subject<int>(); Subscribe(subject, onError: delegate { }); subject.OnError(new TestException()); subject.OnCompleted(); } [Test] public void CompletesOnce() { var count = 0; var subject = new Subject<int>(); Subscribe(subject, onCompleted: () => count++); subject.OnCompleted(); subject.OnCompleted(); Assert.That(count, Is.EqualTo(1)); } [Test] public void ErrorsOnce() { var count = 0; var subject = new Subject<int>(); Subscribe(subject, onError: _ => count++); subject.OnError(new TestException()); subject.OnError(new TestException()); Assert.That(count, Is.EqualTo(1)); } [Test] public void SafeToDisposeDuringOnNext() { var subject = new Subject<int>(); IDisposable subscription = null; var action = new Action(() => subscription.Dispose()); subscription = subject.Subscribe(_ => action()); subject.OnNext(42); action = BreakingAction.WithoutArguments; subject.OnNext(42); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// ChunkedUploadResponse /// </summary> [DataContract] public partial class ChunkedUploadResponse : IEquatable<ChunkedUploadResponse>, IValidatableObject { public ChunkedUploadResponse() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="ChunkedUploadResponse" /> class. /// </summary> /// <param name="Checksum">Checksum.</param> /// <param name="ChunkedUploadId">ChunkedUploadId.</param> /// <param name="ChunkedUploadParts">ChunkedUploadParts.</param> /// <param name="ChunkedUploadUri">ChunkedUploadUri.</param> /// <param name="Committed">Committed.</param> /// <param name="ExpirationDateTime">ExpirationDateTime.</param> /// <param name="MaxChunkedUploadParts">MaxChunkedUploadParts.</param> /// <param name="MaxTotalSize">MaxTotalSize.</param> /// <param name="TotalSize">TotalSize.</param> public ChunkedUploadResponse(string Checksum = default(string), string ChunkedUploadId = default(string), List<ChunkedUploadPart> ChunkedUploadParts = default(List<ChunkedUploadPart>), string ChunkedUploadUri = default(string), string Committed = default(string), string ExpirationDateTime = default(string), string MaxChunkedUploadParts = default(string), string MaxTotalSize = default(string), string TotalSize = default(string)) { this.Checksum = Checksum; this.ChunkedUploadId = ChunkedUploadId; this.ChunkedUploadParts = ChunkedUploadParts; this.ChunkedUploadUri = ChunkedUploadUri; this.Committed = Committed; this.ExpirationDateTime = ExpirationDateTime; this.MaxChunkedUploadParts = MaxChunkedUploadParts; this.MaxTotalSize = MaxTotalSize; this.TotalSize = TotalSize; } /// <summary> /// Gets or Sets Checksum /// </summary> [DataMember(Name="checksum", EmitDefaultValue=false)] public string Checksum { get; set; } /// <summary> /// Gets or Sets ChunkedUploadId /// </summary> [DataMember(Name="chunkedUploadId", EmitDefaultValue=false)] public string ChunkedUploadId { get; set; } /// <summary> /// Gets or Sets ChunkedUploadParts /// </summary> [DataMember(Name="chunkedUploadParts", EmitDefaultValue=false)] public List<ChunkedUploadPart> ChunkedUploadParts { get; set; } /// <summary> /// Gets or Sets ChunkedUploadUri /// </summary> [DataMember(Name="chunkedUploadUri", EmitDefaultValue=false)] public string ChunkedUploadUri { get; set; } /// <summary> /// Gets or Sets Committed /// </summary> [DataMember(Name="committed", EmitDefaultValue=false)] public string Committed { get; set; } /// <summary> /// Gets or Sets ExpirationDateTime /// </summary> [DataMember(Name="expirationDateTime", EmitDefaultValue=false)] public string ExpirationDateTime { get; set; } /// <summary> /// Gets or Sets MaxChunkedUploadParts /// </summary> [DataMember(Name="maxChunkedUploadParts", EmitDefaultValue=false)] public string MaxChunkedUploadParts { get; set; } /// <summary> /// Gets or Sets MaxTotalSize /// </summary> [DataMember(Name="maxTotalSize", EmitDefaultValue=false)] public string MaxTotalSize { get; set; } /// <summary> /// Gets or Sets TotalSize /// </summary> [DataMember(Name="totalSize", EmitDefaultValue=false)] public string TotalSize { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ChunkedUploadResponse {\n"); sb.Append(" Checksum: ").Append(Checksum).Append("\n"); sb.Append(" ChunkedUploadId: ").Append(ChunkedUploadId).Append("\n"); sb.Append(" ChunkedUploadParts: ").Append(ChunkedUploadParts).Append("\n"); sb.Append(" ChunkedUploadUri: ").Append(ChunkedUploadUri).Append("\n"); sb.Append(" Committed: ").Append(Committed).Append("\n"); sb.Append(" ExpirationDateTime: ").Append(ExpirationDateTime).Append("\n"); sb.Append(" MaxChunkedUploadParts: ").Append(MaxChunkedUploadParts).Append("\n"); sb.Append(" MaxTotalSize: ").Append(MaxTotalSize).Append("\n"); sb.Append(" TotalSize: ").Append(TotalSize).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ChunkedUploadResponse); } /// <summary> /// Returns true if ChunkedUploadResponse instances are equal /// </summary> /// <param name="other">Instance of ChunkedUploadResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(ChunkedUploadResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Checksum == other.Checksum || this.Checksum != null && this.Checksum.Equals(other.Checksum) ) && ( this.ChunkedUploadId == other.ChunkedUploadId || this.ChunkedUploadId != null && this.ChunkedUploadId.Equals(other.ChunkedUploadId) ) && ( this.ChunkedUploadParts == other.ChunkedUploadParts || this.ChunkedUploadParts != null && this.ChunkedUploadParts.SequenceEqual(other.ChunkedUploadParts) ) && ( this.ChunkedUploadUri == other.ChunkedUploadUri || this.ChunkedUploadUri != null && this.ChunkedUploadUri.Equals(other.ChunkedUploadUri) ) && ( this.Committed == other.Committed || this.Committed != null && this.Committed.Equals(other.Committed) ) && ( this.ExpirationDateTime == other.ExpirationDateTime || this.ExpirationDateTime != null && this.ExpirationDateTime.Equals(other.ExpirationDateTime) ) && ( this.MaxChunkedUploadParts == other.MaxChunkedUploadParts || this.MaxChunkedUploadParts != null && this.MaxChunkedUploadParts.Equals(other.MaxChunkedUploadParts) ) && ( this.MaxTotalSize == other.MaxTotalSize || this.MaxTotalSize != null && this.MaxTotalSize.Equals(other.MaxTotalSize) ) && ( this.TotalSize == other.TotalSize || this.TotalSize != null && this.TotalSize.Equals(other.TotalSize) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Checksum != null) hash = hash * 59 + this.Checksum.GetHashCode(); if (this.ChunkedUploadId != null) hash = hash * 59 + this.ChunkedUploadId.GetHashCode(); if (this.ChunkedUploadParts != null) hash = hash * 59 + this.ChunkedUploadParts.GetHashCode(); if (this.ChunkedUploadUri != null) hash = hash * 59 + this.ChunkedUploadUri.GetHashCode(); if (this.Committed != null) hash = hash * 59 + this.Committed.GetHashCode(); if (this.ExpirationDateTime != null) hash = hash * 59 + this.ExpirationDateTime.GetHashCode(); if (this.MaxChunkedUploadParts != null) hash = hash * 59 + this.MaxChunkedUploadParts.GetHashCode(); if (this.MaxTotalSize != null) hash = hash * 59 + this.MaxTotalSize.GetHashCode(); if (this.TotalSize != null) hash = hash * 59 + this.TotalSize.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
/** * LookupService.cs * * Copyright (C) 2008 MaxMind Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.IO; using System.Net; using System.Runtime.CompilerServices; public class LookupService{ private FileStream file = null; private DatabaseInfo databaseInfo = null; byte databaseType = Convert.ToByte(DatabaseInfo.COUNTRY_EDITION); int[] databaseSegments; int recordLength; int dboptions; byte[] dbbuffer; //String licenseKey; //int dnsService = 0; private static Country UNKNOWN_COUNTRY = new Country("--", "N/A"); private static int COUNTRY_BEGIN = 16776960; //private static int STATE_BEGIN = 16700000; private static int STRUCTURE_INFO_MAX_SIZE = 20; private static int DATABASE_INFO_MAX_SIZE = 100; private static int FULL_RECORD_LENGTH = 100;//??? private static int SEGMENT_RECORD_LENGTH = 3; private static int STANDARD_RECORD_LENGTH = 3; private static int ORG_RECORD_LENGTH = 4; private static int MAX_RECORD_LENGTH = 4; private static int MAX_ORG_RECORD_LENGTH = 1000;//??? private static int FIPS_RANGE = 360; private static int STATE_BEGIN_REV0 = 16700000; private static int STATE_BEGIN_REV1 = 16000000; private static int US_OFFSET = 1; private static int CANADA_OFFSET = 677; private static int WORLD_OFFSET = 1353; public static int GEOIP_STANDARD = 0; public static int GEOIP_MEMORY_CACHE = 1; public static int GEOIP_UNKNOWN_SPEED = 0; public static int GEOIP_DIALUP_SPEED = 1; public static int GEOIP_CABLEDSL_SPEED = 2; public static int GEOIP_CORPORATE_SPEED = 3; private static String[] countryCode = { "--","AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR", "AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ", "BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF", "CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ", "DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI", "FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL", "GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR", "HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP", "KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC", "LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK", "ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY", "MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM", "PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY", "QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ", "SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG", "TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG", "UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE", "YT","RS","ZA","ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE","BL", "MF"}; private static String[] countryName = { "N/A","Asia/Pacific Region","Europe","Andorra","United Arab Emirates", "Afghanistan","Antigua and Barbuda","Anguilla","Albania","Armenia", "Netherlands Antilles","Angola","Antarctica","Argentina","American Samoa", "Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina", "Barbados","Bangladesh","Belgium","Burkina Faso","Bulgaria","Bahrain", "Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas", "Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada", "Cocos (Keeling) Islands","Congo, The Democratic Republic of the", "Central African Republic","Congo","Switzerland","Cote D'Ivoire", "Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba", "Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany", "Djibouti","Denmark","Dominica","Dominican Republic","Algeria","Ecuador", "Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland", "Fiji","Falkland Islands (Malvinas)","Micronesia, Federated States of", "Faroe Islands","France","France, Metropolitan","Gabon","United Kingdom", "Grenada","Georgia","French Guiana","Ghana","Gibraltar","Greenland","Gambia", "Guinea","Guadeloupe","Equatorial Guinea","Greece", "South Georgia and the South Sandwich Islands","Guatemala","Guam", "Guinea-Bissau","Guyana","Hong Kong","Heard Island and McDonald Islands", "Honduras","Croatia","Haiti","Hungary","Indonesia","Ireland","Israel","India", "British Indian Ocean Territory","Iraq","Iran, Islamic Republic of", "Iceland","Italy","Jamaica","Jordan","Japan","Kenya","Kyrgyzstan","Cambodia", "Kiribati","Comoros","Saint Kitts and Nevis", "Korea, Democratic People's Republic of","Korea, Republic of","Kuwait", "Cayman Islands","Kazakhstan","Lao People's Democratic Republic","Lebanon", "Saint Lucia","Liechtenstein","Sri Lanka","Liberia","Lesotho","Lithuania", "Luxembourg","Latvia","Libyan Arab Jamahiriya","Morocco","Monaco", "Moldova, Republic of","Madagascar","Marshall Islands", "Macedonia, the Former Yugoslav Republic of","Mali","Myanmar","Mongolia", "Macau","Northern Mariana Islands","Martinique","Mauritania","Montserrat", "Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique", "Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua", "Netherlands","Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama", "Peru","French Polynesia","Papua New Guinea","Philippines","Pakistan", "Poland","Saint Pierre and Miquelon","Pitcairn","Puerto Rico","" + "Palestinian Territory, Occupied","Portugal","Palau","Paraguay","Qatar", "Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia", "Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena", "Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino", "Senegal","Somalia","Suriname","Sao Tome and Principe","El Salvador", "Syrian Arab Republic","Swaziland","Turks and Caicos Islands","Chad", "French Southern Territories","Togo","Thailand","Tajikistan","Tokelau", "Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey","Trinidad and Tobago", "Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda", "United States Minor Outlying Islands","United States","Uruguay","Uzbekistan", "Holy See (Vatican City State)","Saint Vincent and the Grenadines", "Venezuela","Virgin Islands, British","Virgin Islands, U.S.","Vietnam", "Vanuatu","Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia", "South Africa","Zambia","Montenegro","Zimbabwe","Anonymous Proxy", "Satellite Provider","Other", "Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy", "Saint Martin"}; public LookupService(String databaseFile, int options){ try { this.file = new FileStream(databaseFile, FileMode.Open, FileAccess.Read); dboptions = options; init(); } catch(System.SystemException) { Console.Write("cannot open file " + databaseFile + "\n"); } } public LookupService(String databaseFile):this(databaseFile, GEOIP_STANDARD){ } private void init(){ int i, j; byte [] delim = new byte[3]; byte [] buf = new byte[SEGMENT_RECORD_LENGTH]; databaseType = (byte)DatabaseInfo.COUNTRY_EDITION; recordLength = STANDARD_RECORD_LENGTH; //file.Seek(file.Length() - 3,SeekOrigin.Begin); file.Seek(-3,SeekOrigin.End); for (i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) { file.Read(delim,0,3); if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255){ databaseType = Convert.ToByte(file.ReadByte()); if (databaseType >= 106) { // Backward compatibility with databases from April 2003 and earlier databaseType -= 105; } // Determine the database type. if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV0; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { databaseSegments = new int[1]; databaseSegments[0] = STATE_BEGIN_REV1; recordLength = STANDARD_RECORD_LENGTH; } else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1 || databaseType == DatabaseInfo.ORG_EDITION || databaseType == DatabaseInfo.ISP_EDITION || databaseType == DatabaseInfo.ASNUM_EDITION) { databaseSegments = new int[1]; databaseSegments[0] = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV0 || databaseType == DatabaseInfo.CITY_EDITION_REV1) { recordLength = STANDARD_RECORD_LENGTH; } else { recordLength = ORG_RECORD_LENGTH; } file.Read(buf,0,SEGMENT_RECORD_LENGTH); for (j = 0; j < SEGMENT_RECORD_LENGTH; j++) { databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8)); } } break; } else { //file.Seek(file.getFilePointer() - 4); file.Seek(-4,SeekOrigin.Current); //file.Seek(file.position-4,SeekOrigin.Begin); } } if ((databaseType == DatabaseInfo.COUNTRY_EDITION) | (databaseType == DatabaseInfo.PROXY_EDITION) | (databaseType == DatabaseInfo.NETSPEED_EDITION)) { databaseSegments = new int[1]; databaseSegments[0] = COUNTRY_BEGIN; recordLength = STANDARD_RECORD_LENGTH; } if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { int l = (int) file.Length; dbbuffer = new byte[l]; file.Seek(0,SeekOrigin.Begin); file.Read(dbbuffer,0,l); } } public void close(){ try { file.Close(); file = null; } catch (Exception) { } } public Country getCountry(IPAddress ipAddress) { return getCountry(bytestoLong(ipAddress.GetAddressBytes())); } public Country getCountry(String ipAddress){ IPAddress addr; try { addr = IPAddress.Parse(ipAddress); } //catch (UnknownHostException e) { catch (Exception e) { Console.Write(e.Message); return UNKNOWN_COUNTRY; } // return getCountry(bytestoLong(addr.GetAddressBytes())); return getCountry(bytestoLong(addr.GetAddressBytes())); } public Country getCountry(long ipAddress){ if (file == null) { //throw new IllegalStateException("Database has been closed."); throw new Exception("Database has been closed."); } if ((databaseType == DatabaseInfo.CITY_EDITION_REV1) | (databaseType == DatabaseInfo.CITY_EDITION_REV0)) { Location l = getLocation(ipAddress); if (l == null) { return UNKNOWN_COUNTRY; } else { return new Country(l.countryCode, l.countryName); } } else { int ret = SeekCountry(ipAddress) - COUNTRY_BEGIN; if (ret == 0) { return UNKNOWN_COUNTRY; } else { return new Country(countryCode[ret], countryName[ret]); } } } public int getID(String ipAddress){ IPAddress addr; try { addr = IPAddress.Parse(ipAddress); } catch (Exception e) { Console.Write(e.Message); return 0; } return getID(bytestoLong(addr.GetAddressBytes())); } public int getID(IPAddress ipAddress) { return getID(bytestoLong(ipAddress.GetAddressBytes())); } public int getID(long ipAddress){ if (file == null) { throw new Exception("Database has been closed."); } int ret = SeekCountry(ipAddress) - databaseSegments[0]; return ret; } public DatabaseInfo getDatabaseInfo(){ if (databaseInfo != null) { return databaseInfo; } try { // Synchronize since we're accessing the database file. lock (this) { bool hasStructureInfo = false; byte [] delim = new byte[3]; // Advance to part of file where database info is stored. file.Seek(-3,SeekOrigin.End); for (int i=0; i<STRUCTURE_INFO_MAX_SIZE; i++) { file.Read(delim,0,3); if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255) { hasStructureInfo = true; break; } } if (hasStructureInfo) { file.Seek(-3,SeekOrigin.Current); } else { // No structure info, must be pre Sep 2002 database, go back to end. file.Seek(-3,SeekOrigin.End); } // Find the database info string. for (int i=0; i<DATABASE_INFO_MAX_SIZE; i++) { file.Read(delim,0,3); if (delim[0]==0 && delim[1]==0 && delim[2]==0) { byte[] dbInfo = new byte[i]; char[] dbInfo2 = new char[i]; file.Read(dbInfo,0,i); for (int a0 = 0;a0 < i;a0++){ dbInfo2[a0] = Convert.ToChar(dbInfo[a0]); } // Create the database info object using the string. this.databaseInfo = new DatabaseInfo(new String(dbInfo2)); return databaseInfo; } file.Seek(-4,SeekOrigin.Current); } } } catch (Exception e) { Console.Write(e.Message); //e.printStackTrace(); } return new DatabaseInfo(""); } public Region getRegion(IPAddress ipAddress) { return getRegion(bytestoLong(ipAddress.GetAddressBytes())); } public Region getRegion(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } catch (Exception e) { Console.Write(e.Message); return null; } return getRegion(bytestoLong(addr.GetAddressBytes())); } [MethodImpl(MethodImplOptions.Synchronized)] public Region getRegion(long ipnum){ Region record = new Region(); int seek_region = 0; if (databaseType == DatabaseInfo.REGION_EDITION_REV0) { seek_region = SeekCountry(ipnum) - STATE_BEGIN_REV0; char [] ch = new char[2]; if (seek_region >= 1000){ record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char)(((seek_region - 1000)/26) + 65); ch[1] = (char)(((seek_region - 1000)%26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[seek_region]; record.countryName = countryName[seek_region]; record.region = ""; } } else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) { seek_region = SeekCountry(ipnum) - STATE_BEGIN_REV1; char [] ch = new char[2]; if (seek_region < US_OFFSET) { record.countryCode = ""; record.countryName = ""; record.region = ""; } else if (seek_region < CANADA_OFFSET) { record.countryCode = "US"; record.countryName = "United States"; ch[0] = (char)(((seek_region - US_OFFSET)/26) + 65); ch[1] = (char)(((seek_region - US_OFFSET)%26) + 65); record.region = new String(ch); } else if (seek_region < WORLD_OFFSET) { record.countryCode = "CA"; record.countryName = "Canada"; ch[0] = (char)(((seek_region - CANADA_OFFSET)/26) + 65); ch[1] = (char)(((seek_region - CANADA_OFFSET)%26) + 65); record.region = new String(ch); } else { record.countryCode = countryCode[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.countryName = countryName[(seek_region - WORLD_OFFSET) / FIPS_RANGE]; record.region = ""; } } return record; } public Location getLocation(IPAddress addr){ return getLocation(bytestoLong(addr.GetAddressBytes())); } public Location getLocation(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } catch (Exception e) { Console.Write(e.Message); return null; } return getLocation(bytestoLong(addr.GetAddressBytes())); } [MethodImpl(MethodImplOptions.Synchronized)] public Location getLocation(long ipnum){ int record_pointer; byte[] record_buf = new byte[FULL_RECORD_LENGTH]; char[] record_buf2 = new char[FULL_RECORD_LENGTH]; int record_buf_offset = 0; Location record = new Location(); int str_length = 0; int j, Seek_country; double latitude = 0, longitude = 0; try { Seek_country = SeekCountry(ipnum); if (Seek_country == databaseSegments[0]) { return null; } record_pointer = Seek_country + ((2 * recordLength - 1) * databaseSegments[0]); if ((dboptions & GEOIP_MEMORY_CACHE) == 1){ Array.Copy(dbbuffer, record_pointer, record_buf, 0, Math.Min(dbbuffer.Length - record_pointer, FULL_RECORD_LENGTH)); } else { file.Seek(record_pointer,SeekOrigin.Begin); file.Read(record_buf,0,FULL_RECORD_LENGTH); } for (int a0 = 0;a0 < FULL_RECORD_LENGTH;a0++){ record_buf2[a0] = Convert.ToChar(record_buf[a0]); } // get country record.countryCode = countryCode[unsignedByteToInt(record_buf[0])]; record.countryName = countryName[unsignedByteToInt(record_buf[0])]; record_buf_offset++; // get region while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.region = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += str_length + 1; str_length = 0; // get region_name record.regionName = RegionName.getRegionName( record.countryCode, record.region ); // get city while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.city = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += (str_length + 1); str_length = 0; // get postal code while (record_buf[record_buf_offset + str_length] != '\0') str_length++; if (str_length > 0) { record.postalCode = new String(record_buf2, record_buf_offset, str_length); } record_buf_offset += (str_length + 1); // get latitude for (j = 0; j < 3; j++) latitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.latitude = (float) latitude/10000 - 180; record_buf_offset += 3; // get longitude for (j = 0; j < 3; j++) longitude += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.longitude = (float) longitude/10000 - 180; record.metro_code = record.dma_code = 0; record.area_code = 0; if (databaseType == DatabaseInfo.CITY_EDITION_REV1) { // get metro_code int metroarea_combo = 0; if (record.countryCode == "US"){ record_buf_offset += 3; for (j = 0; j < 3; j++) metroarea_combo += (unsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8)); record.metro_code = record.dma_code = metroarea_combo/1000; record.area_code = metroarea_combo % 1000; } } } catch (IOException) { Console.Write("IO Exception while seting up segments"); } return record; } public String getOrg(IPAddress addr) { return getOrg(bytestoLong(addr.GetAddressBytes())); } public String getOrg(String str){ IPAddress addr; try { addr = IPAddress.Parse(str); } //catch (UnknownHostException e) { catch (Exception e){ Console.Write(e.Message); return null; } return getOrg(bytestoLong(addr.GetAddressBytes())); } [MethodImpl(MethodImplOptions.Synchronized)] public String getOrg(long ipnum){ int Seek_org; int record_pointer; int str_length = 0; byte [] buf = new byte[MAX_ORG_RECORD_LENGTH]; char [] buf2 = new char[MAX_ORG_RECORD_LENGTH]; String org_buf; try { Seek_org = SeekCountry(ipnum); if (Seek_org == databaseSegments[0]) { return null; } record_pointer = Seek_org + (2 * recordLength - 1) * databaseSegments[0]; if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { Array.Copy(dbbuffer, record_pointer, buf, 0, Math.Min(dbbuffer.Length - record_pointer, MAX_ORG_RECORD_LENGTH)); } else { file.Seek(record_pointer,SeekOrigin.Begin); file.Read(buf,0,MAX_ORG_RECORD_LENGTH); } while (buf[str_length] != 0) { buf2[str_length] = Convert.ToChar(buf[str_length]); str_length++; } buf2[str_length] = '\0'; org_buf = new String(buf2,0,str_length); return org_buf; } catch (IOException) { Console.Write("IO Exception"); return null; } } [MethodImpl(MethodImplOptions.Synchronized)] private int SeekCountry(long ipAddress){ byte [] buf = new byte[2 * MAX_RECORD_LENGTH]; int [] x = new int[2]; int offset = 0; for (int depth = 31; depth >= 0; depth--) { try { if ((dboptions & GEOIP_MEMORY_CACHE) == 1) { for (int i = 0;i < (2 * MAX_RECORD_LENGTH);i++) { buf[i] = dbbuffer[i+(2 * recordLength * offset)]; } } else { file.Seek(2 * recordLength * offset,SeekOrigin.Begin); file.Read(buf,0,2 * MAX_RECORD_LENGTH); } } catch (IOException) { Console.Write("IO Exception"); } for (int i = 0; i<2; i++) { x[i] = 0; for (int j = 0; j<recordLength; j++) { int y = buf[(i*recordLength)+j]; if (y < 0) { y+= 256; } x[i] += (y << (j * 8)); } } if ((ipAddress & (1 << depth)) > 0) { if (x[1] >= databaseSegments[0]) { return x[1]; } offset = x[1]; } else { if (x[0] >= databaseSegments[0]) { return x[0]; } offset = x[0]; } } // shouldn't reach here Console.Write("Error Seeking country while Seeking " + ipAddress); return 0; } private static long swapbytes(long ipAddress){ return (((ipAddress>>0) & 255) << 24) | (((ipAddress>>8) & 255) << 16) | (((ipAddress>>16) & 255) << 8) | (((ipAddress>>24) & 255) << 0); } private static long bytestoLong(byte [] address){ long ipnum = 0; for (int i = 0; i < 4; ++i) { long y = address[i]; if (y < 0) { y+= 256; } ipnum += y << ((3-i)*8); } return ipnum; } private static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } }
using System.Globalization; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Soloco.Composition.Construction; using System; namespace Soloco.Composition.UnitTests.Construction.AttributeKnownPartTypesResolverSpecifications { [TestClass] public class When_resolving_known_part_types_based_on_attributes { public interface IPart1 { } public interface IPart2 { } [Implementation(typeof(PartOverridenPart1))] public interface IOverridenPart1 : IPart1 { } [Implementation(typeof(PartOverridenPart2))] public interface IOverridenPart2 : IPart2 { } public class CompositeOverridenPart1 : IPart1 { } public class CompositeOverridenPart2 : IPart2 { } public class PartOverridenPart1 : IOverridenPart1 { } public class PartOverridenPart2 : IOverridenPart2 { } public class ResolvingKnownPartTypesContext { public Type Part1OverrideType { get; private set; } public Type Part2OverrideType { get; private set; } public Type CompositeType { get; private set; } public ResolvingKnownPartTypesContext(Type part1OverrideType, Type part2OverrideType, Type compositeType) { Part1OverrideType = part1OverrideType; Part2OverrideType = part2OverrideType; CompositeType = compositeType; } } public interface IComposite : IPart1, IPart2 { } public interface ICompositePart2Part : IPart1, IOverridenPart2 { } public interface ICompositePart1Part : IOverridenPart1, IPart2 { } public interface ICompositePart1Part2Part : IOverridenPart1, IOverridenPart2 { } [Composite(typeof(CompositeOverridenPart1))] public interface ICompositePart1Composite : IPart1, IPart2 { } [Composite(typeof(CompositeOverridenPart1))] public interface ICompositePart1CompositePart2Part : IPart1, IOverridenPart2 { } [Composite(typeof(CompositeOverridenPart1))] public interface ICompositePart1CompositePart1Part : IOverridenPart1, IPart2 { } [Composite(typeof(CompositeOverridenPart1))] public interface ICompositePart1CompositePart1Part2Part : IOverridenPart1, IOverridenPart2 { } [Composite(typeof(CompositeOverridenPart2))] public interface ICompositePart2Composite : IPart1, IPart2 { } [Composite(typeof(CompositeOverridenPart2))] public interface ICompositePart2CompositePart2Part : IPart1, IOverridenPart2 { } [Composite(typeof(CompositeOverridenPart2))] public interface ICompositePart2CompositePart1Part : IOverridenPart1, IPart2 { } [Composite(typeof(CompositeOverridenPart2))] public interface ICompositePart2CompositePart1Part2Part : IOverridenPart1, IOverridenPart2 { } [Composite(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2))] public interface ICompositePart1Part2Composite : IPart1, IPart2 { } [Composite(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2))] public interface ICompositePart1Part2CompositePart2Part : IPart1, IOverridenPart2 { } [Composite(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2))] public interface ICompositePart1Part2CompositePart1Part : IOverridenPart1, IPart2 { } [Composite(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2))] public interface ICompositePart1Part2CompositePart1Part2Part : IOverridenPart1, IOverridenPart2 { } private readonly ResolvingKnownPartTypesContext[] _contexts = new[] { new ResolvingKnownPartTypesContext(null, null, typeof(IComposite)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), null, typeof(ICompositePart1Composite)), new ResolvingKnownPartTypesContext(null, typeof(CompositeOverridenPart2), typeof(ICompositePart2Composite)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2), typeof(ICompositePart1Part2Composite)), new ResolvingKnownPartTypesContext(typeof(PartOverridenPart1), null, typeof(ICompositePart1Part)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), null, typeof(ICompositePart1CompositePart1Part)), new ResolvingKnownPartTypesContext(typeof(PartOverridenPart1), typeof(CompositeOverridenPart2), typeof(ICompositePart2CompositePart1Part)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2), typeof(ICompositePart1Part2CompositePart1Part)), new ResolvingKnownPartTypesContext(null, typeof(PartOverridenPart2), typeof(ICompositePart2Part)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), typeof(PartOverridenPart2), typeof(ICompositePart1CompositePart2Part)), new ResolvingKnownPartTypesContext(null, typeof(CompositeOverridenPart2), typeof(ICompositePart2CompositePart2Part)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2), typeof(ICompositePart1Part2CompositePart2Part)), new ResolvingKnownPartTypesContext(typeof(PartOverridenPart1), typeof(PartOverridenPart2), typeof(ICompositePart1Part2Part)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), typeof(PartOverridenPart2), typeof(ICompositePart1CompositePart1Part2Part)), new ResolvingKnownPartTypesContext(typeof(PartOverridenPart1), typeof(CompositeOverridenPart2), typeof(ICompositePart2CompositePart1Part2Part)), new ResolvingKnownPartTypesContext(typeof(CompositeOverridenPart1), typeof(CompositeOverridenPart2), typeof(ICompositePart1Part2CompositePart1Part2Part)), }; [TestMethod] public void then_known_part_types_should_contain_correct_overrides() { var messageBuilder = new StringBuilder(); foreach (var context in _contexts) { VerifyContext(context, messageBuilder); } VerifyMessageBuilder(messageBuilder); } private static void VerifyMessageBuilder(StringBuilder messageBuilder) { if (messageBuilder.Length > 0) { Assert.Fail(messageBuilder.ToString()); } } private static void VerifyContext(ResolvingKnownPartTypesContext context, StringBuilder builder) { var compositeType = context.CompositeType; try { var resolver = new AttributeKnownPartTypesResolver(); var interfaces = compositeType.GetInterfaces(); var knownPartTypes = resolver.Resolve(compositeType, interfaces); AssertPart(typeof(IPart1), compositeType, context.Part1OverrideType, knownPartTypes, builder); AssertPart(typeof(IPart2), compositeType, context.Part2OverrideType, knownPartTypes, builder); } catch (Exception ex) { builder.AppendLine( string.Format(CultureInfo.InvariantCulture, "Exception thrown when checking for composite type {0}.{1}{2}", compositeType, Environment.NewLine, ex )); } } private static void AssertPart(Type partType, Type compositeType, Type expected, KnownPartTypes knownPartTypes, StringBuilder builder) { var message = AssertPart(partType, compositeType, expected, knownPartTypes); if (message != null) { builder.AppendLine(message); } } private static string AssertPart(Type partType, Type compositeType, Type expected, KnownPartTypes knownPartTypes) { var actual = knownPartTypes.GetImplementationType(partType); var title = partType.Name; return expected == null ? AssertPartNull(compositeType, actual, title) : AssertEqual(compositeType, expected, actual, title); } private static string AssertEqual(Type compositeType, Type expected, Type actual, string title) { if (actual == null) { return string.Format( CultureInfo.InvariantCulture, "Failure when checking {0} for composite type {1}. Part type should be '{2}' but is 'null'", title, compositeType, expected.FullName); } if (actual != expected) { return string.Format( CultureInfo.InvariantCulture, "Failure when checking {0} for composite type {1}. Part type should be '{2}' but is '{3}'", title, compositeType, expected.FullName, actual.GetType().FullName); } return null; } private static string AssertPartNull(Type compositeType, Type actual, string title) { if (actual == null) return null; return string.Format( CultureInfo.InvariantCulture, "Failure when checking {0} for composite type {1}. Part type should be 'null' but is '{2}'", title, compositeType, actual.GetType().FullName); } } }
using System; using NUnit.Framework; namespace BehaveN.Tests { [TestFixture] public class DateTimeParserTests { private static readonly TimeSpan _allowedDelta = TimeSpan.FromSeconds(2); internal static void AssertThatDateTimeIsCloseEnoughToNow(DateTime actual) { AssertThatDateTimeIsCloseEnough(actual, DateTime.Now); } [CoverageExclude] internal static void AssertThatDateTimeIsCloseEnough(DateTime actual, DateTime expected) { if (expected - actual > _allowedDelta) { // We know this will fail, but we like the error message. Assert.That(actual, Is.EqualTo(expected)); } } [Test] public void InvalidDateTime() { DateTime now = DateTime.Now; DateTime dt = DateTimeParser.ParseDateTime("xxx", now); Assert.That(dt, Is.EqualTo(now)); } [Test] public void Now() { DateTime dt = DateTimeParser.ParseDateTime(DateTime.Now.ToString()); AssertThatDateTimeIsCloseEnoughToNow(dt); } [Test] public void LowerCaseNow() { DateTime dt = DateTimeParser.ParseDateTime("now"); AssertThatDateTimeIsCloseEnoughToNow(dt); } [Test] public void UpperCaseNow() { DateTime dt = DateTimeParser.ParseDateTime("NOW"); AssertThatDateTimeIsCloseEnoughToNow(dt); } [Test] public void MixedCaseNow() { DateTime dt = DateTimeParser.ParseDateTime("Now"); AssertThatDateTimeIsCloseEnoughToNow(dt); } [Test] public void Today() { DateTime dt = DateTimeParser.ParseDateTime("Today"); Assert.That(dt, Is.EqualTo(DateTime.Today)); } [Test] public void Tomorrow() { DateTime dt = DateTimeParser.ParseDateTime("Tomorrow"); Assert.That(dt, Is.EqualTo(DateTime.Today.AddDays(1))); } [Test] public void Yesterday() { DateTime dt = DateTimeParser.ParseDateTime("Yesterday"); Assert.That(dt, Is.EqualTo(DateTime.Today.AddDays(-1))); } [Test] public void InvalidUnit() { DateTime now = DateTime.Now; DateTime dt = DateTimeParser.ParseDateTime("In 1 Foo", now); Assert.That(dt, Is.EqualTo(now)); } [Test] public void In1Day() { DateTime dt = DateTimeParser.ParseDateTime("In 1 Day"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(1)); } [Test] public void In1Days() { DateTime dt = DateTimeParser.ParseDateTime("In 1 Days"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(1)); } [Test] public void In30Days() { DateTime dt = DateTimeParser.ParseDateTime("In 30 Days"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(30)); } [Test] public void _1DayAgo() { DateTime dt = DateTimeParser.ParseDateTime("1 Day Ago"); Assert.That(dt, Is.EqualTo(DateTime.Today.AddDays(-1))); } [Test] public void _30DaysAgo() { DateTime dt = DateTimeParser.ParseDateTime("30 Days Ago"); Assert.That(dt, Is.EqualTo(DateTime.Today.AddDays(-30))); } [Test] public void _1DayFromNow() { DateTime dt = DateTimeParser.ParseDateTime("1 Day From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddDays(1)); } [Test] public void _30DaysFromNow() { DateTime dt = DateTimeParser.ParseDateTime("30 Days From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddDays(30)); } [Test] public void In5Seconds() { DateTime dt = DateTimeParser.ParseDateTime("In 5 Seconds"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddSeconds(5)); } [Test] public void In5Minutes() { DateTime dt = DateTimeParser.ParseDateTime("In 5 Minutes"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddMinutes(5)); } [Test] public void In5Hours() { DateTime dt = DateTimeParser.ParseDateTime("In 5 Hours"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddHours(5)); } [Test] public void In5Days() { DateTime dt = DateTimeParser.ParseDateTime("In 5 Days"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(5)); } [Test] public void In5Months() { DateTime dt = DateTimeParser.ParseDateTime("In 5 Months"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddMonths(5)); } [Test] public void In5Years() { DateTime dt = DateTimeParser.ParseDateTime("In 5 Years"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddYears(5)); } [Test] public void _5SecondsAgo() { DateTime dt = DateTimeParser.ParseDateTime("5 Seconds Ago"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddSeconds(-5)); } [Test] public void _5MinutesAgo() { DateTime dt = DateTimeParser.ParseDateTime("5 Minutes Ago"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddMinutes(-5)); } [Test] public void _5HoursAgo() { DateTime dt = DateTimeParser.ParseDateTime("5 Hours Ago"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddHours(-5)); } [Test] public void _5DaysAgo() { DateTime dt = DateTimeParser.ParseDateTime("5 Days Ago"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(-5)); } [Test] public void _5MonthsAgo() { DateTime dt = DateTimeParser.ParseDateTime("5 Months Ago"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddMonths(-5)); } [Test] public void _5YearsAgo() { DateTime dt = DateTimeParser.ParseDateTime("5 Years Ago"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddYears(-5)); } [Test] public void _5SecondsFromNow() { DateTime dt = DateTimeParser.ParseDateTime("5 Seconds From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddSeconds(5)); } [Test] public void _5MinutesFromNow() { DateTime dt = DateTimeParser.ParseDateTime("5 Minutes From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddMinutes(5)); } [Test] public void _5HoursFromNow() { DateTime dt = DateTimeParser.ParseDateTime("5 Hours From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddHours(5)); } [Test] public void _5DaysFromNow() { DateTime dt = DateTimeParser.ParseDateTime("5 Days From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddDays(5)); } [Test] public void _5MonthsFromNow() { DateTime dt = DateTimeParser.ParseDateTime("5 Months From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddMonths(5)); } [Test] public void _5YearsFromNow() { DateTime dt = DateTimeParser.ParseDateTime("5 Years From Now"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Now.AddYears(5)); } [Test] public void _5DaysFromToday() { DateTime dt = DateTimeParser.ParseDateTime("5 Days From Today"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(5)); } [Test] public void _5MonthsBeforeToday() { DateTime dt = DateTimeParser.ParseDateTime("5 Months Before Today"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddMonths(-5)); } [Test] public void _5MonthsBeforeTomorrow() { DateTime dt = DateTimeParser.ParseDateTime("5 Months Before Tomorrow"); AssertThatDateTimeIsCloseEnough(dt, DateTime.Today.AddDays(1).AddMonths(-5)); } } }
//------------------------------------------------------------------------------ // <copyright file="SystemWebSectionGroup.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System.Configuration; using System.Security.Permissions; public sealed class SystemWebSectionGroup : ConfigurationSectionGroup { public SystemWebSectionGroup() { } // public properties [ConfigurationProperty("anonymousIdentification")] public AnonymousIdentificationSection AnonymousIdentification { get { return (AnonymousIdentificationSection) Sections["anonymousIdentification"]; } } [ConfigurationProperty("authentication")] public AuthenticationSection Authentication { get { return (AuthenticationSection) Sections["authentication"]; } } [ConfigurationProperty("authorization")] public AuthorizationSection Authorization { get { return (AuthorizationSection) Sections["authorization"]; } } [ConfigurationProperty("browserCaps")] public DefaultSection BrowserCaps { get { return (DefaultSection) Sections["browserCaps"]; } } [ConfigurationProperty("clientTarget")] public ClientTargetSection ClientTarget { get { return (ClientTargetSection) Sections["clientTarget"]; } } [ConfigurationProperty("compilation")] public CompilationSection Compilation { get { return (CompilationSection) Sections["compilation"]; } } [ConfigurationProperty("customErrors")] public CustomErrorsSection CustomErrors { get { return (CustomErrorsSection) Sections["customErrors"]; } } [ConfigurationProperty("deployment")] public DeploymentSection Deployment { get { return (DeploymentSection) Sections["deployment"]; } } [ConfigurationProperty("deviceFilters")] public DefaultSection DeviceFilters { get { return (DefaultSection) Sections["deviceFilters"]; } } [ConfigurationProperty("fullTrustAssemblies")] public FullTrustAssembliesSection FullTrustAssemblies { get { return (FullTrustAssembliesSection)Sections["fullTrustAssemblies"]; } } [ConfigurationProperty("globalization")] public GlobalizationSection Globalization { get { return (GlobalizationSection) Sections["globalization"]; } } [ConfigurationProperty("healthMonitoring")] public HealthMonitoringSection HealthMonitoring { get { return (HealthMonitoringSection) Sections["healthMonitoring"]; } } [ConfigurationProperty("hostingEnvironment")] public HostingEnvironmentSection HostingEnvironment { get { return (HostingEnvironmentSection) Sections["hostingEnvironment"]; } } [ConfigurationProperty("httpCookies")] public HttpCookiesSection HttpCookies { get { return (HttpCookiesSection) Sections["httpCookies"]; } } [ConfigurationProperty("httpHandlers")] public HttpHandlersSection HttpHandlers { get { return (HttpHandlersSection) Sections["httpHandlers"]; } } [ConfigurationProperty("httpModules")] public HttpModulesSection HttpModules { get { return (HttpModulesSection) Sections["httpModules"]; } } [ConfigurationProperty("httpRuntime")] public HttpRuntimeSection HttpRuntime { get { return (HttpRuntimeSection) Sections["httpRuntime"]; } } [ConfigurationProperty("identity")] public IdentitySection Identity { get { return (IdentitySection) Sections["identity"]; } } [ConfigurationProperty("machineKey")] public MachineKeySection MachineKey { get { return (MachineKeySection) Sections["machineKey"]; } } [ConfigurationProperty("membership")] public MembershipSection Membership { get { return (MembershipSection) Sections["membership"]; } } // Note that the return type is ConfigurationSection, not MobileControlsSection. // The reason is that we don't want to link to System.Web.UI.MobileControls just // to return the correct type of this property. [ConfigurationProperty("mobileControls")] [Obsolete("System.Web.Mobile.dll is obsolete.")] public ConfigurationSection MobileControls { get { return (ConfigurationSection) Sections["mobileControls"]; } } [ConfigurationProperty("pages")] public PagesSection Pages { get { return (PagesSection) Sections["pages"]; } } [ConfigurationProperty("partialTrustVisibleAssemblies")] public PartialTrustVisibleAssembliesSection PartialTrustVisibleAssemblies { get { return (PartialTrustVisibleAssembliesSection)Sections["partialTrustVisibleAssemblies"]; } } [ConfigurationProperty("processModel")] public ProcessModelSection ProcessModel { get { return (ProcessModelSection) Sections["processModel"]; } } [ConfigurationProperty("profile")] public ProfileSection Profile { get { return (ProfileSection)Sections["profile"]; } } [ConfigurationProperty("protocols")] public DefaultSection Protocols { get { return (DefaultSection)Sections["protocols"]; } } [ConfigurationProperty("roleManager")] public RoleManagerSection RoleManager { get { return (RoleManagerSection) Sections["roleManager"]; } } [ConfigurationProperty("securityPolicy")] public SecurityPolicySection SecurityPolicy { get { return (SecurityPolicySection) Sections["securityPolicy"]; } } [ConfigurationProperty("sessionState")] public SessionStateSection SessionState { get { return (SessionStateSection) Sections["sessionState"]; } } [ConfigurationProperty("siteMap")] public SiteMapSection SiteMap { get { return (SiteMapSection) Sections["siteMap"]; } } [ConfigurationProperty("trace")] public TraceSection Trace { get { return (TraceSection) Sections["trace"]; } } [ConfigurationProperty("trust")] public TrustSection Trust { get { return (TrustSection) Sections["trust"]; } } [ConfigurationProperty("urlMappings")] public UrlMappingsSection UrlMappings { get { return (UrlMappingsSection) Sections["urlMappings"]; } } [ConfigurationProperty("webControls")] public WebControlsSection WebControls { get { return (WebControlsSection) Sections["webControls"]; } } [ConfigurationProperty("webParts")] public WebPartsSection WebParts { get { return (WebPartsSection) Sections["WebParts"]; } } [ConfigurationProperty("webServices")] public System.Web.Services.Configuration.WebServicesSection WebServices { get { return (System.Web.Services.Configuration.WebServicesSection) Sections["webServices"]; } } [ConfigurationProperty("xhtmlConformance")] public XhtmlConformanceSection XhtmlConformance { get { return (XhtmlConformanceSection) Sections["xhtmlConformance"]; } } } }
#region Using using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Math; using FlatRedBall.Math.Geometry; using FlatRedBall.Gui; using FlatRedBall.Instructions; #if !SILVERLIGHT using FlatRedBall.Graphics.Model; #endif using FlatRedBall.ManagedSpriteGroups; using FlatRedBall.Graphics; using FlatRedBall.Utilities; using PolygonSaveList = FlatRedBall.Content.Polygon.PolygonSaveList; using System.Threading; using FlatRedBall.Input; using FlatRedBall.IO; #endregion // Test namespace TestBed.Screens { public enum AsyncLoadingState { NotStarted, LoadingScreen, Done } public class Screen { #region Fields protected bool IsPaused = false; protected double mAccumulatedPausedTime = 0; protected Camera mCamera; protected Layer mLayer; public bool ShouldRemoveLayer { get; set; } public double PauseAdjustedCurrentTime { get { return TimeManager.CurrentTime - mAccumulatedPausedTime; } } protected List<Screen> mPopups = new List<Screen>(); private string mContentManagerName; // The following are objects which belong to the screen. // These are removed by the Screen when it is Destroyed protected SpriteList mSprites = new SpriteList(); protected List<SpriteGrid> mSpriteGrids = new List<SpriteGrid>(); protected PositionedObjectList<SpriteFrame> mSpriteFrames = new PositionedObjectList<SpriteFrame>(); protected List<IDrawableBatch> mDrawableBatches = new List<IDrawableBatch>(); // End of objects which belong to the Screen. // These variables control the flow from one Screen to the next. protected Scene mLastLoadedScene; private bool mIsActivityFinished; private string mNextScreen; private bool mManageSpriteGrids; internal Screen mNextScreenToLoadAsync; Action ActivatingAction; Action DeactivatingAction; #endregion #region Properties public int ActivityCallCount { get; set; } public string ContentManagerName { get { return mContentManagerName; } } #region XML Docs /// <summary> /// Gets and sets whether the activity is finished for a particular screen. /// </summary> /// <remarks> /// If activity is finished, then the ScreenManager or parent /// screen (if the screen is a popup) knows to destroy the screen /// and loads the NextScreen class.</remarks> #endregion public bool IsActivityFinished { get { return mIsActivityFinished; } set { mIsActivityFinished = value; } } public AsyncLoadingState AsyncLoadingState { get; private set; } public Layer Layer { get { return mLayer; } set { mLayer = value; } } public bool ManageSpriteGrids { get { return mManageSpriteGrids; } set { mManageSpriteGrids = value; } } #region XML Docs /// <summary> /// The fully qualified path of the Screen-inheriting class that this screen is /// to link to. /// </summary> /// <remarks> /// This property is read by the ScreenManager when IsActivityFinished is /// set to true. Therefore, this must always be set to some value before /// or in the same frame as when IsActivityFinished is set to true. /// </remarks> #endregion public string NextScreen { get { return mNextScreen; } set { mNextScreen = value; } } public bool IsMovingBack { get; set; } #if !MONODROID public BackStackBehavior BackStackBehavior = BackStackBehavior.Move; #endif protected bool UnloadsContentManagerWhenDestroyed { get; set; } #endregion #region Methods #region Constructor public Screen(string contentManagerName) { ShouldRemoveLayer = true; UnloadsContentManagerWhenDestroyed = true; mContentManagerName = contentManagerName; mManageSpriteGrids = true; IsActivityFinished = false; mLayer = ScreenManager.NextScreenLayer; ActivatingAction = new Action(Activating); DeactivatingAction = new Action(OnDeactivating); StateManager.Current.Activating += ActivatingAction; StateManager.Current.Deactivating += DeactivatingAction; if (ScreenManager.ShouldActivateScreen) { Activating(); } } #endregion #region Public Methods public virtual void Activating() { this.PreActivate();// for generated code to override, to reload the statestack this.OnActivate(PlatformServices.State);// for user created code } private void OnDeactivating() { this.PreDeactivate();// for generated code to override, to save the statestack this.OnDeactivate(PlatformServices.State);// for user generated code; } #region Activation Methods protected virtual void OnActivate(StateManager state) { } protected virtual void PreActivate() { } protected virtual void OnDeactivate(StateManager state) { } protected virtual void PreDeactivate() { } #endregion public virtual void Activity(bool firstTimeCalled) { if (IsPaused) { mAccumulatedPausedTime += TimeManager.SecondDifference; } if (mManageSpriteGrids) { for (int i = 0; i < mSpriteGrids.Count; i++) { SpriteGrid sg = mSpriteGrids[i]; sg.Manage(); } } for (int i = mPopups.Count - 1; i > -1; i--) { Screen popup = mPopups[i]; popup.Activity(false); popup.ActivityCallCount++; if (popup.IsActivityFinished) { string nextPopup = popup.NextScreen; popup.Destroy(); mPopups.RemoveAt(i); if (nextPopup != "" && nextPopup != null) { LoadPopup(nextPopup, false); } } } #if !MONODROID // This needs to happen after popup activity // in case the Screen creates a popup - we don't // want 2 activity calls for one frame. We also want // to make sure that popups have the opportunity to handle // back calls so that the base doesn't get it. if (PlatformServices.BackStackEnabled && InputManager.BackPressed && !firstTimeCalled) { this.HandleBackNavigation(); } #endif } Type asyncScreenTypeToLoad = null; public void StartAsyncLoad(string screenType) { if (AsyncLoadingState == Screens.AsyncLoadingState.LoadingScreen) { #if DEBUG throw new InvalidOperationException("This Screen is already loading a Screen of type " + asyncScreenTypeToLoad + ". This is a DEBUG-only exception"); #endif } else if (AsyncLoadingState == Screens.AsyncLoadingState.Done) { #if DEBUG throw new InvalidOperationException("This Screen has already loaded a Screen of type " + asyncScreenTypeToLoad + ". This is a DEBUG-only exception"); #endif } else { asyncScreenTypeToLoad = Type.GetType(screenType); if (asyncScreenTypeToLoad == null) { throw new Exception("Could not find the type " + screenType); } AsyncLoadingState = AsyncLoadingState.LoadingScreen; ThreadStart threadStart = new ThreadStart(PerformAsyncLoad); Thread thread = new Thread(threadStart); thread.Start(); } } private void PerformAsyncLoad() { #if XBOX360 // We can not use threads 0 or 2 Thread.CurrentThread.SetProcessorAffinity(4); mNextScreenToLoadAsync = (Screen)Activator.CreateInstance(asyncScreenTypeToLoad); #else mNextScreenToLoadAsync = (Screen)Activator.CreateInstance(asyncScreenTypeToLoad, new object[0]); #endif // Don't add it to the manager! mNextScreenToLoadAsync.Initialize(false); AsyncLoadingState = AsyncLoadingState.Done; } public virtual void Initialize(bool addToManagers) { mAccumulatedPausedTime = TimeManager.CurrentTime; } public virtual void AddToManagers() { } public virtual void Destroy() { StateManager.Current.Activating -= ActivatingAction; StateManager.Current.Deactivating -= DeactivatingAction; if (mLastLoadedScene != null) { mLastLoadedScene.Clear(); } FlatRedBall.Debugging.Debugger.DestroyText(); // All of the popups should be destroyed as well foreach (Screen s in mPopups) s.Destroy(); SpriteManager.RemoveSpriteList<Sprite>(mSprites); // It's common for users to forget to add Particle Sprites // to the mSprites SpriteList. This will either create leftover // particles when the next screen loads or will throw an assert when // the ScreenManager checks if there are any leftover Sprites. To make // things easier we'll just clear the Particle Sprites here. bool isPopup = this != ScreenManager.CurrentScreen; if (!isPopup) SpriteManager.RemoveAllParticleSprites(); // Destory all SpriteGrids that belong to this Screen foreach (SpriteGrid sg in mSpriteGrids) sg.Destroy(); // Destroy all SpriteFrames that belong to this Screen while (mSpriteFrames.Count != 0) SpriteManager.RemoveSpriteFrame(mSpriteFrames[0]); if (UnloadsContentManagerWhenDestroyed && mContentManagerName != FlatRedBallServices.GlobalContentManager) { FlatRedBallServices.Unload(mContentManagerName); FlatRedBallServices.Clean(); } if (ShouldRemoveLayer && mLayer != null) { SpriteManager.RemoveLayer(mLayer); } if (IsPaused) { UnpauseThisScreen(); } GuiManager.Cursor.IgnoreNextClick = true; } protected virtual void PauseThisScreen() { //base.PauseThisScreen(); this.IsPaused = true; InstructionManager.PauseEngine(); } protected virtual void UnpauseThisScreen() { InstructionManager.UnpauseEngine(); this.IsPaused = false; } public double PauseAdjustedSecondsSince(double time) { return PauseAdjustedCurrentTime - time; } #region XML Docs /// <summary>Tells the screen that we are done and wish to move to the /// supplied screen</summary> /// <param>Fully Qualified Type of the screen to move to</param> #endregion public void MoveToScreen(string screenClass) { IsActivityFinished = true; NextScreen = screenClass; } #endregion #region Protected Methods public T LoadPopup<T>(Layer layerToLoadPopupOn) where T : Screen { T loadedScreen = ScreenManager.LoadScreen<T>(layerToLoadPopupOn); mPopups.Add(loadedScreen); return loadedScreen; } public Screen LoadPopup(string popupToLoad, Layer layerToLoadPopupOn) { return LoadPopup(popupToLoad, layerToLoadPopupOn, true); } public Screen LoadPopup(string popupToLoad, Layer layerToLoadPopupOn, bool addToManagers) { Screen loadedScreen = ScreenManager.LoadScreen(popupToLoad, layerToLoadPopupOn, addToManagers, false); mPopups.Add(loadedScreen); return loadedScreen; } public Screen LoadPopup(string popupToLoad, bool useNewLayer) { Screen loadedScreen = ScreenManager.LoadScreen(popupToLoad, useNewLayer); mPopups.Add(loadedScreen); return loadedScreen; } /// <param name="state">This should be a valid enum value of the concrete screen type.</param> public virtual void MoveToState(int state) { // no-op } /// <summary>Default implementation tells the screen manager to finish this screen's activity and navigate /// to the previous screen on the backstack.</summary> /// <remarks>Override this method if you want to have custom behavior when the back button is pressed.</remarks> protected virtual void HandleBackNavigation() { // This is to prevent popups from unexpectedly going back if (ScreenManager.CurrentScreen == this) { #if !MONODROID ScreenManager.NavigateBack(); #endif } } #endregion #endregion } }
// Copyright (c) 2013 Krkadoni.com - Released under The MIT License. // Full license text can be found at http://opensource.org/licenses/MIT using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; //using System.IO; using System.IO; using System.Linq; using System.Runtime.Serialization; using Krkadoni.EnigmaSettings.Interfaces; namespace Krkadoni.EnigmaSettings { [DataContract] public class Settings : ISettings { #region "INotifyPropertyChanged" public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region "IEditable" private bool _isEditing; private IList<IBouquet> _mBouquets; private IList<IXmlSatellite> _mSatellites; private IList<IService> _mServices; private IList<ITransponder> _mTransponders; private string _mSettingsFileName; private Enums.SettingsVersion _mSettingsVersion; public void BeginEdit() { if (_isEditing) return; _mBouquets = new List<IBouquet>(_bouquets); _mServices = new List<IService>(_services); _mTransponders = new List<ITransponder>(_transponders); _mSatellites = new List<IXmlSatellite>(_satellites); _mSettingsFileName = _settingsFileName; _mSettingsVersion = _settingsVersion; _isEditing = true; } public void EndEdit() { _isEditing = false; } public void CancelEdit() { if (!_isEditing) return; Bouquets.Clear(); foreach (IBouquet bouquet in _mBouquets) { Bouquets.Add(bouquet); } Services.Clear(); foreach (IService service in _mServices) { Services.Add(service); } Transponders.Clear(); foreach (ITransponder transponder in _mTransponders) { Transponders.Add(transponder); } Satellites.Clear(); foreach (IXmlSatellite satellite in _mSatellites) { Satellites.Add(satellite); } SettingsFileName = _mSettingsFileName; SettingsVersion = _mSettingsVersion; _isEditing = false; } #endregion #region "ICloneable" /// <summary> /// Performs deep Clone on the object /// </summary> /// <returns></returns> public object Clone() { var settings = (ISettings)MemberwiseClone(); settings.Bouquets = new List<IBouquet>(); settings.Satellites = new List<IXmlSatellite>(); settings.Services = new List<IService>(); settings.Transponders = new List<ITransponder>(); foreach (var bouquet in Bouquets) { if (bouquet != null) settings.Bouquets.Add((IBouquet)bouquet.Clone()); } foreach (var satellite in Satellites) { if (satellite != null) settings.Satellites.Add((IXmlSatellite)satellite.Clone()); } foreach (var service in Services) { if (service != null) settings.Services.Add((IService)service.Clone()); } foreach (var transponder in Transponders) { if (transponder != null) settings.Transponders.Add((ITransponder)transponder.Clone()); } return settings; } #endregion #region "Properties" private IList<IBouquet> _bouquets = new List<IBouquet>(); private IList<IXmlSatellite> _satellites = new List<IXmlSatellite>(); private IList<IService> _services = new List<IService>(); private IList<ITransponder> _transponders = new List<ITransponder>(); private ILog _log; private static readonly ILog NullLogger = new NullLogger(); private string _settingsFileName = string.Empty; private Enums.SettingsVersion _settingsVersion = Enums.SettingsVersion.Unknown; /// <summary> /// Instance used for logging /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> public ILog Log { get { return _log ?? NullLogger; } set { if (value == null) return; if (value == _log) return; _log = value; OnPropertyChanged("Log"); } } /// <summary> /// Full path to settings file location on disk /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public string SettingsFileName { get { return _settingsFileName; } set { if (value == _settingsFileName) return; _settingsFileName = value; OnPropertyChanged("SettingsFileName"); } } /// <summary> /// Directory with all the files for the settings /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public string SettingsDirectory { get { if (string.IsNullOrEmpty(SettingsFileName)) return string.Empty; try { return Path.GetDirectoryName(SettingsFileName); } catch (Exception ex) { Log.Error(ex.Message, ex); return string.Empty; } } } /// <summary> /// Version of the settings file /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public Enums.SettingsVersion SettingsVersion { get { return _settingsVersion; } set { if (value == _settingsVersion) return; _settingsVersion = value; OnPropertyChanged("SettingsVersion"); } } /// <summary> /// List of satellites from satelites.xml file /// </summary> /// <value></value> /// <returns></returns> /// <remarks>Each satelite has coresponding xml transponders from satellites.xml file</remarks> [DataMember] public IList<IXmlSatellite> Satellites { get { return _satellites; } set { if (value == null) value = new List<IXmlSatellite>(); _satellites = value; OnPropertyChanged("Satellites"); } } /// <summary> /// All transponders (DVBS, DVBT, DVBC) from settings file /// </summary> /// <value></value> /// <returns></returns> /// <remarks>These are not transponders from satellites.xml file</remarks> [DataMember] public IList<ITransponder> Transponders { get { return _transponders; } set { if (value == null) value = new List<ITransponder>(); _transponders = value; OnPropertyChanged("Transponders"); } } /// <summary> /// All services from settings file /// </summary> /// <value></value> /// <returns></returns> /// <remarks>Each service should have corresponding transponder from services file</remarks> [DataMember] public IList<IService> Services { get { return _services; } set { if (value == null) value = new List<IService>(); _services = value; OnPropertyChanged("Services"); } } /// <summary> /// All bouquets except the ones stored in 'bouquets' file from Enigma 1 /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public IList<IBouquet> Bouquets { get { return _bouquets; } set { if (value == null) value = new List<IBouquet>(); _bouquets = value; OnPropertyChanged("Bouquets"); } } #endregion #region "Public methods" /// <summary> /// Returns list of satellite transponders from list with all transponders /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<ITransponderDVBS> FindSatelliteTransponders() { return new List<ITransponderDVBS>( Transponders.OfType<ITransponderDVBS>().OrderBy(x => x.OrbitalPositionInt).ThenBy(x => x.Frequency).ToList()); } /// <summary> /// Returns list of transponders for selected satellite /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<ITransponderDVBS> FindTranspondersForSatellite(IXmlSatellite satellite) { return new List<ITransponderDVBS>( FindSatelliteTransponders().Where(x => x.OrbitalPositionInt == Convert.ToInt32(satellite.Position)).ToList()); } /// <summary> /// Returns list of services for selected satellite /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<IService> FindServicesForSatellite(IXmlSatellite satellite) { return new List<IService>( Services.Where( x => (x.Transponder) is ITransponderDVBS && ((ITransponderDVBS)x.Transponder).OrbitalPositionInt == Convert.ToInt32(satellite.Position)).ToList()); } /// <summary> /// Returns list of satellite transponders without corresponding satellite /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<ITransponderDVBS> FindTranspondersWithoutSatellite() { return new List<ITransponderDVBS>(FindSatelliteTransponders().Where(x => x.Satellite == null).ToList()); } /// <summary> /// Returns list of services without corresponding transponder /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<IService> FindServicesWithoutTransponder() { return new List<IService>(Services.Where(x => x.Transponder == null).ToList()); } /// <summary> /// Returns list of services for transponder /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<IService> FindServicesForTransponder(ITransponder transponder) { return new List<IService>(Services.Where(x => x.TransponderId == transponder.TransponderId).ToList()); } /// <summary> /// Returns list of locked services /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> public IList<IService> FindLockedServices() { return new List<IService>(Services.Where(x => x.ServiceSecurity == Enums.ServiceSecurity.BlackListed).ToList()); } /// <summary> /// Returns list of bouquets that have duplicate names /// </summary> /// <returns></returns> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public IList<IFileBouquet> FindBouquetsWithDuplicateFilename() { try { Log.Debug("Searching for bouquets with duplicate filenames"); var fileNames = Bouquets.OfType<IFileBouquet>().GroupBy(x => x.FileName).Where(g => g.Count() > 1).Select(grp => grp.Key).ToList(); foreach (var fileName in fileNames) { Log.Debug(string.Format("Bouquet filename {0} is not unique.", fileName)); } return Bouquets.OfType<IFileBouquet>().GroupBy(x => x.FileName).Where(grp => grp.Count() > 1).SelectMany(grp => grp).ToList(); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException("There was an error while searching for bouquets with duplicate filenames", ex); } } /// <summary> /// Adds new xmlSatellites and xmlTransponders for all transponders in settings file /// that don't have corresponding xmlSatellite. /// </summary> /// <param name="factory"></param> /// <param name="frequencyToleration">Toleration in Hz when searching for existing transponder</param> /// <remarks>Only transponders for new xmlSatellites will be added if not found.</remarks> /// <exception cref="SettingsException"></exception> public void AddMissingXmlSatellites(IInstanceFactory factory, int frequencyToleration = 30000) { var trans = FindTranspondersWithoutSatellite().ToList(); if (trans.Count == 0) { Log.Debug("All satellite transponders have corresponding satellite"); return; } Log.Warn(string.Format("Found {0} transponders without corresponding satellite", trans.Count)); Log.Debug("Adding missing xmlSatellites for transponders in settings file"); try { var missingPositions = trans.Select(x => x.OrbitalPositionInt).Distinct().OrderBy(x => x).ToList(); var newSatellites = new List<IXmlSatellite>(); //adding non existing satellites foreach (int position in missingPositions) { if (position == 0) continue; int mPosition = position; if (Satellites.Any(x => x.Position == mPosition.ToString(CultureInfo.CurrentCulture))) { IXmlSatellite xmlSat = factory.InitNewxmlSatellite(); xmlSat.Position = position.ToString(CultureInfo.CurrentCulture); xmlSat.Flags = "0"; xmlSat.Name = "Sat " + xmlSat.PositionString; Satellites.Add(xmlSat); newSatellites.Add(xmlSat); IList<ITransponderDVBS> found = FindTranspondersWithoutSatellite() .Where(x => x.OrbitalPositionInt == Convert.ToInt32(xmlSat.Position)) .ToList(); foreach (var transponder in found) { transponder.Satellite = xmlSat; } Log.Warn(string.Format(Resources.Settings_AddMissingXMLSatellites_New_satellite_for_position__0__added_to_satellites, position)); } else { Log.Warn( string.Format( Resources .Settings_AddMissingXMLSatellites_WARNING__Some_transponders_are_market_as_satellite_but_have_invalid_position_0_degrees_)); } } foreach (IXmlSatellite newsat in newSatellites) { IList<ITransponderDVBS> transList = FindTranspondersForSatellite(newsat); foreach (ITransponderDVBS tran in transList) { ITransponderDVBS mTran = tran; IList<IXmlTransponder> query = newsat.Transponders.Where( t => ((Convert.ToInt32(t.Frequency) < Convert.ToInt32(mTran.Frequency) + frequencyToleration) && (Convert.ToInt32(t.Frequency) > Convert.ToInt32(mTran.Frequency) - frequencyToleration)) && t.Polarization == mTran.Polarization && t.SymbolRate == mTran.SymbolRate).ToList(); if (query.Count() != 0) continue; IXmlTransponder xmlTran = factory.InitNewxmlTransponder(tran); tran.Satellite.Transponders.Add(xmlTran); Log.Warn(string.Format(Resources.Settings_AddMissingXMLSatellites_Added_new_transponder__0__for_previously_missing_satellite__1_, tran.TransponderId, newsat.PositionString)); } } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_AddMissingXMLSatellites_Failed_to_update_missing_XML_satellites, ex); } } /// <summary> /// Adds new xmlTransponders for all transponders in settings file /// that don't have corresponding xmlTransponder in xmlsatellites.xml /// </summary> /// <param name="factory"></param> /// <param name="frequencyToleration">Toleration in Hz when searching for existing transponder</param> /// <remarks>Transponders are added to all satellites without matching transponder</remarks> /// <exception cref="SettingsException"></exception> public void AddMissingXmlTransponders(IInstanceFactory factory, int frequencyToleration = 30000) { try { AddMissingXmlSatellites(factory, frequencyToleration); Log.Debug("Adding missing xmlTransponders for transponders in settings file"); IList<ITransponderDVBS> tranS = FindSatelliteTransponders().OrderBy(x => x.OrbitalPositionInt).ToList(); foreach (ITransponderDVBS tran in tranS) { ITransponderDVBS mTran = tran; IList<IXmlTransponder> query = tran.Satellite.Transponders.Where( t => ((Convert.ToInt32(t.Frequency) < Convert.ToInt32(mTran.Frequency) + frequencyToleration) && (Convert.ToInt32(t.Frequency) > Convert.ToInt32(mTran.Frequency) - frequencyToleration)) && t.Polarization == mTran.Polarization && t.SymbolRate == mTran.SymbolRate).ToList(); if (query.Any()) continue; //there is no corresponding transponder in xml, go ahead and add it IXmlTransponder xmlTran = factory.InitNewxmlTransponder(tran); tran.Satellite.Transponders.Add(xmlTran); Log.Warn(string.Format("Transponder ID {0} added to xmlTransponders", tran.TransponderId)); } } catch (SettingsException ex) { Log.Error(ex.Message, ex); throw; } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_AddMissingXMLTransponders_Failed_to_update_missing_XML_transponders, ex); } } /// <summary> /// Matches services without transponder with corresponding transponders /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void MatchServicesWithTransponders() { Log.Debug("Matching services with transponders"); try { var query = Services.Join(Transponders, sr => sr.TransponderId, tr => tr.TransponderId, (sr, tr) => new { Transponder = tr, Service = sr }); foreach (var match in query.ToList()) { Log.Debug(string.Format("Service ID {0} {1} matched with transponder ID {2}", match.Service.SID, match.Service.Name, match.Transponder.TransponderId)); match.Service.Transponder = match.Transponder; } IList<IService> servc = FindServicesWithoutTransponder(); if (servc.Count == 0) { Log.Debug("All services have corresponding transponder"); } else { foreach (IService srv in servc) { Log.Warn(string.Format(Resources.Settings_MatchServicesWithTransponders_No_transponder_has_been_found_for_service__0_____1_, srv.ServiceId, srv.Name)); } } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException( Resources.Settings_MatchServicesWithTransponders_There_was_an_error_while_trying_to_match_services_with_transponders, ex); } } /// <summary> /// Matches transponders from settings file without corresponding satellite to satellites from xml file /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void MatchSatellitesWithTransponders() { if (Satellites.Count == 0) { Log.Debug("There is no Satellites from satellites.xml file, skipping matching satellites with transponders"); return; } Log.Debug("Matching satellites with transponders"); try { IList<ITransponderDVBS> transDVBS = FindSatelliteTransponders(); var query = transDVBS.Join(Satellites, tr => Convert.ToString(tr.OrbitalPositionInt), sat => sat.Position, (tr, sat) => new { Transponder = tr, Satellite = sat }); foreach (var match in query.ToList()) { Log.Debug(string.Format("Transponder {0} matched to satellite {1}", match.Transponder.TransponderId, match.Satellite.Name)); match.Transponder.Satellite = match.Satellite; } foreach (ITransponderDVBS tr in transDVBS.Where(x => x.Satellite == null).ToList()) { Log.Warn(string.Format(Resources.Settings_MatchSatellitesWithTransponders_No_satellite_has_been_found_for_transponder__0_, tr.TransponderId)); } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException( Resources.Settings_MatchSatellitesWithTransponders_There_was_an_error_while_matching_transponders_with_satellites_, ex); } } /// <summary> /// Matches services from file bouquets to services from settings /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void MatchFileBouquetsServices() { if (Bouquets.Count == 0) { Log.Debug("There is no bouquets, skip matching file bouquets services to services from settings"); return; } Log.Debug("Matching file bouquets services to services from settings"); try { IList<IBouquetItemService> bis = Bouquets.SelectMany(x => x.BouquetItems).OfType<IBouquetItemService>().ToList(); var query = bis.Join(Services, bs => bs.ServiceId.ToLower(), srv => srv.ServiceId.ToLower(), (bs, srv) => new { BouquetItem = bs, Service = srv }); foreach (var match in query.ToList()) { match.BouquetItem.Service = match.Service; } foreach (IBouquet bq in Bouquets) { foreach (IBouquetItemService bqis in bq.BouquetItems.OfType<IBouquetItemService>().ToList().Where(bqis => bqis.Service != null)) { Log.Debug(string.Format("Bouquet item {0} in file bouquet {1} matched to service {2}", bqis.ServiceId, bq.Name, bqis.Service)); } } IList<IBouquetItemService> notMatched = bis.Where(x => x.Service == null).ToList(); if (notMatched.Count == 0) { Log.Debug("All file bouquets services have corresponding service from settings"); } else { foreach (IBouquetItemService nm in notMatched) { Log.Warn(string.Format(Resources.Settings_MatchBouquetServices_Bouquet_service__0__not_found_in_settings, nm.ServiceId)); } } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_MatchBouquetServices_There_was_an_error_while_matching_bouquet_items_to_services, ex); } } /// <summary> /// Matches services from bouquets inside 'bouquets' file to services from settings /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void MatchBouquetsBouquetsServices() { Log.Debug("Matching services from Enigma1 bouquets file to services from settings"); try { IBouquet bouquetsBouquet = Bouquets.SingleOrDefault(x => x.BouquetType == Enums.BouquetType.E1Bouquets); if (bouquetsBouquet == null) { Log.Debug("'bouquets' bouquet not found in the list of bouquets, skipping matching..."); return; } var a = bouquetsBouquet.BouquetItems.OfType<IBouquetItemBouquetsBouquet>(); var b = a.SelectMany(x => x.Bouquet.BouquetItems); IList<IBouquetItemService> bis = b.OfType<IBouquetItemService>().ToList(); if (bis.Count == 0) { Log.Debug("'bouquets' bouquet has no services, skipping matching..."); return; } var query = bis.Join(Services, bs => bs.ServiceId.ToLower(), srv => srv.ServiceId.ToLower(), (bs, srv) => new { BouquetItem = bs, Service = srv }); foreach (var match in query.ToList()) { match.BouquetItem.Service = match.Service; } foreach (IBouquetItemBouquetsBouquet bq in bouquetsBouquet.BouquetItems.OfType<IBouquetItemBouquetsBouquet>().ToList()) { foreach (IBouquetItemService bqis in bq.Bouquet.BouquetItems.OfType<IBouquetItemService>().ToList().Where(bqis => bqis.Service != null) ) { Log.Debug(string.Format("Bouquet item {0} in Enigma1 bouquet {1} matched to service {2}", bqis.ServiceId, bq.Bouquet.Name, bqis.Service)); } } IList<IBouquetItemService> notMatched = bis.Where(x => x.Service == null).ToList(); if (notMatched.Count == 0) { Log.Debug("All services from Enigma1 bouquets file have corresponding service from settings"); } else { foreach (IBouquetItemService nm in notMatched) { Log.Warn(string.Format(Resources.Settings_MatchBouquetServices_Bouquet_service__0__not_found_in_settings, nm.ServiceId)); } } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_MatchBouquetServices_There_was_an_error_while_matching_bouquet_items_to_services, ex); } } /// <summary> /// Renumbers markers in all bouquets /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RenumberMarkers() { try { Log.Debug("Renumbering marker numbers"); IList<IBouquetItemMarker> bim = Bouquets.SelectMany(x => x.BouquetItems).OfType<IBouquetItemMarker>().ToList(); for (int i = 0; i <= bim.Count - 1; i++) { bim[i].MarkerNumber = i.ToString("X"); Log.Debug(string.Format("Marker {0} now has number {1} (integer value {2}) ", bim[i].Description, i.ToString("X"), i)); } Log.Debug(string.Format("Finished renumbering markers")); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RenumberMarkers_There_was_an_error_while_renumbering_markers_, ex); } } /// <summary> /// Renumbers file names for all file bouquets that have filename starting with 'userbouquet.dbe' /// </summary> /// <remarks>Preserves path in filename if any is set</remarks> /// <exception cref="SettingsException"></exception> public void RenumberBouquetFileNames() { try { Log.Debug("Renumbering bouquets filenames"); IList<IFileBouquet> bqsTv = Bouquets.OfType<IFileBouquet>().Where(x => { string s = Path.GetFileName(x.FileName); return s != null && (x.BouquetType == Enums.BouquetType.UserBouquetTv && s.StartsWith("userbouquet.dbe")); }).OrderBy(x => x.FileName).ToList(); int index = 0; foreach (IFileBouquet bouquet in bqsTv) { string name = Path.GetFileName(bouquet.FileName); if (name != null && !name.StartsWith("userbouquet.dbe")) continue; string fileName = string.Empty; if (bouquet.FileName.IndexOf("/", StringComparison.CurrentCulture) > -1) { fileName = bouquet.FileName.Substring(0, bouquet.FileName.LastIndexOf("/", StringComparison.CurrentCulture) + 1); } fileName = fileName + "userbouquet.dbe" + index.ToString(CultureInfo.CurrentCulture).PadLeft(2, '0') + ".tv"; if (fileName != bouquet.FileName) { Log.Debug(string.Format("Changed filename for bouquet {0} from {1} to {2}", bouquet.Name, Path.GetFileName(bouquet.FileName), Path.GetFileName(fileName))); bouquet.FileName = fileName; } index += 1; } index = 0; IList<IFileBouquet> bqsRadio = Bouquets.OfType<IFileBouquet>().Where(x => { string name = Path.GetFileName(x.FileName); return name != null && (x.BouquetType == Enums.BouquetType.UserBouquetRadio && name.StartsWith("userbouquet.dbe")); }).OrderBy(x => x.FileName).ToList(); foreach (IFileBouquet bouquet in bqsRadio) { string fileName = string.Empty; if (bouquet.FileName.IndexOf("/", StringComparison.CurrentCulture) > -1) { fileName = bouquet.FileName.Substring(0, bouquet.FileName.LastIndexOf("/", StringComparison.CurrentCulture) + 1); } fileName = fileName + "userbouquet.dbe" + index.ToString(CultureInfo.CurrentCulture).PadLeft(2, '0') + ".radio"; if (fileName != bouquet.FileName) { Log.Debug(string.Format("Changed filename for bouquet {0} from {1} to {2}", bouquet.Name, Path.GetFileName(bouquet.FileName), Path.GetFileName(fileName))); bouquet.FileName = fileName; } index += 1; } Log.Debug("Finished renumbering file names"); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RenumberBouquetFileNames_There_was_an_error_while_trying_to_renumber_bouquet_file_names_, ex); } } /// <summary> /// Removes services without transponder from the list of services and all bouquets /// </summary> /// <remarks></remarks> public void RemoveServicesWithoutTransponder() { Log.Debug("Removing services without transponder"); IList<IService> srvcs = Services.Where(x => x.Transponder == null).ToList(); RemoveServices(srvcs); Log.Debug(string.Format("Removed {0} services without transponder", srvcs.Count)); } /// <summary> /// Removes markers that are followed by another marker, or not followed with any items /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveEmptyMarkers() { RemoveEmptyMarkers(null); } /// <summary> /// Removes markers that are followed by another marker, or not followed with any items /// </summary> /// <param name="preserveCondition">Markers that match specified condition will always be preserved</param> /// <exception cref="SettingsException"></exception> public void RemoveEmptyMarkers(Func<IBouquetItemMarker, bool> preserveCondition) { try { Log.Debug("Removing empty markers"); List<IBouquetItemMarker> preserveList = null; if (preserveCondition != null) { preserveList = Bouquets.SelectMany(x => x.BouquetItems).OfType<IBouquetItemMarker>().Where(preserveCondition).ToList(); } foreach (IBouquet bouquet in Bouquets.Where(bouquet => bouquet.BouquetItems.Count > 0)) { for (int i = bouquet.BouquetItems.Count - 1; i >= 0; i += -1) { var bouquetItemMarker = bouquet.BouquetItems.ElementAt(i) as IBouquetItemMarker; //we're only interested in markers if (bouquetItemMarker == null) continue; if (i == bouquet.BouquetItems.Count - 1) { if (preserveList != null && preserveList.Count > 0 && preserveList.Contains(bouquetItemMarker)) { Log.Debug(String.Format("Marker {0} in bouquet {1} is the last item, " + "but not deleting it because it's matching preserve condition", bouquetItemMarker.Description, bouquet.Name)); } else { //if marker is last item in the list remove it bouquet.BouquetItems.RemoveAt(i); Log.Debug(String.Format("Empty marker {0} removed from bouquet {1} because it's the last item in the bouquet", bouquetItemMarker.Description, bouquet.Name)); } } else if (bouquet.BouquetItems.ElementAt(i + 1) is IBouquetItemMarker) { if (preserveList != null && preserveList.Count > 0 && preserveList.Contains(bouquetItemMarker)) { Log.Debug(String.Format("Marker {0} in bouquet {1} is suceeded by another marker, " + "but not deleting it because it's matching preserve condition", bouquetItemMarker.Description, bouquet.Name)); } else { //if next item in the bouquet is also marker remove this one bouquet.BouquetItems.RemoveAt(i); Log.Debug(String.Format("Empty marker {0} removed from bouquet {1} because it's suceeded by another marker", bouquetItemMarker.Description, bouquet.Name)); } } } } Log.Debug("Finished removing empty markers"); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveDoubleMarkers_There_was_an_error_while_removing_double_markers, ex); } } /// <summary> /// Removes bouquets without any items /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveEmptyBouquets() { try { Log.Debug("Removing empty bouquets"); IList<IBouquet> bqs = Bouquets.Where(x => x.BouquetItems.Count == 0).ToList(); foreach (IBouquet bouquet in bqs) { Bouquets.Remove(bouquet); Log.Debug(string.Format("Removed empty bouquet {0} from the list of bouquets", bouquet.Name)); } Log.Debug("Finished removing empty bouquets"); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveEmptyBouquets_There_was_an_error_while_removing_empty_bouquets, ex); } } /// <summary> /// Removes all stream references from all bouquets /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveStreams() { try { Log.Debug("Removing streams from bouquets"); foreach (IBouquet bouquet in Bouquets) { IList<IBouquetItemStream> streams = bouquet.BouquetItems.OfType<IBouquetItemStream>().ToList(); foreach (IBouquetItemStream stream in streams) { bouquet.BouquetItems.Remove(stream); Log.Debug(string.Format("Stream {0} removed from bouquet {1}", stream.Description, bouquet.Name)); } } Log.Debug("Finished removing streams from bouquets"); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveStreams_There_was_an_error_while_removing_streams, ex); } } /// <summary> /// Removes service from list of services and all bouquets /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveService(IService service) { try { if (service == null) throw new ArgumentNullException(); Log.Debug(string.Format("Removing service {0} from settings", service.Name)); foreach (IBouquet bouquet in Bouquets) { IList<IBouquetItemService> biServices = bouquet.BouquetItems.OfType<IBouquetItemService>().Where(x => x.ServiceId == service.ServiceId).ToList(); foreach (IBouquetItemService bis in biServices) { bouquet.BouquetItems.Remove(bis); Log.Debug(string.Format("Service {0} removed from bouquet {1}", service.Name, bouquet.Name)); } } if (Services.Contains(service)) Services.Remove(service); Log.Debug(string.Format("Service {0} removed from settings", service.Name)); } catch (Exception ex) { Log.Error(ex.Message, ex); if (service != null) { throw new SettingsException( string.Format(Resources.Settings_RemoveService_There_was_an_error_while_removing_service__0_, service.Name), ex); } throw new SettingsException( string.Format(Resources.Settings_RemoveService_There_was_an_error_while_removing_service__0_, String.Empty), ex); } } /// <summary> /// Removes services from list of services and all bouquets /// </summary> /// <param name="srv">List of services to be removed</param> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveServices(IList<IService> srv) { try { if (srv.Count == 1) { RemoveService(srv.First()); } else if (srv.Count > 0) { Log.Debug(string.Format("Removing {0} services from settings", srv.Count)); foreach (IBouquet bouquet in Bouquets) { IList<IBouquetItemService> bouquetServices = bouquet.BouquetItems.OfType<IBouquetItemService>().Where(x => (x.Service != null)).ToList(); var query = bouquetServices.Join(srv, bs => bs.ServiceId.ToLower(), sr => sr.ServiceId.ToLower(), (bs, sr) => new { BouquetItem = bs, Service = sr }); foreach (var match in query.ToList()) { bouquet.BouquetItems.Remove(match.BouquetItem); Log.Debug(string.Format("Service {0} removed from bouquet {1}", match.Service.Name, bouquet.Name)); } } foreach (IService service in srv.Where(service => Services.Contains(service))) { Services.Remove(service); Log.Debug(string.Format("Service {0} removed from services", service.Name)); } Log.Debug(string.Format("Services removed")); } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveServices_There_was_an_error_while_deleting_services, ex); } } /// <summary> /// Removes transponder from list of transponders /// and all services on that transponder from all bouquets and from list of services /// </summary> /// <param name="transponder"></param> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveTransponder(ITransponder transponder) { try { if (transponder == null) throw new ArgumentNullException(); Log.Debug(string.Format("Removing transponder {0} from settings", transponder.TransponderId)); foreach (IBouquet bouquet in Bouquets) { IList<IBouquetItemService> biServices = bouquet.BouquetItems.OfType<IBouquetItemService>().Where(x => x.Service != null && Equals(x.Service.Transponder, transponder)).ToList(); foreach (IBouquetItemService bis in biServices) { bouquet.BouquetItems.Remove(bis); Log.Debug(string.Format("Service {0} removed from bouquet {1}", bis.Service.Name, bouquet.Name)); } } foreach (IService service in Services.Where(x => Equals(x.Transponder, transponder)).ToList()) { Services.Remove(service); Log.Debug(string.Format("Service {0} removed from services", service.Name)); } if (Transponders.Contains(transponder)) Transponders.Remove(transponder); Log.Debug(string.Format("Transponder {0} removed from settings", transponder.TransponderId)); } catch (Exception ex) { Log.Error(ex.Message, ex); if (transponder != null) throw new SettingsException( string.Format(Resources.Settings_RemoveTransponder_There_was_an_error_while_removing_transponder__0_, transponder.TransponderId), ex); throw new SettingsException( string.Format(Resources.Settings_RemoveTransponder_There_was_an_error_while_removing_transponder__0_, String.Empty), ex); } } /// <summary> /// Removes transponders from list of transponders /// and all services on specified transponders from all bouquets and from list of services /// </summary> /// <param name="trans"></param> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveTransponders(IList<ITransponder> trans) { try { if (trans.Count == 1) { RemoveTransponder(trans.First()); } else if (trans.Count > 0) { Log.Debug(string.Format("Removing {0} transponders from settings", trans.Count)); foreach (IBouquet bouquet in Bouquets) { IList<IBouquetItemService> bouquetServices = bouquet.BouquetItems.OfType<IBouquetItemService>().Where(x => (x.Service != null)).ToList(); var query = bouquetServices.Join(trans, bs => bs.Service.Transponder, tr => tr, (bs, tr) => new { BouquetItem = bs, Transponder = tr }); foreach (var match in query.ToList()) { bouquet.BouquetItems.Remove(match.BouquetItem); Log.Debug(string.Format("Service {0} removed from bouquet {1}", match.BouquetItem.Service.Name, bouquet.Name)); } } var query2 = Services.Join(trans, sr => sr.Transponder, tr => tr, (sr, tr) => new { Service = sr, Transponder = tr }); foreach (var match in query2.ToList()) { Services.Remove(match.Service); Log.Debug(string.Format("Service {0} removed from services", match.Service.Name)); } foreach (ITransponder tran in trans) { if (!Transponders.Contains(tran)) continue; Transponders.Remove(tran); Log.Debug(string.Format("Transponder {0} removed from transponders", tran.TransponderId)); } Log.Debug(string.Format("Transponders removed")); } } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveTransponders_There_was_an_error_while_removing_transponders, ex); } } /// <summary> /// Remove satellite from list of satellites, /// removes all corresponding transponders from list of transponders /// removes services on that satellite from all bouquets and from list of services /// </summary> /// <param name="satellite"></param> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveSatellite(IXmlSatellite satellite) { try { if (satellite == null) throw new ArgumentNullException(); Log.Debug(string.Format("Removing satellite {0}", satellite.Name)); IList<ITransponder> trans = Transponders.OfType<ITransponderDVBS>().Where(x => Equals(x.Satellite, satellite)).Select(x => (ITransponder)x).ToList(); RemoveTransponders(trans); if (Satellites.Contains(satellite)) { Satellites.Remove(satellite); Log.Debug(string.Format("Satellite {0} removed from satellites", satellite.Name)); } Log.Debug(string.Format("Satellite {0} removed", satellite.Name)); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveSatellite_There_was_an_error_while_removing_satellite, ex); } } /// <summary> /// Remove satellite from list of satellites, /// removes all corresponding transponders from list of transponders /// removes services on that satellite from all bouquets and from list of services /// </summary> /// <param name="orbitalPosition">Orbital position as integer, as seen in satellites.xml file - IE. Astra 19.2 = 192</param> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void RemoveSatellite(int orbitalPosition) { try { Log.Debug(string.Format("Removing satellite position {0}", orbitalPosition)); IList<ITransponder> trans = Transponders.OfType<ITransponderDVBS>().Where(x => x.OrbitalPositionInt == orbitalPosition).Select(x => (ITransponder)x).ToList(); RemoveTransponders(trans); IXmlSatellite satellite = Satellites.FirstOrDefault(x => x.Position == orbitalPosition.ToString(CultureInfo.CurrentCulture)); if (satellite != null) { if (Satellites.Contains(satellite)) { Satellites.Remove(satellite); Log.Debug(string.Format("Satellite {0} removed from satellites", satellite.Name)); } } Log.Debug(string.Format("Satellite position {0} removed", orbitalPosition)); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveSatellite_There_was_an_error_while_removing_satellite, ex); } } /// <summary> /// Removes IBouquetItemService, IBouquetItemFileBouquet and IBouquetItemBouquetsBouquet bouquet items without valid /// reference to service or another bouquet from all bouquets /// </summary> /// <remarks>IBouquetsBouquet, IBouquetItemMarker and IBouquetItemStream items are preserved</remarks> public void RemoveInvalidBouquetItems() { try { Log.Debug("Removing bouquet items without valid reference to service or another bouquet"); foreach (IBouquet bouquet in Bouquets) { IList<IBouquetItemService> biServices = bouquet.BouquetItems.OfType<IBouquetItemService>().Where(x => x.Service == null).ToList(); foreach (IBouquetItemService bis in biServices) { bouquet.BouquetItems.Remove(bis); Log.Debug(string.Format("Removed invalid service reference {0} from bouquet {1}", bis.ServiceId, bouquet)); } IList<IBouquetItemFileBouquet> biFileBouquets = bouquet.BouquetItems.OfType<IBouquetItemFileBouquet>().Where(x => x.Bouquet == null).ToList(); foreach (IBouquetItemFileBouquet bifb in biFileBouquets) { bouquet.BouquetItems.Remove(bifb); Log.Debug(string.Format("Removed invalid reference to file bouquet {0} from bouquet {1}", bifb.FileName, bouquet)); } IList<IBouquetItemBouquetsBouquet> biBouquetsBouquets = bouquet.BouquetItems.OfType<IBouquetItemBouquetsBouquet>().Where(x => x.Bouquet == null).ToList(); foreach (IBouquetItemBouquetsBouquet bibb in biBouquetsBouquets) { bouquet.BouquetItems.Remove(bibb); Log.Debug(string.Format("Removed invalid reference to bouquets bouquet number {0} from bouquet {1}", bibb.BouquetOrderNumberInt, bouquet)); } } Log.Debug(string.Format("Finished removing invalid bouquet items")); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_RemoveInvalidBouquetItems_There_was_an_error_while_removing_invalid_bouquet_items, ex); } } /// <summary> /// Updates namespaces for all satellite transponders with calculated namespace /// </summary> /// <remarks></remarks> /// <exception cref="SettingsException"></exception> public void UpdateSatelliteTranspondersNameSpaces() { try { Log.Debug("Updating namespaces for satellite transponders"); IList<ITransponderDVBS> trans = Transponders.OfType<ITransponderDVBS>().Where(x => x.NameSpc != x.CalculatedNameSpace).ToList(); foreach (ITransponderDVBS transponder in trans) { string oldNameSpc = transponder.NameSpc; transponder.NameSpc = transponder.CalculatedNameSpace; Log.Debug(string.Format("Updated namespace for transponder {0} on satellite position {1} from {2} to {3}", string.Join(":", new[] { transponder.Frequency, transponder.SymbolRate.PadRight(8, '0'), transponder.Polarization, transponder.FEC }), transponder.OrbitalPositionInt, oldNameSpc, transponder.NameSpc)); } Log.Debug("Finished updating namespaces for satellite transponders"); } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException( Resources.Settings_UpdateSatelliteTranspondersNameSpaces_There_was_an_error_while_updating_namespaces_for_satellite_transponders_, ex); } } /// <summary> /// Changes satellite position to new position for satellite and belonging transponders /// </summary> /// <param name="satellite">Instance of IXmlSatellite</param> /// <param name="newPosition">New orbital position as integer as seen in satellites.xml file, IE. Astra 19.2 = 192</param> /// <exception cref="SettingsException">Throws SettingsException if another satellite exists on new position</exception> /// <remarks>Updates transponder namespace with calculated one, if different</remarks> public void ChangeSatellitePosition(IXmlSatellite satellite, int newPosition) { try { if (satellite == null) throw new ArgumentNullException(); if (satellite.Position == newPosition.ToString(CultureInfo.CurrentCulture)) return; Log.Debug(string.Format("Changing position for satellite {0} from {1} to {2}", satellite.Name, satellite.Position, newPosition)); if (Satellites.Any(x => x.Position == newPosition.ToString(CultureInfo.CurrentCulture))) { throw new SettingsException( string.Format( Resources .Settings_ChangeSatellitePosition_Cannot_change_position_for_satellite__1__to__2___0_There_is_already_satellite_on_this_position, Environment.NewLine, satellite.Name, newPosition)); } IList<ITransponderDVBS> trans = FindTranspondersForSatellite(satellite); foreach (ITransponderDVBS transponder in trans) { string oldNameSpc = transponder.NameSpc; transponder.OrbitalPositionInt = newPosition; transponder.NameSpc = transponder.CalculatedNameSpace; if (transponder.NameSpc != oldNameSpc) { Log.Debug(string.Format("Updated namespace & position for transponder {0} from {1} to {2}", string.Join(":", new[] { transponder.Frequency, transponder.SymbolRate.PadRight(8, '0'), transponder.Polarization, transponder.FEC }), oldNameSpc, transponder.NameSpc)); } else { Log.Debug(string.Format("Updated position for transponder {0}", string.Join(":", new[] { transponder.Frequency, transponder.SymbolRate.PadRight(8, '0'), transponder.Polarization, transponder.FEC }))); } } satellite.Position = newPosition.ToString(CultureInfo.CurrentCulture); Log.Debug(string.Format("Finished changing satellite position for satellite {0}", satellite.Name)); } catch (SettingsException ex) { Log.Error(ex.Message, ex); throw; } catch (Exception ex) { Log.Error(ex.Message, ex); throw new SettingsException(Resources.Settings_MoveSatellite_There_was_an_error_while_moving_satellite_to_a_new_position, ex); } } /// <summary> /// Performs MemberwiseClone on current object /// </summary> /// <returns></returns> public object ShallowCopy() { return MemberwiseClone(); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.IO; using System.Web; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps { #region Stream Handler public delegate byte[] StreamHandlerCallback(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse); public class StreamHandler : BaseStreamHandler { StreamHandlerCallback m_callback; public StreamHandler(string httpMethod, string path, StreamHandlerCallback callback) : base(httpMethod, path) { m_callback = callback; } public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return m_callback(path, request, httpRequest, httpResponse); } } #endregion Stream Handler public class GetTextureModule : IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private IAssetService m_assetService; #region IRegionModule Members public void Initialise(Scene pScene, IConfigSource pSource) { m_scene = pScene; } public void PostInitialise() { m_assetService = m_scene.RequestModuleInterface<IAssetService>(); m_scene.EventManager.OnRegisterCaps += RegisterCaps; } public void Close() { } public string Name { get { return "GetTextureModule"; } } public bool IsSharedModule { get { return false; } } public void RegisterCaps(UUID agentID, Caps caps) { UUID capID = UUID.Random(); m_log.Info("[GETTEXTURE]: /CAPS/" + capID); caps.RegisterHandler("GetTexture", new StreamHandler("GET", "/CAPS/" + capID, ProcessGetTexture)); } #endregion private byte[] ProcessGetTexture(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { // TODO: Change this to a config option const string REDIRECT_URL = null; // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string textureStr = query.GetOne("texture_id"); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return null; } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { //m_log.DebugFormat("[GETTEXTURE]: {0}", textureID); AssetBase texture; if (!String.IsNullOrEmpty(REDIRECT_URL)) { // Only try to fetch locally cached textures. Misses are redirected texture = m_assetService.GetCached(textureID.ToString()); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; httpResponse.Send(); return null; } SendTexture(httpRequest, httpResponse, texture); } else { string textureUrl = REDIRECT_URL + textureID.ToString(); m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); httpResponse.RedirectLocation = textureUrl; } } else { // Fetch locally or remotely. Misses return a 404 texture = m_assetService.Get(textureID.ToString()); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; httpResponse.Send(); return null; } SendTexture(httpRequest, httpResponse, texture); } else { m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; } } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); } httpResponse.Send(); return null; } private void SendTexture(OSHttpRequest request, OSHttpResponse response, AssetBase texture) { string range = request.Headers.GetOne("Range"); //m_log.DebugFormat("[GETTEXTURE]: Range {0}", range); if (!String.IsNullOrEmpty(range)) { // Range request int start, end; if (TryParseRange(range, out start, out end)) { end = Utils.Clamp(end, 1, texture.Data.Length); start = Utils.Clamp(start, 0, end - 1); //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); if (end - start < texture.Data.Length) response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentLength = end - start; response.ContentType = texture.Metadata.ContentType; response.Body.Write(texture.Data, start, end - start); } else { m_log.Warn("Malformed Range header: " + range); response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; } } else { // Full content request response.ContentLength = texture.Data.Length; response.ContentType = texture.Metadata.ContentType; response.Body.Write(texture.Data, 0, texture.Data.Length); } } private bool TryParseRange(string header, out int start, out int end) { if (header.StartsWith("bytes=")) { string[] rangeValues = header.Substring(6).Split('-'); if (rangeValues.Length == 2) { if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end)) return true; } } start = end = 0; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Globalization; using System.Linq; using System.Reflection; namespace Microsoft.Tools.ServiceModel.Svcutil { /// <summary> /// This class drives serializing/deserializing the application options into/from a JSON (file or text). /// This is to support updating the web service reference added to a project. A JSON file with the options used to generate the web service reference /// is added along with the generated source file, and is used later to update the reference by passing it as the param to the tool. /// </summary> internal class OptionsSerializer<TAppOptions> : JsonConverter where TAppOptions : ApplicationOptions, new() { /* JSON BASIC SCHEMA { "providerId": "", "version": "", "options": { "op" : value } } */ public override bool CanConvert(Type objectType) { return typeof(TAppOptions).GetTypeInfo().IsAssignableFrom(objectType); } #region Read (deserialization) operations public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jObject = JObject.Load(reader, new JsonLoadSettings() { CommentHandling = CommentHandling.Ignore, LineInfoHandling = LineInfoHandling.Ignore }); return ReadJson(jObject); } public static TAppOptions ReadJson(JObject jObject) { var options = new TAppOptions(); ((IOptionsSerializationHandler)options).RaiseBeforeDeserializeEvent(); foreach (var jPropInfo in jObject) { try { bool optionFound = options.TryGetOption(jPropInfo.Key, out var option); if (optionFound) { switch (option.Name) { case ApplicationOptions.ProviderIdKey: case ApplicationOptions.VersionKey: { ReadOption(option, jPropInfo.Value); } break; case ApplicationOptions.OptionsKey: // special-case the 'options' option to preserve the order. Observe that it must be set to ensure it is initialized only once in case there are multiple definitions in the JSON. option.Deserialize(new JValue(jPropInfo.Key)); var jOptionsObject = jPropInfo.Value as JObject ?? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Shared.Resources.ErrorInvalidOptionValueFormat, jPropInfo.Value?.Type, option.SerializationName)); ReadOptions(options, jOptionsObject); break; default: // it happened to be a property with the same name but on a different location in the JSON schema. optionFound = false; break; } } if (!optionFound) { options.AddWarning(string.Format(CultureInfo.CurrentCulture, Shared.Resources.WarningUnrecognizedOptionFormat, jPropInfo.Key)); } } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; options.AddError(ex); } } ((IOptionsSerializationHandler)options).RaiseAfterDeserializeEvent(); return options; } private static void ReadOption(OptionBase option, JToken jToken) { // let the option deserialize the value. option.Deserialize(jToken); } private static void ReadOptions(TAppOptions options, JObject jOptionsObject) { foreach (var jProperty in jOptionsObject) { try { if (options.TryGetOption(jProperty.Key, out var option)) { ReadOption(option, jProperty.Value); } else { options.AddWarning(string.Format(CultureInfo.CurrentCulture, Shared.Resources.WarningUnrecognizedOptionFormat, jProperty.Key)); } } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) throw; options.AddError(ex); } } } #endregion #region write (serialization) operations public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { WriteJson(writer, (TAppOptions)value, serializer); } public static void WriteJson(JsonWriter writer, TAppOptions options, JsonSerializer serializer) { serializer.TypeNameHandling = TypeNameHandling.Auto; ((IOptionsSerializationHandler)options).RaiseBeforeSerializeEvent(); writer.WriteStartObject(); WriteHeaderProperties(options, writer, serializer); WriteOptions(options, writer, serializer); writer.WriteEndObject(); ((IOptionsSerializationHandler)options).RaiseAfterSerializeEvent(); } private static void WriteHeaderProperties(TAppOptions options, JsonWriter writer, JsonSerializer serializer) { var providerOption = options.GetOption(ApplicationOptions.ProviderIdKey); SerializeOption(providerOption, writer, serializer); var versionOption = options.GetOption(ApplicationOptions.VersionKey); SerializeOption(versionOption, writer, serializer); } private static void WriteOptions(TAppOptions options, JsonWriter writer, JsonSerializer serializer) { var optionsOption = options.GetOption(ApplicationOptions.OptionsKey); writer.WritePropertyName(optionsOption.SerializationName); writer.WriteStartObject(); // keep inputs as the first options entry for convenience (the property bag is sorted). var inputsOption = options.GetOption(ApplicationOptions.InputsKey); SerializeOption(inputsOption, writer, serializer); // get unprocessed options. var otherOptions = options.GetOptions().Where(o => o.Name != ApplicationOptions.InputsKey && o.Name != ApplicationOptions.OptionsKey && o.Name != ApplicationOptions.ProviderIdKey && o.Name != ApplicationOptions.VersionKey).OrderBy(o => o.SerializationName); foreach (var option in otherOptions) { SerializeOption(option, writer, serializer); } writer.WriteEndObject(); } private static void SerializeOption(OptionBase option, JsonWriter writer, JsonSerializer serializer) { if (option.CanSerialize) { writer.WritePropertyName(option.SerializationName); // let the option serialize the value. option.Serialize(writer, serializer); } } #endregion /// <summary> /// This is a convenient method to serialize the options into a command-line-formatted string. /// </summary> /// <param name="options"></param> /// <param name="prettyFormat"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)")] public static string SerializeToString(TAppOptions options, bool prettyFormat) { // Format the string similarly to the JSON format. var valueBuilder = new System.Text.StringBuilder(); var separator = prettyFormat ? Environment.NewLine : " "; foreach (var input in options.Inputs) { valueBuilder.Append($"\"{OptionValueParser.GetSerializationValue(input)}\"{separator}"); } var printOptions = options.GetOptions().Where(o => o.Name != ApplicationOptions.InputsKey && o.Name != ApplicationOptions.OptionsKey && o.Name != ApplicationOptions.ProviderIdKey && o.Name != ApplicationOptions.VersionKey).OrderBy(o => o.SerializationName); foreach (var option in printOptions) { if (option.CanSerialize) { var value = OptionValueParser.GetSerializationValue(option.Value); if (value is ICollection collection) { foreach (var listValue in collection) { valueBuilder.Append($"--{option.Name} \"{listValue}\"{separator}"); } } else { value = value is bool ? string.Empty : $" \"{value}\""; valueBuilder.Append($"--{option.Name}{value}{separator}"); } } } return valueBuilder.ToString(); } } /// <summary> /// This interface allows the options serializer to notify the options container about serialization events. /// This is useful for options container that need to synchronize property values after serialization for instance. /// </summary> public interface IOptionsSerializationHandler { void RaiseBeforeSerializeEvent(); void RaiseAfterSerializeEvent(); void RaiseBeforeDeserializeEvent(); void RaiseAfterDeserializeEvent(); } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; using System.Threading; using System.Globalization; using NUnit.Framework; using NUnit.Framework.Constraints; using NUnit.Framework.Internal.Execution; #if !NETCF using System.Security.Principal; #endif namespace NUnit.Framework.Internal { /// <summary> /// Summary description for TestExecutionContextTests. /// </summary> [TestFixture][Property("Question", "Why?")] public class TestExecutionContextTests { TestExecutionContext fixtureContext; TestExecutionContext setupContext; #if !NETCF && !SILVERLIGHT && !PORTABLE string originalDirectory; IPrincipal originalPrincipal; #endif [OneTimeSetUp] public void OneTimeSetUp() { fixtureContext = TestExecutionContext.CurrentContext; } [OneTimeTearDown] public void OneTimeTearDown() { // TODO: We put some tests in one time teardown to verify that // the context is still valid. It would be better if these tests // were placed in a second-level test, invoked from this test class. TestExecutionContext ec = TestExecutionContext.CurrentContext; Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); Assert.That(ec.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); Assert.That(fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } /// <summary> /// Since we are testing the mechanism that saves and /// restores contexts, we save manually here /// </summary> [SetUp] public void Initialize() { setupContext = new TestExecutionContext(TestExecutionContext.CurrentContext); #if !NETCF && !PORTABLE originalCulture = CultureInfo.CurrentCulture; originalUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE originalDirectory = Environment.CurrentDirectory; originalPrincipal = Thread.CurrentPrincipal; #endif } [TearDown] public void Cleanup() { #if !NETCF && !PORTABLE Thread.CurrentThread.CurrentCulture = originalCulture; Thread.CurrentThread.CurrentUICulture = originalUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE Environment.CurrentDirectory = originalDirectory; Thread.CurrentPrincipal = originalPrincipal; #endif Assert.That( TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo(setupContext.CurrentTest.FullName), "Context at TearDown failed to match that saved from SetUp"); } #region CurrentTest [Test] public void FixtureSetUpCanAccessFixtureName() { Assert.That(fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); } [Test] public void FixtureSetUpCanAccessFixtureFullName() { Assert.That(fixtureContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); } [Test] public void FixtureSetUpHasNullMethodName() { Assert.That(fixtureContext.CurrentTest.MethodName, Is.Null); } [Test] public void FixtureSetUpCanAccessFixtureId() { Assert.That(fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] public void FixtureSetUpCanAccessFixtureProperties() { Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } [Test] public void SetUpCanAccessTestName() { Assert.That(setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName")); } [Test] public void SetUpCanAccessTestFullName() { Assert.That(setupContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName")); } [Test] public void SetUpCanAccessTestMethodName() { Assert.That(setupContext.CurrentTest.MethodName, Is.EqualTo("SetUpCanAccessTestMethodName")); } [Test] public void SetUpCanAccessTestId() { Assert.That(setupContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void SetUpCanAccessTestProperties() { Assert.That(setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [Test] public void TestCanAccessItsOwnName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName")); } [Test] public void TestCanAccessItsOwnFullName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName")); } [Test] public void TestCanAccessItsOwnMethodName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("TestCanAccessItsOwnMethodName")); } [Test] public void TestCanAccessItsOwnId() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } #if !PORTABLE && !SILVERLIGHT [Test] public void TestHasWorkerIdWhenParallel() { var workerId = TestExecutionContext.CurrentContext.WorkerId; var isRunningUnderTestWorker = TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher; Assert.That(workerId != null || !isRunningUnderTestWorker); } #endif [Test] [Property("Answer", 42)] public void TestCanAccessItsOwnProperties() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } #endregion #region CurrentCulture and CurrentUICulture #if !NETCF && !PORTABLE CultureInfo originalCulture; CultureInfo originalUICulture; [Test] public void FixtureSetUpContextReflectsCurrentCulture() { Assert.That(fixtureContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void FixtureSetUpContextReflectsCurrentUICulture() { Assert.That(fixtureContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } [Test] public void SetUpContextReflectsCurrentCulture() { Assert.That(setupContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void SetUpContextReflectsCurrentUICulture() { Assert.That(setupContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } [Test] public void TestContextReflectsCurrentCulture() { Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void TestContextReflectsCurrentUICulture() { Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } [Test] public void SetAndRestoreCurrentCulture() { var context = new TestExecutionContext(setupContext); try { CultureInfo otherCulture = new CultureInfo(originalCulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentCulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set"); Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context"); Assert.AreEqual(setupContext.CurrentCulture, originalCulture, "Original context should not change"); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture was not restored"); Assert.AreEqual(setupContext.CurrentCulture, originalCulture, "Culture not in final context"); } [Test] public void SetAndRestoreCurrentUICulture() { var context = new TestExecutionContext(setupContext); try { CultureInfo otherCulture = new CultureInfo(originalUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentUICulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set"); Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context"); Assert.AreEqual(setupContext.CurrentUICulture, originalUICulture, "Original context should not change"); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentUICulture, originalUICulture, "UICulture was not restored"); Assert.AreEqual(setupContext.CurrentUICulture, originalUICulture, "UICulture not in final context"); } #endif #endregion #region CurrentPrincipal #if !NETCF && !SILVERLIGHT && !PORTABLE [Test] public void FixtureSetUpContextReflectsCurrentPrincipal() { Assert.That(fixtureContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal)); } [Test] public void SetUpContextReflectsCurrentPrincipal() { Assert.That(setupContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal)); } [Test] public void TestContextReflectsCurrentPrincipal() { Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal)); } [Test] public void SetAndRestoreCurrentPrincipal() { var context = new TestExecutionContext(setupContext); try { GenericIdentity identity = new GenericIdentity("foo"); context.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name, "Principal was not set"); Assert.AreEqual("foo", context.CurrentPrincipal.Identity.Name, "Principal not in new context"); Assert.AreEqual(setupContext.CurrentPrincipal, originalPrincipal, "Original context should not change"); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(Thread.CurrentPrincipal, originalPrincipal, "Principal was not restored"); Assert.AreEqual(setupContext.CurrentPrincipal, originalPrincipal, "Principal not in final context"); } #endif #endregion #region ValueFormatter [Test] public void SetAndRestoreValueFormatter() { var context = new TestExecutionContext(setupContext); var originalFormatter = context.CurrentValueFormatter; try { ValueFormatter f = val => "dummy"; context.AddFormatter(next => f); Assert.That(context.CurrentValueFormatter, Is.EqualTo(f)); context.EstablishExecutionEnvironment(); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy")); } finally { setupContext.EstablishExecutionEnvironment(); } Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter)); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123")); } #endregion #region SingleThreaded [Test] public void SingleThreadedDefaultsToFalse() { Assert.False(new TestExecutionContext().IsSingleThreaded); } [Test] public void SingleThreadedIsInherited() { var parent = new TestExecutionContext(); parent.IsSingleThreaded = true; Assert.True(new TestExecutionContext(parent).IsSingleThreaded); } #endregion #region ExecutionStatus [Test] public void ExecutionStatusIsPushedToHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); bottomContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(topContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } [Test] public void ExecutionStatusIsPulledFromHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); topContext.ExecutionStatus = TestExecutionStatus.AbortRequested; Assert.That(bottomContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.AbortRequested)); } [Test] public void ExecutionStatusIsPromulgatedAcrossBranches() { var topContext = new TestExecutionContext(); var leftContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); var rightContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); leftContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(rightContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } #endregion #region Cross-domain Tests #if !SILVERLIGHT && !NETCF && !PORTABLE [Test] public void CanCreateObjectInAppDomain() { AppDomain domain = AppDomain.CreateDomain( "TestCanCreateAppDomain", AppDomain.CurrentDomain.Evidence, AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()), null, false); var obj = domain.CreateInstanceAndUnwrap("nunit.framework.tests", "NUnit.Framework.Internal.TestExecutionContextTests+TestClass"); Assert.NotNull(obj); } [Serializable] private class TestClass { } #endif #endregion } #if !PORTABLE && !SILVERLIGHT && !NETCF [TestFixture] public class TextExecutionContextInAppDomain { private RunsInAppDomain _runsInAppDomain; [SetUp] public void SetUp() { var domain = AppDomain.CreateDomain("TestDomain", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false); _runsInAppDomain = domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "NUnit.Framework.Internal.RunsInAppDomain") as RunsInAppDomain; Assert.That(_runsInAppDomain, Is.Not.Null); } [Test] [Description("Issue 71 - NUnit swallows console output from AppDomains created within tests")] public void CanWriteToConsoleInAppDomain() { _runsInAppDomain.WriteToConsole(); } [Test] [Description("Issue 210 - TestContext.WriteLine in an AppDomain causes an error")] public void CanWriteToTestContextInAppDomain() { _runsInAppDomain.WriteToTestContext(); } } internal class RunsInAppDomain : MarshalByRefObject { public void WriteToConsole() { Console.WriteLine("RunsInAppDomain.WriteToConsole"); } public void WriteToTestContext() { TestContext.WriteLine("RunsInAppDomain.WriteToTestContext"); } } #endif }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Web.Mvc; using System.Web.WebPages; using JetBrains.Annotations; namespace Masb.Mvc.TableBuilder { /// <summary> /// Represents a table rendering helper, that renders table templates. /// </summary> /// <typeparam name="TModel">Type of the root model.</typeparam> /// <typeparam name="TCollectionItem">Type of the collection item, rendered as data rows.</typeparam> public class TableRenderer<TModel, TCollectionItem> : IHelperContext<IList<TCollectionItem>>, ITableRenderer { [NotNull] private readonly ITableTemplate<TModel, TCollectionItem> tableTemplate; [NotNull] private readonly HtmlHelper<TModel> masterHtml; /// <summary> /// Initializes a new instance of the <see cref="TableRenderer{TModel,TCollectionItem}"/> class. /// </summary> /// <param name="tableTemplate"> Table template to render. </param> /// <param name="masterHtml"> The master <see cref="HtmlHelper"/>. </param> public TableRenderer( [NotNull] ITableTemplate<TModel, TCollectionItem> tableTemplate, [NotNull] HtmlHelper<TModel> masterHtml) { if (tableTemplate == null) throw new ArgumentNullException("tableTemplate"); if (masterHtml == null) throw new ArgumentNullException("masterHtml"); this.tableTemplate = tableTemplate; this.masterHtml = masterHtml; this.lazyViewTemplate = new Lazy<TemplateArgs<IList<TCollectionItem>>>(this.CreateTemplateArgs); } /// <summary> /// Gets the header renderer. /// </summary> public TableHeaderRowRenderer Header { get { return this.tableTemplate.Accept(new TableHeaderRowRendererCreator(this.masterHtml)); } } /// <summary> /// Gets a renderer for each item in the table. /// </summary> public IEnumerable<ITableDataRowRenderer> Items { get { Debug.Assert(this.tableTemplate.Expression != null, "this.tableTemplate.Expression != null"); var getter = this.tableTemplate.Expression.Compile(); // ReSharper disable once CompareNonConstrainedGenericWithNull if (this.masterHtml.ViewData.Model == null) return Enumerable.Empty<ITableDataRowRenderer>(); var collection = getter(this.masterHtml.ViewData.Model); if (collection == null) return Enumerable.Empty<ITableDataRowRenderer>(); var result = collection.Select((x, i) => this.CreateItem(x, i, false)); return result; } } /// <summary> /// Returns a renderer for a row that allows the insertion of new items. /// </summary> /// <param name="index">Index that is going to be considered as a new item.</param> /// <param name="defaultModel">Default model that will be used to render this new row.</param> /// <returns>A renderer that helps rendering the "new line".</returns> public ITableDataRowRenderer NewItem(int index, object defaultModel) { return this.CreateItem((TCollectionItem)defaultModel, index, true); } /// <summary> /// Returns a renderer for a row that allows the insertion of new items. /// </summary> /// <param name="index">Index that is going to be considered as a new item.</param> /// <returns>A renderer that helps rendering the "new line".</returns> public ITableDataRowRenderer NewItem(int index) { return this.CreateItem(default(TCollectionItem), index, true); } /// <summary> /// Returns a renderer for a row that allows the insertion of new items. /// </summary> /// <param name="index">Index that is going to be considered as a new item.</param> /// <param name="defaultModel">Default model that will be used to render this new row.</param> /// <returns>A renderer that helps rendering the "new line".</returns> [NotNull] public TableDataRowRenderer<TCollectionItem> NewItem(int index, TCollectionItem defaultModel) { return this.CreateItem(defaultModel, index, true); } [NotNull] private TableDataRowRenderer<TCollectionItem> CreateItem(TCollectionItem item, int index, bool isNewRow) { Debug.Assert(this.tableTemplate.Expression != null, "this.tableTemplate.Expression != null"); var indexHiddenFieldName = this.masterHtml.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName( ExpressionHelper.GetExpressionText(this.tableTemplate.Expression)) + ".Index"; var indexHiddenElementId = this.masterHtml.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId( ExpressionHelper.GetExpressionText(this.tableTemplate.Expression)) + "_Index__" + index; Expression<Func<TModel, TCollectionItem>> indexerLambda; { var expression = this.tableTemplate.Expression; var body = expression.Body; if (body.NodeType == ExpressionType.Convert) body = ((UnaryExpression)body).Operand; if (body.Type.IsArray) { var indexer = Expression.ArrayIndex( body, Expression.Constant(index)); indexerLambda = Expression.Lambda<Func<TModel, TCollectionItem>>(indexer, expression.Parameters); } else { var indexerTypes = new[] { typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(ushort), typeof(short), typeof(sbyte), typeof(byte) }; // getting indexer get method: // reference: http://stackoverflow.com/questions/6759416/accessing-indexer-from-expression-tree var indexerPropInfos = (from pi in body.Type.GetDefaultMembers().OfType<PropertyInfo>() where pi.PropertyType == typeof(TCollectionItem) && pi.CanRead let args = pi.GetIndexParameters() where args.Length == 1 && args[0].ParameterType == typeof(int) let argsType = args[0].ParameterType where indexerTypes.Contains(argsType) select new { pi, argsType }).ToDictionary(x => x.argsType, x => x.pi); var indexerPropInfo = indexerTypes.Select( x => { PropertyInfo pi; indexerPropInfos.TryGetValue(x, out pi); return pi; }) .FirstOrDefault(pi => pi != null); if (indexerPropInfo == null) throw new Exception(string.Format( "Indexer accepting an integer argument and returning {0} was not found in type {1}.", typeof(TCollectionItem).Name, body.Type.Name)); var indexer = Expression.Call( body, indexerPropInfo.GetGetMethod(), new Expression[] { Expression.Constant(index) }); indexerLambda = Expression.Lambda<Func<TModel, TCollectionItem>>(indexer, expression.Parameters); } } var viewData = new ViewDataDictionary<TCollectionItem>(item) { TemplateInfo = { HtmlFieldPrefix = this.masterHtml.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName( ExpressionHelper.GetExpressionText(indexerLambda)) }, ModelMetadata = ModelMetadata.FromLambdaExpression( indexerLambda, this.masterHtml.ViewData) }; var viewContext = new ViewContext( this.masterHtml.ViewContext, this.masterHtml.ViewContext.View, viewData, this.masterHtml.ViewContext.TempData, this.masterHtml.ViewContext.Writer); var viewTemplate = new TemplateArgs<TCollectionItem, RowInfo>( viewData, viewContext, new RowInfo(index, isNewRow)); var row = new TableDataRowRenderer<TCollectionItem>( this.tableTemplate, this.tableTemplate.Columns, viewTemplate, index, indexHiddenFieldName, indexHiddenElementId); return row; } /// <summary> /// Renders a named section. /// </summary> /// <param name="sectionName">Name of the section to render.</param> /// <returns>A <see cref="HelperResult"/> that writes the section to the output stream.</returns> public HelperResult RenderSection(string sectionName) { if (sectionName == null) throw new ArgumentNullException("sectionName"); return this.RenderSection(sectionName, true); } /// <summary> /// Renders a named section. /// </summary> /// <param name="sectionName">Name of the section to render.</param> /// <param name="required">A value indicating whether the section is required or not.</param> /// <returns>A <see cref="HelperResult"/> that writes the section to the output stream.</returns> [ContractAnnotation("canbenull <= required: false; notnull <= required: true")] public HelperResult RenderSection(string sectionName, bool required) { if (sectionName == null) throw new ArgumentNullException("sectionName"); var helperResult = this.GetHelperResult(sectionName); if (helperResult == null && required) throw new Exception(string.Format("Section must be defined: {0}", sectionName)); return helperResult; } /// <summary> /// Returns a value indicating whether the named section is defined or not. /// </summary> /// <param name="sectionName">Name of the section to test.</param> /// <returns>True if the section is defined; otherwise False.</returns> public bool IsSectionDefined(string sectionName) { if (sectionName == null) throw new ArgumentNullException("sectionName"); return this.tableTemplate.IsSectionDefined(sectionName, this.lazyViewTemplate.Value); } [CanBeNull] private HelperResult GetHelperResult([NotNull] string sectionName) { Debug.Assert(sectionName != null, "sectionName != null"); if (!this.tableTemplate.IsSectionDefined(sectionName, this.lazyViewTemplate.Value)) return null; var result = this.tableTemplate.GetSectionHelperResult(sectionName, this.lazyViewTemplate.Value); return result; } private class TableHeaderRowRendererCreator : ITableTemplateVisitor<TModel, TableHeaderRowRenderer> { private readonly HtmlHelper masterHtml; public TableHeaderRowRendererCreator(HtmlHelper masterHtml) { this.masterHtml = masterHtml; } [NotNull] public TableHeaderRowRenderer Visit<TCollectionItem1>(ITableTemplate<TModel, TCollectionItem1> value) { var creator = new TableHeaderCellRendererCreator<TCollectionItem1>(this.masterHtml); var allColumns = value.Columns.Select(x => x.Accept(creator)); var result = new TableHeaderRowRenderer(allColumns); return result; } private class TableHeaderCellRendererCreator<TCollectionItem1> : ITableColumnTemplateFromVisitor<TCollectionItem1, ITableHeaderCellRenderer> { private readonly HtmlHelper rootHtml; public TableHeaderCellRendererCreator(HtmlHelper rootHtml) { this.rootHtml = rootHtml; } public ITableHeaderCellRenderer Visit<TSubProperty>(ITableColumnTemplate<TCollectionItem1, TSubProperty> value) { var viewData = new ViewDataDictionary<TSubProperty> { // Commented code: This code is commented to show what IS NOT NEEDED in this case, // Commented code: because this is a HEADER CELL. ////TemplateInfo = ////{ //// HtmlFieldPrefix = this.html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName( //// ExpressionHelper.GetExpressionText(value.Expression)) ////}, ModelMetadata = ModelMetadata.FromLambdaExpression( value.Expression, new ViewDataDictionary<TCollectionItem1>()) }; var viewContext = new ViewContext( this.rootHtml.ViewContext, this.rootHtml.ViewContext.View, viewData, this.rootHtml.ViewContext.TempData, this.rootHtml.ViewContext.Writer); var viewTemplate = new TemplateArgs<TSubProperty>(viewData, viewContext); var result = new TableHeaderCellRenderer<TSubProperty>(value, viewTemplate); return result; } } } private readonly Lazy<TemplateArgs<IList<TCollectionItem>>> lazyViewTemplate; private TemplateArgs<IList<TCollectionItem>> CreateTemplateArgs() { Debug.Assert(this.tableTemplate.Expression != null, "this.tableTemplate.Expression != null"); var getter = this.tableTemplate.Expression.Compile(); var model = this.masterHtml.ViewData.Model; var collection = default(IList<TCollectionItem>); try { if (model != null) collection = getter(model); } catch (NullReferenceException) { } var viewData = new ViewDataDictionary<IList<TCollectionItem>>(collection) { TemplateInfo = { HtmlFieldPrefix = this.masterHtml.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName( ExpressionHelper.GetExpressionText(this.tableTemplate.Expression)) }, ModelMetadata = ModelMetadata.FromLambdaExpression( this.tableTemplate.Expression, this.masterHtml.ViewData) }; var viewContext = new ViewContext( this.masterHtml.ViewContext, this.masterHtml.ViewContext.View, viewData, this.masterHtml.ViewContext.TempData, this.masterHtml.ViewContext.Writer); var viewTemplate = new TemplateArgs<IList<TCollectionItem>>(viewData, viewContext); return viewTemplate; } /// <summary> /// Gets the <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax. /// </summary> /// <returns> /// The <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax. /// </returns> public AjaxHelper<IList<TCollectionItem>> Ajax { get { return this.lazyViewTemplate.Value.Ajax; } } /// <summary> /// Gets the <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements. /// </summary> /// <returns> /// The <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements. /// </returns> public HtmlHelper<IList<TCollectionItem>> Html { get { return this.lazyViewTemplate.Value.Html; } } /// <summary> /// Gets the current model object or value. /// </summary> public IList<TCollectionItem> Model { get { return this.lazyViewTemplate.Value.Model; } } /// <summary> /// Gets the <see cref="ModelMetadata"/> associated with this object. /// </summary> public ModelMetadata Meta { get { return this.lazyViewTemplate.Value.Meta; } } /// <summary> /// Gets the <see cref="T:System.Web.Mvc.UrlHelper"/> of the rendered snippet. /// </summary> public UrlHelper Url { get { return this.lazyViewTemplate.Value.Url; } } /// <summary> /// Gets the <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax. /// </summary> /// <returns> /// The <see cref="T:System.Web.Mvc.AjaxHelper"/> object that is used to render HTML markup using Ajax. /// </returns> AjaxHelper IHelperContext.Ajax { get { return this.lazyViewTemplate.Value.Ajax; } } /// <summary> /// Gets the <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements. /// </summary> /// <returns> /// The <see cref="T:System.Web.Mvc.HtmlHelper"/> object that is used to render HTML elements. /// </returns> HtmlHelper IHelperContext.Html { get { return this.lazyViewTemplate.Value.Html; } } } }
// -------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // -------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace Codex.Utilities { /// <summary> /// Static utilities related to <see cref="Task" />. /// </summary> public static class TaskUtilities { public static void IgnoreAsync(this Task t) { } /// <summary> /// Returns a faulted task containing the given exception. /// This is the failure complement of <see cref="Task.FromResult{TResult}" />. /// </summary> [ContractOption("runtime", "checking", false)] public static Task<T> FromException<T>(Exception ex) { Contract.Requires(ex != null); Contract.Ensures(Contract.Result<Task<T>>() != null); var failureSource = new TaskCompletionSource<T>(); failureSource.SetException(ex); return failureSource.Task; } /// <summary> /// Provides await functionality for ordinary <see cref="WaitHandle"/>s. /// </summary> /// <param name="handle">The handle to wait on.</param> /// <returns>The awaiter.</returns> public static TaskAwaiter GetAwaiter(this WaitHandle handle) { Contract.Requires(handle != null); return handle.ToTask().GetAwaiter(); } /// <summary> /// Provides await functionality for an array of ordinary <see cref="WaitHandle"/>s. /// </summary> /// <param name="handles">The handles to wait on.</param> /// <returns>The awaiter.</returns> public static TaskAwaiter<int> GetAwaiter(this WaitHandle[] handles) { Contract.Requires(handles != null); Contract.Requires(Contract.ForAll(handles, handle => handles != null)); return handles.ToTask().GetAwaiter(); } /// <summary> /// Creates a TPL Task that is marked as completed when a <see cref="WaitHandle"/> is signaled. /// </summary> /// <param name="handle">The handle whose signal triggers the task to be completed. Do not use a <see cref="Mutex"/> here.</param> /// <param name="timeout">The timeout (in milliseconds) after which the task will fault with a <see cref="TimeoutException"/> if the handle is not signaled by that time.</param> /// <returns>A Task that is completed after the handle is signaled.</returns> /// <remarks> /// There is a (brief) time delay between when the handle is signaled and when the task is marked as completed. /// </remarks> public static Task ToTask(this WaitHandle handle, int timeout = Timeout.Infinite) { Contract.Requires(handle != null); return ToTask(new WaitHandle[1] { handle }, timeout); } /// <summary> /// Creates a TPL Task that is marked as completed when any <see cref="WaitHandle"/> in the array is signaled. /// </summary> /// <param name="handles">The handles whose signals triggers the task to be completed. Do not use a <see cref="Mutex"/> here.</param> /// <param name="timeout">The timeout (in milliseconds) after which the task will return a value of WaitTimeout.</param> /// <returns>A Task that is completed after any handle is signaled.</returns> /// <remarks> /// There is a (brief) time delay between when the handles are signaled and when the task is marked as completed. /// </remarks> public static Task<int> ToTask(this WaitHandle[] handles, int timeout = Timeout.Infinite) { Contract.Requires(handles != null); Contract.Requires(Contract.ForAll(handles, handle => handles != null)); var tcs = new TaskCompletionSource<int>(); int signalledHandle = WaitHandle.WaitAny(handles, 0); if (signalledHandle != WaitHandle.WaitTimeout) { // An optimization for if the handle is already signaled // to return a completed task. tcs.SetResult(signalledHandle); } else { var localVariableInitLock = new object(); lock (localVariableInitLock) { RegisteredWaitHandle[] callbackHandles = new RegisteredWaitHandle[handles.Length]; for (int i = 0; i < handles.Length; i++) { callbackHandles[i] = ThreadPool.RegisterWaitForSingleObject( handles[i], (state, timedOut) => { int handleIndex = (int)state; if (timedOut) { tcs.TrySetResult(WaitHandle.WaitTimeout); } else { tcs.TrySetResult(handleIndex); } // We take a lock here to make sure the outer method has completed setting the local variable callbackHandles contents. lock (localVariableInitLock) { foreach (var handle in callbackHandles) { handle.Unregister(null); } } }, state: i, millisecondsTimeOutInterval: timeout, executeOnlyOnce: true); } } } return tcs.Task; } /// <summary> /// Creates a new <see cref="SemaphoreSlim"/> representing a mutex which can only be entered once. /// </summary> /// <returns>the semaphore</returns> public static SemaphoreSlim CreateMutex() { return new SemaphoreSlim(initialCount: 1, maxCount: 1); } /// <summary> /// Asynchronously acquire a semaphore /// </summary> /// <param name="semaphore">The semaphore to acquire</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>A disposable which will release the semaphore when it is disposed.</returns> public static async Task<SemaphoreReleaser> AcquireAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) { Contract.Requires(semaphore != null); await semaphore.WaitAsync(cancellationToken); return new SemaphoreReleaser(semaphore); } /// <summary> /// Synchronously acquire a semaphore /// </summary> /// <param name="semaphore">The semaphore to acquire</param> public static SemaphoreReleaser AcquireSemaphore(this SemaphoreSlim semaphore) { Contract.Requires(semaphore != null); semaphore.Wait(); return new SemaphoreReleaser(semaphore); } /// <summary> /// Consumes a task and doesn't do anything with it. Useful for fire-and-forget calls to async methods within async methods. /// </summary> /// <param name="task">The task whose result is to be ignored.</param> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "task")] public static void Forget(this Task task) { } /// <summary> /// Allows an IDisposable-conforming release of an acquired semaphore /// </summary> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] public struct SemaphoreReleaser : IDisposable { private readonly SemaphoreSlim m_semaphore; /// <summary> /// Creates a new releaser. /// </summary> /// <param name="semaphore">The semaphore to release when Dispose is invoked.</param> /// <remarks> /// Assumes the semaphore is already acquired. /// </remarks> internal SemaphoreReleaser(SemaphoreSlim semaphore) { Contract.Requires(semaphore != null); this.m_semaphore = semaphore; } /// <summary> /// IDispoaable.Dispose() /// </summary> public void Dispose() { m_semaphore.Release(); } /// <summary> /// Whether this semaphore releaser is valid (and not the default value) /// </summary> public bool IsValid { get { return m_semaphore != null; } } /// <summary> /// Gets the number of threads that will be allowed to enter the semaphore. /// </summary> public int CurrentCount { get { return m_semaphore.CurrentCount; } } } } }
using Plugin.Connectivity.Abstractions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Android.Content; using Android.Net; using Android.Net.Wifi; using Android.App; using Java.Net; namespace Plugin.Connectivity { /// <summary> /// Implementation for Feature /// </summary> [Android.Runtime.Preserve(AllMembers = true)] public class ConnectivityImplementation : BaseConnectivity { private ConnectivityChangeBroadcastReceiver receiver; /// <summary> /// Default constructor /// </summary> public ConnectivityImplementation() { ConnectivityChangeBroadcastReceiver.ConnectionChanged = OnConnectivityChanged; ConnectivityChangeBroadcastReceiver.ConnectionTypeChanged = OnConnectivityTypeChanged; receiver = new ConnectivityChangeBroadcastReceiver(); Application.Context.RegisterReceiver(receiver, new IntentFilter(ConnectivityManager.ConnectivityAction)); } private ConnectivityManager connectivityManager; private WifiManager wifiManager; ConnectivityManager ConnectivityManager { get { if (connectivityManager == null || connectivityManager.Handle == IntPtr.Zero) connectivityManager = (ConnectivityManager)(Application.Context.GetSystemService(Context.ConnectivityService)); return connectivityManager; } } WifiManager WifiManager { get { if(wifiManager == null || wifiManager.Handle == IntPtr.Zero) wifiManager = (WifiManager)(Application.Context.GetSystemService(Context.WifiService)); return wifiManager; } } public static bool GetIsConnected(ConnectivityManager manager) { try { //When on API 21+ need to use getAllNetworks, else fall base to GetAllNetworkInfo //https://developer.android.com/reference/android/net/ConnectivityManager.html#getAllNetworks() if ((int)Android.OS.Build.VERSION.SdkInt >= 21) { foreach (var network in manager.GetAllNetworks()) { try { var capabilities = manager.GetNetworkCapabilities(network); if (capabilities == null) continue; //check to see if it has the internet capability if (!capabilities.HasCapability(NetCapability.Internet)) continue; //if on 23+ then we can also check validated //Indicates that connectivity on this network was successfully validated. //this means that you can be connected to wifi and has internet //2/7/18: We are removing this because apparently devices aren't reporting back the correct information :( //if ((int)Android.OS.Build.VERSION.SdkInt >= 23 && !capabilities.HasCapability(NetCapability.Validated)) // continue; var info = manager.GetNetworkInfo(network); if (info == null || !info.IsAvailable) continue; if (info.IsConnected) return true; } catch { //there is a possibility, but don't worry } } } else { #pragma warning disable CS0618 // Type or member is obsolete foreach (var info in manager.GetAllNetworkInfo()) #pragma warning restore CS0618 // Type or member is obsolete { if (info == null || !info.IsAvailable) continue; if (info.IsConnected) return true; } } return false; } catch (Exception e) { Debug.WriteLine("Unable to get connected state - do you have ACCESS_NETWORK_STATE permission? - error: {0}", e); return false; } } /// <summary> /// Gets if there is an active internet connection /// </summary> public override bool IsConnected => GetIsConnected(ConnectivityManager); /// <summary> /// Tests if a host name is pingable /// </summary> /// <param name="host">The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address (127.0.0.1)</param> /// <param name="msTimeout">Timeout in milliseconds</param> /// <returns></returns> public override async Task<bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException(nameof(host)); if (!IsConnected) return false; return await Task.Run(() => { bool reachable; try { reachable = InetAddress.GetByName(host).IsReachable(msTimeout); } catch (UnknownHostException ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); reachable = false; } catch (Exception ex2) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex2); reachable = false; } return reachable; }); } /// <summary> /// Tests if a remote host name is reachable /// </summary> /// <param name="host">Host name can be a remote IP or URL of website</param> /// <param name="port">Port to attempt to check is reachable.</param> /// <param name="msTimeout">Timeout in milliseconds.</param> /// <returns></returns> public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException(nameof(host)); if (!IsConnected) return false; host = host.Replace("http://www.", string.Empty). Replace("http://", string.Empty). Replace("https://www.", string.Empty). Replace("https://", string.Empty). TrimEnd('/'); return await Task.Run(async () => { try { var tcs = new TaskCompletionSource<InetSocketAddress>(); new System.Threading.Thread(() => { /* this line can take minutes when on wifi with poor or none internet connectivity and Task.Delay solves it only if this is running on new thread (Task.Run does not help) */ InetSocketAddress result = new InetSocketAddress(host, port); if (!tcs.Task.IsCompleted) tcs.TrySetResult(result); }).Start(); Task.Run(async () => { await Task.Delay(msTimeout); if (!tcs.Task.IsCompleted) tcs.TrySetResult(null); }); var sockaddr = await tcs.Task; if (sockaddr == null) return false; using (var sock = new Socket()) { await sock.ConnectAsync(sockaddr, msTimeout); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } }); } /// <summary> /// Gets the list of all active connection types. /// </summary> public override IEnumerable<ConnectionType> ConnectionTypes { get { return GetConnectionTypes(ConnectivityManager); } } public static IEnumerable<ConnectionType> GetConnectionTypes(ConnectivityManager manager) { //When on API 21+ need to use getAllNetworks, else fall base to GetAllNetworkInfo //https://developer.android.com/reference/android/net/ConnectivityManager.html#getAllNetworks() if ((int)Android.OS.Build.VERSION.SdkInt >= 21) { foreach (var network in manager.GetAllNetworks()) { NetworkInfo info = null; try { info = manager.GetNetworkInfo(network); } catch { //there is a possibility, but don't worry about it } if (info == null || !info.IsAvailable) continue; yield return GetConnectionType(info.Type, info.TypeName); } } else { foreach (var info in manager.GetAllNetworkInfo()) { if (info == null || !info.IsAvailable) continue; yield return GetConnectionType(info.Type, info.TypeName); } } } public static ConnectionType GetConnectionType(ConnectivityType connectivityType, string typeName) { switch (connectivityType) { case ConnectivityType.Ethernet: return ConnectionType.Desktop; case ConnectivityType.Wimax: return ConnectionType.Wimax; case ConnectivityType.Wifi: return ConnectionType.WiFi; case ConnectivityType.Bluetooth: return ConnectionType.Bluetooth; case ConnectivityType.Mobile: case ConnectivityType.MobileDun: case ConnectivityType.MobileHipri: case ConnectivityType.MobileMms: return ConnectionType.Cellular; case ConnectivityType.Dummy: return ConnectionType.Other; default: if (string.IsNullOrWhiteSpace(typeName)) return ConnectionType.Other; var typeNameLower = typeName.ToLowerInvariant(); if (typeNameLower.Contains("mobile")) return ConnectionType.Cellular; if (typeNameLower.Contains("wifi")) return ConnectionType.WiFi; if (typeNameLower.Contains("wimax")) return ConnectionType.Wimax; if (typeNameLower.Contains("ethernet")) return ConnectionType.Desktop; if (typeNameLower.Contains("bluetooth")) return ConnectionType.Bluetooth; return ConnectionType.Other; } } /// <summary> /// Retrieves a list of available bandwidths for the platform. /// Only active connections. /// </summary> public override IEnumerable<UInt64> Bandwidths { get { try { if (ConnectionTypes.Contains(ConnectionType.WiFi)) return new[] { (UInt64)WifiManager.ConnectionInfo.LinkSpeed * 1000000 }; } catch (Exception e) { Debug.WriteLine("Unable to get connected state - do you have ACCESS_WIFI_STATE permission? - error: {0}", e); } return new UInt64[] { }; } } private bool disposed = false; /// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> public override void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (receiver != null) Application.Context.UnregisterReceiver(receiver); ConnectivityChangeBroadcastReceiver.ConnectionChanged = null; if (wifiManager != null) { wifiManager.Dispose(); wifiManager = null; } if (connectivityManager != null) { connectivityManager.Dispose(); connectivityManager = null; } } disposed = true; } base.Dispose(disposing); } } }
/* * @(#) ISF2InkML.cs 1.0 06-08-2007 author: Manoj Prasad ************************************************************************* * Copyright (c) 2008 Hewlett-Packard Development Company, L.P. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **************************************************************************/ /************************************************************************ * SVN MACROS * * $Revision: 244 $ * $Author: mnab $ * $LastChangedDate: 2008-07-04 13:57:50 +0530 (Fri, 04 Jul 2008) $ ************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.IO; using Microsoft.Ink; using InkMLConverters; using InkML; namespace InkMLConverters { /// <summary> /// /// </summary> public class ISF2InkML { #region Fields private InkInterpreter inkmlInterpreter; private Dictionary<Guid, string> mapGuidChannel; private int id; private DrawingAttributes currentBrush; private Guid[] currentTraceFormat; #endregion Fields #region Constructor public ISF2InkML() { currentBrush = new DrawingAttributes(); currentTraceFormat = new Guid[5]; ReInitialize(); Initialize(); } /// <summary> /// Function to re initialise the object /// </summary> public void ReInitialize() { id = 0; inkmlInterpreter = new InkInterpreter(); currentTraceFormat.Initialize(); } /// <summary> /// Function to initialise the Map between /// the Guids of the Channel supported in ISF to InkML Channel Names /// </summary> private void Initialize() { mapGuidChannel = new Dictionary<Guid,string>(); mapGuidChannel.Add(PacketProperty.X, "X"); mapGuidChannel.Add(PacketProperty.Y, "Y"); mapGuidChannel.Add(PacketProperty.Z, "Z"); mapGuidChannel.Add(PacketProperty.TimerTick, "T"); mapGuidChannel.Add(PacketProperty.NormalPressure, "F"); mapGuidChannel.Add(PacketProperty.XTiltOrientation, "OTX"); mapGuidChannel.Add(PacketProperty.YTiltOrientation, "OTY"); mapGuidChannel.Add(PacketProperty.RollRotation, "OR"); mapGuidChannel.Add(PacketProperty.YawRotation, "OA"); mapGuidChannel.Add(PacketProperty.PitchRotation, "OE"); mapGuidChannel.Add(PacketProperty.AltitudeOrientation, "E"); mapGuidChannel.Add(PacketProperty.AzimuthOrientation, "A"); mapGuidChannel.Add(PacketProperty.ButtonPressure, "B"); mapGuidChannel.Add(PacketProperty.PacketStatus, "PacketStatus"); mapGuidChannel.Add(PacketProperty.SerialNumber, "S.NO"); mapGuidChannel.Add(PacketProperty.TangentPressure, "TP"); mapGuidChannel.Add(PacketProperty.TwistOrientation, "TO"); } #endregion Constructor #region Convert Functions /// <summary> /// Function to Convert ISF file to InkML file /// </summary> /// <param name="InputFileName">Input ISF file</param> /// <param name="OutputFileName">Output InkML File</param> public void ConvertToInkML(string inputFileName, string outputFileName) { Microsoft.Ink.Ink inkobject = new Microsoft.Ink.Ink(); using (FileStream inkStream = new FileStream(inputFileName, FileMode.Open, FileAccess.Read)) { byte[] inkBytes = new byte[inkStream.Length]; inkStream.Read(inkBytes, 0, System.Convert.ToInt16(inkStream.Length)); inkobject.Load(inkBytes); ConvertToInkML(inkobject, outputFileName); inkStream.Close(); } } /// <summary> /// Function to convert Ink Object to InkML and Save it in the OutputFile /// </summary> /// <param name="InkObject">Ink Object to be converted to InkML</param> /// <param name="OutputFileName">Output InkML File</param> public void ConvertToInkML(Microsoft.Ink.Ink inkObject, string outputFileName) { if (outputFileName.Equals("")) return; currentTraceFormat = inkObject.Strokes[0].PacketDescription; AddInk(inkObject); SaveInkML(outputFileName); } #endregion Convert Functions #region Add and Save Functions /// <summary> /// Function to convert Ink Object to inkML. /// Converts Ink Objects to InkML objects and adds to InkML Interpreter. /// </summary> /// <param name="InkObject"> Ink Object to be converted and added to InkML</param> public void AddInk(Microsoft.Ink.Ink inkObject) { try { currentTraceFormat = inkObject.Strokes[0].PacketDescription; AddTraceFormat(inkObject.Strokes[0]); AddBrush(currentBrush); AddAnnotation(inkObject.ExtendedProperties); AddTraces(inkObject.Strokes); } catch(Exception ) { } } /// <summary> /// Function to convert Tablet Object to InkML. /// Used to capture inkSource information. /// </summary> /// <param name="tabletObject"> Tablet Object</param> public void AddInk(Microsoft.Ink.Tablet tabletObject) { // Creating inkSource object to store the Tablet information InkSource resultIS = new InkSource(inkmlInterpreter.Defs); TraceFormat resultTF = new TraceFormat(inkmlInterpreter.Defs); try { resultIS.TraceFormat = GetTraceFormat(tabletObject); } catch (Exception) { } inkmlInterpreter.ParseInk(resultIS); } /// <summary> /// Function to Save the InkML objects created. /// </summary> /// <param name="FileName"> Output FileName</param> public void SaveInkML(string FileName) { inkmlInterpreter.SaveInk(FileName); } public string SaveInkML() { return inkmlInterpreter.SaveInk(); } #endregion Add and Save Functions #region Converting Functions /// <summary> /// Function to find the traceFormat of the Tablet. /// </summary> /// <param name="theTablet">Tablet Object</param> /// <returns>TraceFormat of the Tablet Object</returns> private TraceFormat GetTraceFormat(Tablet theTablet) { try { TraceFormat resultTF = new TraceFormat(inkmlInterpreter.Defs); // If this particular property is supported, // report the name and property metrics information. Channel tempChannel; Dictionary<Guid, string>.Enumerator guidenum = mapGuidChannel.GetEnumerator(); // Checking the channel support for every Channel possible while (guidenum.MoveNext()) { // If the Channel is supported, // create a Channel object and fill the properties from the Metrics of the Tablet. if (theTablet.IsPacketPropertySupported(guidenum.Current.Key)) { TabletPropertyMetrics theMetrics = theTablet.GetPropertyMetrics(guidenum.Current.Key); tempChannel = new Channel(guidenum.Current.Value, ChannelType.DECIMAL); tempChannel.Units = "inch"; tempChannel.Max = System.Convert.ToString(theMetrics.Maximum); tempChannel.Min = System.Convert.ToString(theMetrics.Minimum); resultTF.AddChannel(tempChannel, true); } } return resultTF; } catch (Exception) { } return null; } private void AddTraceFormat(Microsoft.Ink.Stroke stroke) { int i; Guid[] packetDescription = stroke.PacketDescription; TraceFormat resultTF = new TraceFormat(inkmlInterpreter.Defs); Channel tempChannel; for (i = 0; i < packetDescription.Length; i++) { // create a Channel object and fill the properties from the Metrics of stroke TabletPropertyMetrics theMetrics =stroke.GetPacketDescriptionPropertyMetrics((Guid)packetDescription.GetValue(i)); tempChannel = new Channel(mapGuidChannel[((Guid)packetDescription.GetValue(i))], ChannelType.DECIMAL); tempChannel.Units = "inch"; tempChannel.Max = System.Convert.ToString(theMetrics.Maximum); tempChannel.Min = System.Convert.ToString(theMetrics.Minimum); resultTF.AddChannel(tempChannel, true); } inkmlInterpreter.ParseInk(resultTF); } /// <summary> /// Function to Add Extended Properties of the Ink to InkML. /// </summary> /// <param name="inkAnnotation"> Extended Properties of Ink</param> private void AddAnnotation(ExtendedProperties inkAnnotation) { try { // Using Enumerator, Get the Data and Id // Initialise a annotation element for every Data and id and save the data into it. // Add the annotation element to the inkml interpreter Annotation result; ExtendedProperties.ExtendedPropertiesEnumerator annotationEnum = inkAnnotation.GetEnumerator(); while (annotationEnum.MoveNext()) { result = new Annotation(); result.AnnotationTextValue = System.Convert.ToString(annotationEnum.Current.Data); result.SetAttribute("id", annotationEnum.Current.Id.ToString()); inkmlInterpreter.ParseInk(result); } } catch (Exception) { } } /* This function Captures the Brush and traceFormat changes in a Stroke. * Other Properties like TransForm, Shear and Scale are not Captured. * This can be done after including the CanvasTransform and Mapping element * in the Parser. * * **** TransForm property of the Strokes/Stroke sets a Matrix Mapping * **** Scale property of the Strokes/Stroke sets XY scaling values. * **** Shear and rotate are not supported in inkML. But can be added as annotations * * This Function First checks for change in Brush. * Adds a brush element to the inkML if there is a change. * * Next it checks for change in TraceFormat. * Adds a traceFormat element to the inkMl if there is a change * * It also has Extended Properties. This function doesnot convert this to * annotations. Inserting AddAnnotation(extendedProperties) would solve this. * * Next it adds a stroke object. */ private void AddTraces(Strokes traces) { Trace tempTrace; Microsoft.Ink.Stroke temp; try { for(int j=0;j<traces.Count;j++) { temp = traces[j]; if (!temp.Deleted) { if (BrushChanged(temp.DrawingAttributes)) { AddBrush(temp.DrawingAttributes); currentBrush = temp.DrawingAttributes; } if (TraceFormatChanged(temp.PacketDescription)) { currentTraceFormat = temp.PacketDescription; AddTraceFormat(temp); } tempTrace = new Trace(inkmlInterpreter.Defs); for (int i = 0; i < currentTraceFormat.Length; i++) { //Get stroke data. ArrayList strokeData = new ArrayList(temp.GetPacketValuesByProperty((Guid)currentTraceFormat.GetValue(i))); //Convert from HIMETRIC to inch // Converting the data in HIMETRIC unit(dev) to Pixels (PPI) unit. for (int k = 0; k < strokeData.Count; k++) { // 1 HIMETRIC = .01 mm and 1 inch = 25.4 mm // typical screenResolution = 96 pixels/inch //value in pixels = himetric * .01 * screenResolution / 25.4 double value = (double)(int)strokeData[k]; value = (value * .01)/ 25.4; strokeData[k] = (double)value; } //set trace data in inches to inkML trace tempTrace.SetTraceDataDecimal(mapGuidChannel[((Guid)currentTraceFormat.GetValue(i))], strokeData); } inkmlInterpreter.ParseInk(tempTrace); } } } catch (Exception ) { } } /// <summary> /// Function to Add brush element to the InkML interpreter. /// Converts the Drawing Attribute of a stroke to AnnotationXML /// Extended Property is left for future implementation. /// Brush now supports only one annotation element within in it. /// </summary> /// <param name="brush">Drawing Attributes to be Converted to Brush element</param> private void AddBrush(DrawingAttributes brush) { Brush inkMLBrush = new Brush(inkmlInterpreter.Defs); AnnotationXML bAnnotation = new AnnotationXML(); bAnnotation.AddProperty("color", brush.Color.Name); bAnnotation.AddProperty("width", System.Convert.ToString(brush.Width)); bAnnotation.AddProperty("transparency", System.Convert.ToString(brush.Transparency)); bAnnotation.AddProperty("antialiased", System.Convert.ToString(brush.AntiAliased)); bAnnotation.AddProperty("fittocurve", System.Convert.ToString(brush.FitToCurve)); bAnnotation.AddProperty("height", System.Convert.ToString(brush.Height)); bAnnotation.AddProperty("ignorePressure", System.Convert.ToString(brush.IgnorePressure)); bAnnotation.AddProperty("pentip", System.Convert.ToString(brush.PenTip)); inkMLBrush.BrushAnnotationXML = bAnnotation; inkmlInterpreter.ParseInk(inkMLBrush); } /// <summary> /// Function to check whether the traceFormat list is the same as the /// current TraceFormat List /// </summary> /// <param name="traceFormat"> list of channels in traceFormat</param> /// <returns> boolean value </returns> private bool TraceFormatChanged(Guid[] traceFormat) { if (currentTraceFormat.Length != traceFormat.Length) { return true; } IEnumerator tfEnum = traceFormat.GetEnumerator(); IEnumerator ctfEnum = currentTraceFormat.GetEnumerator(); while(tfEnum.MoveNext() && ctfEnum.MoveNext()) { if (!((Guid)tfEnum.Current).Equals(ctfEnum.Current)) { return true; } } return false; } /// <summary> /// Function to find Change in the Brush properties. /// </summary> /// <param name="brush">Brush to be compared with the current brush</param> /// <returns>boolean value </returns> private bool BrushChanged(DrawingAttributes brush) { if (currentBrush.AntiAliased != brush.AntiAliased) { return true; } if (!currentBrush.Color.Equals(brush.Color)) { return true; } if (currentBrush.FitToCurve != brush.FitToCurve) { return true; } if (currentBrush.Height != brush.Height) { return true; } if (currentBrush.IgnorePressure != brush.IgnorePressure) { return true; } if (currentBrush.PenTip != brush.PenTip) { return true; } if (currentBrush.Transparency != brush.Transparency) { return true; } if (currentBrush.Width != brush.Width) { return true; } return false; } private int IncrementId() { return id++; } #endregion Converting Functions } }
namespace LUAnity { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; // Passes objects from the CLR to Lua and vice-versa public class ObjectTranslator { public Lua Interpreter; public MetaFunctions MetaFunctions; public TypeChecker TypeChecker; List<Assembly> _assemblies; LuaCSFunction _loadAssemblyFunction; LuaCSFunction _importTypeFunction; LuaCSFunction _getMethodSigFunction; LuaCSFunction _getConstructorSigFunction; LuaCSFunction _ctypeFunction; LuaCSFunction _enumFromIntFunction; // [object index]: object readonly Dictionary<int, object> _objects = new Dictionary<int, object>(); // [object]: object index readonly Dictionary<object, int> _objectsBackward = new Dictionary<object, int>(); int _nextObjectIndex = 0; // We want to ensure that objects always have a unique ID //public EventHandlerContainer pendingEvents = new EventHandlerContainer(); public ObjectTranslator( Lua interpreter, IntPtr luaState ) { Interpreter = interpreter; MetaFunctions = new MetaFunctions( this ); TypeChecker = new TypeChecker( this ); _assemblies = new List<Assembly>(); _CreateLuaObjectList( luaState ); _CreateIndexingMetaFunction( luaState ); _CreateBaseClassMetatable( luaState ); _CreateClassMetatable( luaState ); _CreateFunctionMetatable( luaState ); _SetGlobalFunctions( luaState ); } // Sets up the list of objects in the Lua side void _CreateLuaObjectList( IntPtr luaState ) { LuaLib.lua_pushstring( luaState, "luaNet_objects" ); // s LuaLib.lua_newtable( luaState ); // s|t LuaLib.lua_newtable( luaState ); // s|t|mt // The values in the metatable are weak LuaLib.lua_pushstring( luaState, "__mode" ); // s|t|mt|s LuaLib.lua_pushstring( luaState, "v" ); // s|t|mt|s|s LuaLib.lua_settable( luaState, -3 ); // s|t|mt LuaLib.lua_setmetatable( luaState, -2 ); // s|t LuaLib.lua_settable( luaState, LuaIndexes.LUA_REGISTRYINDEX ); } // Registers the indexing function of CLR objects passed to Lua void _CreateIndexingMetaFunction( IntPtr luaState ) { LuaLib.lua_pushstring( luaState, "luaNet_indexfunction" ); // s LuaLib.luaL_dostring( luaState, MetaFunctions.LuaIndexFunction ); // s|f LuaLib.lua_rawset( luaState, LuaIndexes.LUA_REGISTRYINDEX ); } // Creates the metatable for superclasses (the base field of registered tables) void _CreateBaseClassMetatable( IntPtr luaState ) { LuaLib.luaL_newmetatable( luaState, "luaNet_searchbase" ); // mt LuaLib.lua_pushstring( luaState, "__gc" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.GcFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__tostring" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ToStringFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__index" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.BaseIndexFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__newindex" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.NewIndexFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_settop( luaState, -2 ); } // Creates the metatable for type references void _CreateClassMetatable( IntPtr luaState ) { LuaLib.luaL_newmetatable( luaState, "luaNet_class" ); // mt LuaLib.lua_pushstring( luaState, "__gc" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.GcFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__tostring" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ToStringFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__index" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ClassIndexFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__newindex" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ClassNewindexFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__call" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.CallConstructorFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_settop( luaState, -2 ); } // Creates the metatable for delegates void _CreateFunctionMetatable( IntPtr luaState ) { LuaLib.luaL_newmetatable( luaState, "luaNet_function" ); // mt LuaLib.lua_pushstring( luaState, "__gc" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.GcFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__call" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ExecuteDelegateFunction ); // mt|s|cf LuaLib.lua_settable( luaState, -3 ); // mt LuaLib.lua_settop( luaState, -2 ); } // Registers the global functions used by LUAnity void _SetGlobalFunctions( IntPtr luaState ) { _loadAssemblyFunction = new LuaCSFunction( _LoadAssembly ); _importTypeFunction = new LuaCSFunction( _ImportType ); _getMethodSigFunction = new LuaCSFunction( _GetMethodSignature ); _getConstructorSigFunction = new LuaCSFunction( GetConstructorSignature ); _ctypeFunction = new LuaCSFunction( _CType ); _enumFromIntFunction = new LuaCSFunction( _EnumFromIntOrString ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.IndexFunction ); LuaLib.lua_setglobal( luaState, "get_object_member" ); LuaLib.lua_pushstdcallcfunction( luaState, _importTypeFunction ); LuaLib.lua_setglobal( luaState, "import_type" ); LuaLib.lua_pushstdcallcfunction( luaState, _loadAssemblyFunction ); LuaLib.lua_setglobal( luaState, "load_assembly" ); LuaLib.lua_pushstdcallcfunction( luaState, _getMethodSigFunction ); LuaLib.lua_setglobal( luaState, "get_method_bysig" ); LuaLib.lua_pushstdcallcfunction( luaState, _getConstructorSigFunction ); LuaLib.lua_setglobal( luaState, "get_constructor_bysig" ); LuaLib.lua_pushstdcallcfunction( luaState, _ctypeFunction ); LuaLib.lua_setglobal( luaState, "ctype" ); LuaLib.lua_pushstdcallcfunction( luaState, _enumFromIntFunction ); LuaLib.lua_setglobal( luaState, "enum" ); } // Implementation of load_assembly( "assemblyName" ) // Throws an error if the assembly is not found [MonoPInvokeCallback( typeof( LuaCSFunction ) )] static int _LoadAssembly( IntPtr luaState ) { ObjectTranslator translator = Lua.GetObjectTranslator( luaState ); try { string assemblyName = LuaLib.lua_tostring( luaState, 1 ); Assembly assembly = null; try { assembly = Assembly.Load( assemblyName ); } catch( BadImageFormatException ) { // The assemblyName was invalid, it is most likely a path } if( assembly == null ) { assembly = Assembly.Load( AssemblyName.GetAssemblyName( assemblyName ) ); } if( assembly != null && !translator._assemblies.Contains( assembly ) ) { translator._assemblies.Add( assembly ); } } catch( Exception e ) { translator.ThrowError( luaState, e ); } return 0; } // Implementation of import_type( "className" ) // Returns nil if the type is not found [MonoPInvokeCallback( typeof( LuaCSFunction ) )] static int _ImportType( IntPtr luaState ) { ObjectTranslator translator = Lua.GetObjectTranslator( luaState ); string className = LuaLib.lua_tostring( luaState, 1 ); Type klass = translator.FindType( className ); if( klass != null ) { translator.PushType( luaState, klass ); } else { LuaLib.lua_pushnil( luaState ); } return 1; } // Implementation of get_method_bysig( obj, "methodName", "paramType1", ... ) // Returns nil if no matching method is not found [MonoPInvokeCallback( typeof( LuaCSFunction ) )] static int _GetMethodSignature( IntPtr luaState ) { ObjectTranslator translator = Lua.GetObjectTranslator( luaState ); ProxyType klass; object target; int udata = LuaLib.luanet_checkudata( luaState, 1, "luaNet_class" ); if( udata != -1 ) { klass = (ProxyType)translator._objects[udata]; target = null; } else { target = translator.GetRawNetObject( luaState, 1 ); if( target == null ) { translator.ThrowError( luaState, "get_method_bysig: first arg is not type or object reference" ); LuaLib.lua_pushnil( luaState ); return 1; } klass = new ProxyType( target.GetType() ); } string methodName = LuaLib.lua_tostring( luaState, 2 ).ToString(); var signatures = new Type[LuaLib.lua_gettop( luaState ) - 2]; for( int i = 0; i < signatures.Length; ++i ) { signatures[i] = translator.FindType( LuaLib.lua_tostring( luaState, i + 3 ).ToString() ); } try { MethodInfo method = klass.GetMethod( methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, signatures ); translator.PushFunction( luaState, new LuaCSFunction( ( new LuaMethodWrapper( translator, target, klass, method ) ).InvokeFunction ) ); } catch( Exception e ) { translator.ThrowError( luaState, e ); LuaLib.lua_pushnil( luaState ); } return 1; } // Implementation of get_constructor_bysig( obj, "paramType1", ... ) // Returns nil if no matching constructor is found [MonoPInvokeCallback( typeof( LuaCSFunction ) )] static int GetConstructorSignature( IntPtr luaState ) { ObjectTranslator translator = Lua.GetObjectTranslator( luaState ); ProxyType klass = null; int udata = LuaLib.luanet_checkudata( luaState, 1, "luaNet_class" ); if( udata != -1 ) { klass = (ProxyType)translator._objects[udata]; } if( klass == null ) { translator.ThrowError( luaState, "get_constructor_bysig: first arg is invalid type reference" ); } var signature = new Type[LuaLib.lua_gettop( luaState ) - 1]; for( int i = 0; i < signature.Length; ++i ) { signature[i] = translator.FindType( LuaLib.lua_tostring( luaState, i + 2 ).ToString() ); } try { ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor( signature ); translator.PushFunction( luaState, new LuaCSFunction( ( new LuaMethodWrapper( translator, null, klass, constructor ) ).InvokeFunction ) ); } catch( Exception e ) { translator.ThrowError( luaState, e ); LuaLib.lua_pushnil( luaState ); } return 1; } // Implementation of ctype( obj ) [MonoPInvokeCallback( typeof( LuaCSFunction ) )] static int _CType( IntPtr luaState ) { var translator = Lua.GetObjectTranslator( luaState ); Type t = translator._TypeOf( luaState, 1 ); if( t == null ) { return translator.PushError( luaState, "Not a CLR Class" ); } translator.PushObject( luaState, t, "luaNet_metatable" ); return 1; } // Implementation of enum( "enumType", "enumValue, ..." ) [MonoPInvokeCallback( typeof( LuaCSFunction ) )] static int _EnumFromIntOrString( IntPtr luaState ) { ObjectTranslator translator = Lua.GetObjectTranslator( luaState ); Type t = translator._TypeOf( luaState, 1 ); if( t == null || !t.IsEnum() ) { return translator.PushError( luaState, "Not an Enum." ); } object res = null; LuaTypes lt = LuaLib.lua_type( luaState, 2 ); if( lt == LuaTypes.LUA_TNUMBER ) { int ival = (int)LuaLib.lua_tonumber( luaState, 2 ); res = Enum.ToObject( t, ival ); } else if( lt == LuaTypes.LUA_TSTRING ) { string sflags = LuaLib.lua_tostring( luaState, 2 ); try { res = Enum.Parse( t, sflags, true ); } catch( ArgumentException e ) { return translator.PushError( luaState, e.Message ); } } else { return translator.PushError( luaState, "Second argument must be a integer or a string." ); } translator.PushObject( luaState, res, "luaNet_metatable" ); return 1; } Type _TypeOf( IntPtr luaState, int idx ) { int udata = LuaLib.luanet_checkudata( luaState, 1, "luaNet_class" ); if( udata == -1 ) return null; ProxyType pt = (ProxyType)_objects[udata]; return pt.UnderlyingSystemType; } //-------------------------------------------------------------------------------------------------------------- // FindType // PushType // PushFunction // PushObject // GetAsType // CollectObject // // GetObject // GetFunction // GetTable // GetUserData // GetNetObject // GetRawNetObject // PopValues // Push // // MatchParameters // TableToArray //-------------------------------------------------------------------------------------------------------------- public Type FindType( string className ) { foreach( var assembly in _assemblies ) { var klass = assembly.GetType( className ); if( klass != null ) return klass; } return null; } // Pushes a type reference into the stack public void PushType( IntPtr luaState, Type t ) { PushObject( luaState, new ProxyType( t ), "luaNet_class" ); } // Pushes a delegate into the stack public void PushFunction( IntPtr luaState, LuaCSFunction func ) { PushObject( luaState, func, "luaNet_function" ); } // Pushes a CLR object into the Lua stack as an userdata with the provided metatable public void PushObject( IntPtr luaState, object o, string metatable ) { // Pushes nil if( o == null ) { LuaLib.lua_pushnil( luaState ); return; } int index = -1; // Object already in the list of Lua objects? Push the stored reference bool found = ( !o.GetType().IsValueType || o.GetType().IsEnum ) && _objectsBackward.TryGetValue( o, out index ); if( found ) { LuaLib.luaL_getmetatable( luaState, "luaNet_objects" ); LuaLib.lua_rawgeti( luaState, -1, index ); // Note: // Starting with lua5.1 the garbage collector may remove weak reference items (such as our // luaNet_objects values) when the initial GC sweep occurs, but the actual call of the __gc finalizer // for that object may not happen until a little while later // During that window we might call this routine and find the element missing from luaNet_objects, but // collectObject() has not yet been called // In that case, we go ahead and call collect object here // Did we find a non nil object in our table? if not, we need to call collect object var type = LuaLib.lua_type( luaState, -1 ); if( type != LuaTypes.LUA_TNIL ) { LuaLib.lua_remove( luaState, -2 ); // Drop the metatable - we're going to leave our object on the stack return; } // MetaFunctions.dumpStack(this, luaState); LuaLib.lua_remove( luaState, -1 ); // Remove the nil object value LuaLib.lua_remove( luaState, -1 ); // Remove the metatable _CollectObject( o, index ); // Remove from both our tables and fall out to get a new ID } index = _AddObject( o ); _PushNewObject( luaState, o, index, metatable ); } int _AddObject( object obj ) { // New object: inserts it in the list int index = _nextObjectIndex++; _objects[index] = obj; if( !obj.GetType().IsValueType || obj.GetType().IsValueType ) { _objectsBackward[obj] = index; } return index; } // Pushes a new object into the Lua stack with the provided metatable void _PushNewObject( IntPtr luaState, object o, int index, string metatable ) { if( metatable == "luaNet_metatable" ) { // Gets or creates the metatable for the object's type LuaLib.luaL_getmetatable( luaState, o.GetType().AssemblyQualifiedName ); // mt if( LuaLib.lua_isnil( luaState, -1 ) ) { LuaLib.lua_settop( luaState, -2 ); // LuaLib.luaL_newmetatable( luaState, o.GetType().AssemblyQualifiedName ); // mt LuaLib.lua_pushstring( luaState, "cache" ); // mt|s LuaLib.lua_newtable( luaState ); // mt|s|t LuaLib.lua_rawset( luaState, -3 ); // mt LuaLib.lua_pushlightuserdata( luaState, LuaLib.luanet_gettag() ); // mt|lud LuaLib.lua_pushnumber( luaState, 1 ); // mt|lud|n LuaLib.lua_rawset( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__index" ); // mt|s LuaLib.lua_pushstring( luaState, "luaNet_indexfunction" ); // mt|s|s LuaLib.lua_rawget( luaState, LuaIndexes.LUA_REGISTRYINDEX ); // mt|s|cf LuaLib.lua_rawset( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__gc" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.GcFunction ); // mt|s|cf LuaLib.lua_rawset( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__tostring" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ToStringFunction ); // mt|s|cf LuaLib.lua_rawset( luaState, -3 ); // mt LuaLib.lua_pushstring( luaState, "__newindex" ); // mt|s LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.NewIndexFunction ); // mt|s|cf LuaLib.lua_rawset( luaState, -3 ); // mt // Bind C# operator with Lua metamethods (__add, __sub, __mul) _RegisterOperatorsFunctions( luaState, o.GetType() ); } } else { LuaLib.luaL_getmetatable( luaState, metatable ); // mt } // Stores the object index in the Lua list and pushes the index into the Lua stack LuaLib.luaL_getmetatable( luaState, "luaNet_objects" ); // mt|mt2 LuaLib.luanet_newudata( luaState, index ); // mt|mt2|ud LuaLib.lua_pushvalue( luaState, -3 ); // mt|mt2|ud|mt LuaLib.lua_remove( luaState, -4 ); // mt2|ud|mt LuaLib.lua_setmetatable( luaState, -2 ); // mt2|ud LuaLib.lua_pushvalue( luaState, -1 ); // mt2|ud|ud LuaLib.lua_rawseti( luaState, -3, index ); // mt2|ud LuaLib.lua_remove( luaState, -2 ); // ud } void _RegisterOperatorsFunctions( IntPtr luaState, Type type ) { if( type.HasAdditionOpertator() ) { LuaLib.lua_pushstring( luaState, "__add" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.AddFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasSubtractionOpertator() ) { LuaLib.lua_pushstring( luaState, "__sub" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.SubtractFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasMultiplyOpertator() ) { LuaLib.lua_pushstring( luaState, "__mul" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.MultiplyFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasDivisionOpertator() ) { LuaLib.lua_pushstring( luaState, "__div" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.DivisionFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasModulusOpertator() ) { LuaLib.lua_pushstring( luaState, "__mod" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.ModulosFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasUnaryNegationOpertator() ) { LuaLib.lua_pushstring( luaState, "__unm" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.UnaryNegationFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasEqualityOpertator() ) { LuaLib.lua_pushstring( luaState, "__eq" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.EqualFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasLessThanOpertator() ) { LuaLib.lua_pushstring( luaState, "__lt" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.LessThanFunction ); LuaLib.lua_rawset( luaState, -3 ); } if( type.HasLessThanOrEqualOpertator() ) { LuaLib.lua_pushstring( luaState, "__le" ); LuaLib.lua_pushstdcallcfunction( luaState, MetaFunctions.LessThanOrEqualFunction ); LuaLib.lua_rawset( luaState, -3 ); } } // Gets an object from the Lua stack with the desired type if it matches, otherwise returns null public object GetAsType( IntPtr luaState, int stackPos, Type paramType ) { ValueExtractor extractor = TypeChecker.CheckLuaType( luaState, stackPos, paramType ); return extractor != null ? extractor( luaState, stackPos ) : null; } // Given the Lua int ID for an object, remove it from our maps public void CollectObject( int udata ) { object o; bool found = _objects.TryGetValue( udata, out o ); // The other variant of collectObject might have gotten here first, in that case we will silently ignore the missing entry if( found ) { _CollectObject( o, udata ); } } // Given an object reference, remove it from our maps void _CollectObject( object o, int udata ) { _objects.Remove( udata ); if( !o.GetType().IsValueType || o.GetType().IsEnum ) { _objectsBackward.Remove( o ); } } // Gets an object from the Lua stack according to its Lua type public object GetObject( IntPtr luaState, int index ) { var type = LuaLib.lua_type( luaState, index ); switch( type ) { case LuaTypes.LUA_TNUMBER: { return LuaLib.lua_tonumber( luaState, index ); } case LuaTypes.LUA_TSTRING: { return LuaLib.lua_tostring( luaState, index ); } case LuaTypes.LUA_TBOOLEAN: { return LuaLib.lua_toboolean( luaState, index ); } case LuaTypes.LUA_TTABLE: { return GetTable( luaState, index ); } case LuaTypes.LUA_TFUNCTION: { return GetFunction( luaState, index ); } case LuaTypes.LUA_TUSERDATA: { int udata = LuaLib.luanet_tonetobject( luaState, index ); return udata != -1 ? _objects[udata] : GetUserData( luaState, index ); } default: return null; } } // Gets the function in the index positon of the Lua stack public LuaFunction GetFunction( IntPtr luaState, int index ) { LuaLib.lua_pushvalue( luaState, index ); int reference = LuaLib.luaL_ref( luaState, LuaIndexes.LUA_REGISTRYINDEX ); if( reference == -1 ) return null; return new LuaFunction( reference, Interpreter ); } // Gets the table in the index positon of the Lua stack public LuaTable GetTable( IntPtr luaState, int index ) { LuaLib.lua_pushvalue( luaState, index ); int reference = LuaLib.luaL_ref( luaState, LuaIndexes.LUA_REGISTRYINDEX ); if( reference == -1 ) return null; return new LuaTable( reference, Interpreter ); } // Gets the userdata in the index positon of the Lua stack public LuaUserData GetUserData( IntPtr luaState, int index ) { LuaLib.lua_pushvalue( luaState, index ); int reference = LuaLib.luaL_ref( luaState, LuaIndexes.LUA_REGISTRYINDEX ); if( reference == -1 ) return null; return new LuaUserData( reference, Interpreter ); } // Gets the CLR object in the index positon of the Lua stack // Returns delegates as Lua functions public object GetNetObject( IntPtr luaState, int index ) { int idx = LuaLib.luanet_tonetobject( luaState, index ); return idx != -1 ? _objects[idx] : null; } // Gets the CLR object in the index position of the Lua stack // Returns delegates as is public object GetRawNetObject( IntPtr luaState, int index ) { int udata = LuaLib.luanet_rawnetobj( luaState, index ); return udata != -1 ? _objects[udata] : null; } // Gets the values from the provided index to the top of the stack and returns them in an array public object[] PopValues( IntPtr luaState, int oldTop ) { int newTop = LuaLib.lua_gettop( luaState ); if( oldTop == newTop ) { return null; } else { var returnValues = new List<object>(); for( int i = oldTop + 1; i <= newTop; ++i ) { returnValues.Add( GetObject( luaState, i ) ); } LuaLib.lua_settop( luaState, oldTop ); return returnValues.ToArray(); } } // Gets the values from the provided index to the top of the stack and returns them in an array, // casting them to the provided types public object[] PopValues( IntPtr luaState, int oldTop, Type[] popTypes ) { int newTop = LuaLib.lua_gettop( luaState ); if( oldTop == newTop ) { return null; } else { int iTypes; var returnValues = new List<object>(); if( popTypes[0] == typeof( void ) ) iTypes = 1; else iTypes = 0; for( int i = oldTop + 1; i <= newTop; ++i ) { returnValues.Add( GetAsType( luaState, i, popTypes[iTypes] ) ); ++iTypes; } LuaLib.lua_settop( luaState, oldTop ); return returnValues.ToArray(); } } // Pushes the object into the Lua stack according to its type public void Push( IntPtr luaState, object o ) { if( o == null ) { LuaLib.lua_pushnil( luaState ); } else if( o is GameObject && (GameObject)o == null ) { LuaLib.lua_pushnil( luaState ); } else if( o is sbyte || o is byte || o is short || o is ushort || o is int || o is uint || o is long || o is float || o is ulong || o is decimal || o is double ) { double d = Convert.ToDouble( o ); LuaLib.lua_pushnumber( luaState, d ); } else if( o is char ) { double d = (char)o; LuaLib.lua_pushnumber( luaState, d ); } else if( o is string ) { string str = (string)o; LuaLib.lua_pushstring( luaState, str ); } else if( o is bool ) { bool b = (bool)o; LuaLib.lua_pushboolean( luaState, b ); } else if( o is LuaTable ) { ( (LuaTable)o ).Push( luaState ); } else if( o is LuaCSFunction ) { PushFunction( luaState, (LuaCSFunction)o ); } else if( o is LuaFunction ) { ( (LuaFunction)o ).Push( luaState ); } else { PushObject( luaState, o, "luaNet_metatable" ); } } // Checks if the method matches the arguments in the Lua stack, getting the arguments if it does public bool MatchParameters( IntPtr luaState, MethodBase method, ref MethodCache methodCache ) { ValueExtractor extractValue; bool isMethod = true; var paramInfo = method.GetParameters(); int currentLuaParam = 1; int nLuaParams = LuaLib.lua_gettop( luaState ); var paramList = new List<object>(); var outList = new List<int>(); var argTypes = new List<MethodArgs>(); foreach( var currentNetParam in paramInfo ) { // Skips out params if( !currentNetParam.IsIn && currentNetParam.IsOut ) { int index = paramList.Count; paramList.Add( null ); outList.Add( index ); } // Type checking else if( _IsTypeCorrect( luaState, currentLuaParam, currentNetParam, out extractValue ) ) { int index = paramList.Count; paramList.Add( extractValue( luaState, currentLuaParam ) ); var methodArg = new MethodArgs(); methodArg.Index = index; methodArg.ExtractValue = extractValue; argTypes.Add( methodArg ); if( currentNetParam.ParameterType.IsByRef ) { outList.Add( index ); } ++currentLuaParam; } // Type does not match, ignore if the parameter is optional else if( _IsParamsArray( luaState, nLuaParams, currentLuaParam, currentNetParam, out extractValue ) ) { int count = ( nLuaParams - currentLuaParam ) + 1; Type paramArrayType = currentNetParam.ParameterType.GetElementType(); Func<int, object> extractDelegate = ( currentParam ) => { ++currentLuaParam; return extractValue( luaState, currentParam ); }; int index = paramList.Count; Array paramArray = TableToArray( extractDelegate, paramArrayType, currentLuaParam, count ); paramList.Add( paramArray ); var methodArg = new MethodArgs(); methodArg.Index = index; methodArg.ExtractValue = extractValue; methodArg.IsParamsArray = true; methodArg.ParamsArrayType = paramArrayType; argTypes.Add( methodArg ); } // Adds optional parameters else if( currentLuaParam > nLuaParams ) { if( currentNetParam.IsOptional ) { paramList.Add( currentNetParam.DefaultValue ); } else { isMethod = false; break; } } else if( currentNetParam.IsOptional ) { paramList.Add( currentNetParam.DefaultValue ); } // No match else { isMethod = false; break; } } // Number of parameters does not match if( currentLuaParam != nLuaParams + 1 ) { isMethod = false; } if( isMethod ) { methodCache.Args = paramList.ToArray(); methodCache.CachedMethod = method; methodCache.OutList = outList.ToArray(); methodCache.ArgTypes = argTypes.ToArray(); } return isMethod; } // Returns true if the type is set and assigns the extract value bool _IsTypeCorrect( IntPtr luaState, int currentLuaParam, ParameterInfo currentNetParam, out ValueExtractor extractValue ) { try { extractValue = TypeChecker.CheckLuaType( luaState, currentLuaParam, currentNetParam.ParameterType ); return ( extractValue != null ); } catch { extractValue = null; Debug.LogError( "Type wasn't correct" ); return false; } } bool _IsParamsArray( IntPtr luaState, int nLuaParams, int currentLuaParam, ParameterInfo currentNetParam, out ValueExtractor extractValue ) { bool isParamArray = false; extractValue = null; if( currentNetParam.GetCustomAttributes( typeof( ParamArrayAttribute ), false ).Length > 0 ) { isParamArray = nLuaParams < currentLuaParam; LuaTypes luaType; try { luaType = LuaLib.lua_type( luaState, currentLuaParam ); } catch( Exception ex ) { Debug.LogError( "Could not retrieve lua type while attempting to determine params Array Status." ); Debug.LogError( ex.Message ); return false; } if( luaType == LuaTypes.LUA_TTABLE ) { try { extractValue = TypeChecker.GetExtractor( typeof( LuaTable ) ); } catch( Exception ) { Debug.LogError( "An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status." ); } if( extractValue != null ) { return true; } } else { Type paramElementType = currentNetParam.ParameterType.GetElementType(); try { extractValue = TypeChecker.CheckLuaType( luaState, currentLuaParam, paramElementType ); } catch( Exception ) { Debug.LogError( string.Format( "An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName ) ); } if( extractValue != null ) { return true; } } } return isParamArray; } public Array TableToArray( Func<int, object> luaParamValueExtractor, Type paramArrayType, int startIndex, int count ) { Array paramArray; if( count == 0 ) { return Array.CreateInstance( paramArrayType, 0 ); } object luaParamValue = luaParamValueExtractor( startIndex ); if( luaParamValue is LuaTable ) { LuaTable table = (LuaTable)luaParamValue; paramArray = Array.CreateInstance( paramArrayType, table.Values.Count ); IDictionaryEnumerator tableEnumerator = table.GetEnumerator(); tableEnumerator.Reset(); int paramArrayIndex = 0; while( tableEnumerator.MoveNext() ) { object value = tableEnumerator.Value; if( paramArrayType == typeof( object ) ) { if( value != null && value.GetType() == typeof( double ) && _IsInteger( (double)value ) ) { value = Convert.ToInt32( (double)value ); } } paramArray.SetValue( Convert.ChangeType( value, paramArrayType ), paramArrayIndex ); ++paramArrayIndex; } } else { paramArray = Array.CreateInstance( paramArrayType, count ); paramArray.SetValue( luaParamValue, 0 ); for( int i = 1; i < count; ++i ) { ++startIndex; object value = luaParamValueExtractor( startIndex ); paramArray.SetValue( value, i ); } } return paramArray; } static bool _IsInteger( double x ) { return Math.Ceiling( x ) == x; } // Passes errors (argument e) to the Lua interpreter public void ThrowError( IntPtr luaState, object e ) { // We use this to remove anything pushed by luaL_where int oldTop = LuaLib.lua_gettop( luaState ); // Stack frame #1 is our C# wrapper, so not very interesting to the user // Stack frame #2 must be the lua code that called us, so that's what we want to use LuaLib.luaL_where( luaState, 1 ); var curlev = PopValues( luaState, oldTop ); // Determine the position in the script where the exception was triggered string errLocation = string.Empty; if( curlev.Length > 0 ) { errLocation = curlev[0].ToString(); } string message = e as string; if( message != null ) { // Wrap Lua error (just a string) and store the error location e = new LuaScriptException( message, errLocation ); } else { Exception ex = e as Exception; if( ex != null ) { // Wrap generic .NET exception as an InnerException and store the error location e = new LuaScriptException( ex, errLocation ); } } Push( luaState, e ); LuaLib.lua_error( luaState ); } public int PushError( IntPtr luaState, string msg ) { LuaLib.lua_pushnil( luaState ); LuaLib.lua_pushstring( luaState, msg ); return 2; } // Debug tool to dump the lua stack public static void DumpStack( ObjectTranslator translator, IntPtr luaState ) { int depth = LuaLib.lua_gettop( luaState ); Debug.Log( string.Format( "Lua stack depth: {0}", depth ) ); for( int i = 1; i <= depth; ++i ) { LuaTypes type = LuaLib.lua_type( luaState, i ); // We dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, // so manually check for key types string typestr = ( type == LuaTypes.LUA_TTABLE ) ? "table" : LuaLib.lua_typename( luaState, type ); string strrep = LuaLib.lua_tostring( luaState, i ).ToString(); if( type == LuaTypes.LUA_TUSERDATA ) { object obj = translator.GetRawNetObject( luaState, i ); strrep = obj.ToString(); } Debug.Log( string.Format( "{0}: ({1}) {2}", i, typestr, strrep ) ); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService { /// <summary> /// A local resource that is offered by an SMB 2.0 Protocol server for /// access by SMB 2.0 Protocol clients over the network. The SMB 2.0 /// Protocol defines three types of shares: file (or disk) shares, /// which represent a directory tree and its included files; pipe /// shares, which expose access to named pipes; and print shares, /// which provide access to print resources on the server. A pipe /// share as defined by the SMB 2.0 Protocol MUST always have the /// name "IPC$". A pipe share MUST only allow named pipe operations /// and DFS referral requests to itself. /// </summary> public class Share { #region fields private int globalIndex; private string name; private string localPath; private long connectSecurity; private long fileSecurity; private long cscFlags; private bool isDfs; private bool doAccessBasedDirectoryEnumeration; private bool allowNamespaceCaching; private bool forceSharedDelete; private bool restrictExclusiveOpens; #endregion #region properties /// <summary> /// A global integer index in the Global Table of Context. It is be global unique. The value is 1 /// for the first instance, and it always increases by 1 when a new instance is created. /// </summary> public int GlobalIndex { get { return this.globalIndex; } set { this.globalIndex = value; } } /// <summary> /// A unique name for the shared resource on this server. /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// A path that describes the local resource that is being shared. This MUST be a store that either /// provides named pipe functionality, or that offers storage and/or retrieval of files. In the case /// of the latter, it MAY be a device that accepts a file and then processes it in some format, such /// as a printer. /// </summary> public string LocalPath { get { return this.localPath; } set { this.localPath = value; } } /// <summary> /// An authorization policy such as an access control list that describes which users are allowed /// to connect to this share. /// </summary> public long ConnectSecurity { get { return this.connectSecurity; } set { this.connectSecurity = value; } } /// <summary> /// An authorization policy such as an access control list that describes what actions users that /// connect to this share are allowed to perform on the shared resource. /// </summary> public long FileSecurity { get { return this.fileSecurity; } set { this.fileSecurity = value; } } /// <summary> /// The configured offline caching policy for this share. This value MUST be manual caching, /// automatic caching of files, automatic caching of files and programs, or no offline caching. /// For more information, see section 2.2.10. For more information about offline caching, see [OFFLINE]. /// </summary> public long CscFlags { get { return this.cscFlags; } set { this.cscFlags = value; } } /// <summary> /// A Boolean that, if set, indicates that this share is configured for DFS. For more information, /// see [MSDFS]. /// </summary> public bool IsDfs { get { return this.isDfs; } set { this.isDfs = value; } } /// <summary> /// A Boolean that, if set, indicates that the results of directory enumerations on this share /// must be trimmed to include only the files and directories that the calling user has access to. /// </summary> public bool DoAccessBasedDirectoryEnumeration { get { return this.doAccessBasedDirectoryEnumeration; } set { this.doAccessBasedDirectoryEnumeration = value; } } /// <summary> /// A Boolean that, if set, indicates that clients are allowed to cache directory enumeration /// results for better performance. /// </summary> public bool AllowNamespaceCaching { get { return this.allowNamespaceCaching; } set { this.allowNamespaceCaching = value; } } /// <summary> /// A Boolean that, if set, indicates that all opens on this share MUST include FILE_SHARE_DELETE /// in the sharing access. /// </summary> public bool ForceSharedDelete { get { return this.forceSharedDelete; } set { this.forceSharedDelete = value; } } /// <summary> /// A Boolean that, if set, indicates that users who request read-only access to a file /// are not allowed to deny other readers. /// </summary> public bool RestrictExclusiveOpens { get { return this.restrictExclusiveOpens; } set { this.restrictExclusiveOpens = value; } } #endregion #region constructor /// <summary> /// Constructor. /// </summary> public Share() { this.GlobalIndex = 0; this.Name = ""; this.LocalPath = ""; this.ConnectSecurity = 0; this.FileSecurity = 0; this.CscFlags = 0; this.IsDfs = false; this.DoAccessBasedDirectoryEnumeration = false; this.AllowNamespaceCaching = false; this.ForceSharedDelete = false; this.RestrictExclusiveOpens = false; } /// <summary> /// Deep copy constructor. /// </summary> public Share(Share share) { if (share != null) { this.GlobalIndex = share.GlobalIndex; this.Name = share.Name; this.LocalPath = share.LocalPath; this.ConnectSecurity = share.ConnectSecurity; this.FileSecurity = share.FileSecurity; this.CscFlags = share.CscFlags; this.IsDfs = share.IsDfs; this.DoAccessBasedDirectoryEnumeration = share.DoAccessBasedDirectoryEnumeration; this.AllowNamespaceCaching = share.AllowNamespaceCaching; this.ForceSharedDelete = share.ForceSharedDelete; this.RestrictExclusiveOpens = share.RestrictExclusiveOpens; } else { this.GlobalIndex = 0; this.Name = ""; this.LocalPath = ""; this.ConnectSecurity = 0; this.FileSecurity = 0; this.CscFlags = 0; this.IsDfs = false; this.DoAccessBasedDirectoryEnumeration = false; this.AllowNamespaceCaching = false; this.ForceSharedDelete = false; this.RestrictExclusiveOpens = false; } } #endregion } }