context
stringlengths
2.52k
185k
gt
stringclasses
1 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; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal.Commands; #if ASYNC using System.Threading.Tasks; #endif namespace NUnit.Framework.Internal { /// <summary> /// TestSuite represents a composite test, which contains other tests. /// </summary> public class TestSuite : Test { #region Fields /// <summary> /// Our collection of child tests /// </summary> private List<ITest> tests = new List<ITest>(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="name">The name of the suite.</param> public TestSuite(string name) : base(name) { Arguments = new object[0]; } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="parentSuiteName">Name of the parent suite.</param> /// <param name="name">The name of the suite.</param> public TestSuite(string parentSuiteName, string name) : base(parentSuiteName, name) { Arguments = new object[0]; } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="fixtureType">Type of the fixture.</param> public TestSuite(ITypeInfo fixtureType) : base(fixtureType) { Arguments = new object[0]; } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="fixtureType">Type of the fixture.</param> public TestSuite(Type fixtureType) : base(new TypeWrapper(fixtureType)) { Arguments = new object[0]; } #endregion #region Public Methods /// <summary> /// Sorts tests under this suite. /// </summary> public void Sort() { if (!MaintainTestOrder) { this.tests.Sort(); foreach (Test test in Tests) { TestSuite suite = test as TestSuite; if (suite != null) suite.Sort(); } } } #if false /// <summary> /// Sorts tests under this suite using the specified comparer. /// </summary> /// <param name="comparer">The comparer.</param> public void Sort(IComparer comparer) { this.tests.Sort(comparer); foreach( Test test in Tests ) { TestSuite suite = test as TestSuite; if ( suite != null ) suite.Sort(comparer); } } #endif /// <summary> /// Adds a test to the suite. /// </summary> /// <param name="test">The test.</param> public void Add(Test test) { test.Parent = this; tests.Add(test); } #endregion #region Properties /// <summary> /// Gets this test's child tests /// </summary> /// <value>The list of child tests</value> public override IList<ITest> Tests { get { return tests; } } /// <summary> /// Gets a count of test cases represented by /// or contained under this test. /// </summary> /// <value></value> public override int TestCaseCount { get { int count = 0; foreach (Test test in Tests) { count += test.TestCaseCount; } return count; } } /// <summary> /// The arguments to use in creating the fixture /// </summary> public object[] Arguments { get; internal set; } /// <summary> /// Set to true to suppress sorting this suite's contents /// </summary> protected bool MaintainTestOrder { get; set; } #endregion #region Test Overrides /// <summary> /// Overridden to return a TestSuiteResult. /// </summary> /// <returns>A TestResult for this test.</returns> public override TestResult MakeTestResult() { return new TestSuiteResult(this); } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public override bool HasChildren { get { return tests.Count > 0; } } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public override string XmlElementName { get { return "test-suite"; } } /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public override TNode AddToXml(TNode parentNode, bool recursive) { TNode thisNode = parentNode.AddElement("test-suite"); thisNode.AddAttribute("type", this.TestType); PopulateTestNode(thisNode, recursive); thisNode.AddAttribute("testcasecount", this.TestCaseCount.ToString()); if (recursive) foreach (Test test in this.Tests) test.AddToXml(thisNode, recursive); return thisNode; } #endregion #region Helper Methods /// <summary> /// Check that setup and teardown methods marked by certain attributes /// meet NUnit's requirements and mark the tests not runnable otherwise. /// </summary> /// <param name="attrType">The attribute type to check for</param> protected void CheckSetUpTearDownMethods(Type attrType) { foreach (MethodInfo method in Reflect.GetMethodsWithAttribute(TypeInfo.Type, attrType, true)) if (method.IsAbstract || !method.IsPublic && !method.IsFamily || method.GetParameters().Length > 0 || method.ReturnType != typeof(void) #if ASYNC && method.ReturnType != typeof(Task) #endif ) { this.MakeInvalid(string.Format("Invalid signature for SetUp or TearDown method: {0}", method.Name)); break; } } #endregion } }
using Newtonsoft.Json; using reactive_download.Models; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Linq; namespace reactive_download.Helper { internal class ReportEngine { public ReportEngine(Report Report, APIEndpoints apiEndPoint) { _apiEndPoint = apiEndPoint; this._report = Report; } private Report _report; private const string CONTENT_TYPE = "application/json"; private readonly APIEndpoints _apiEndPoint; private const int START_INDEX_FROM = 0; const int INITIAL_PAYLOAD = 100;//minimum number of records to get from api. const int MAX_PAYLOAD = 1000; const int THREESHOLD = 30;//seconds private const int DOWNLOAD_PAGE_SIZE = 1000; internal int? getCurrentModelTotalRecords => _report.TotalRecords; /// <summary> /// Get data for specified reports (calls report API). /// </summary> /// <returns>DatTable structure (to be serialized in Json format before returning from Ajax call to DataTables plugin)</returns> /// <remarks> /// Created By: Mohamed Abdo /// Date: 08 Jan 2017 /// </remarks> public async Task<List<DataTable>> GetDownloadData(HttpRequestBase httpRequest, int? limitDownloadRecords = null) { string httpMessage = string.Empty; Func<int, int> getDownloadPageSize = (totalRecords) => { return DOWNLOAD_PAGE_SIZE; }; int pagesize = getDownloadPageSize(_report.TotalRecords); try { // Call API... var reportApiClient = GetReportStatsHttpClient(httpRequest, limitDownloadRecords); int startFrom = START_INDEX_FROM; List<DataTable> dataset = new List<DataTable>(); while (startFrom < _report.TotalRecords) { var reportApiresponse = await reportApiClient.GetAsync( $"{_apiEndPoint.Data}?pagesize={pagesize}&startFrom={startFrom}"); var responseModel = Utilities.GetHttpModel<IEnumerable<Employee>>(reportApiresponse, out httpMessage); var dataTable = BuildDataTable(responseModel .Select(TransformToDownloadView) .Select(TransformToRow)); dataset.Add(dataTable); startFrom += pagesize; } return await Task.FromResult(dataset); } catch (Exception ex) when (!(ex is UiException)) { //CommonItems.Logger?.ErrorException(ex, $"Error occurred while getting data for download report, {httpMessage}"); throw new UiException("GenericException"); } } public IEnumerable<Task<DataTable>> GetDownloadDataAsync(HttpClient reportStatusCleint, HttpRequestBase httpRequest) { const int TIME_OUT = 3; double? responseInSeconds = null; int currentpagesize = 0; var cancellationToken = new CancellationTokenSource(TimeSpan.FromHours(TIME_OUT)); string httpMessage = string.Empty; int startFrom = START_INDEX_FROM; int idx = 0; while (startFrom < _report.TotalRecords) { currentpagesize = getDownloadPageSize(_report.TotalRecords, currentpagesize, responseInSeconds); #if DEBUG System.Diagnostics.Debug.Print("Begin Call Report API => index => {0}, startFrom =>{1}, pagesize=>{2}, url=>{3}, snapshot=> {4}, at=> {5}", idx++, startFrom, currentpagesize, $"{_apiEndPoint.Data}?startFrom={startFrom}&pagesize={currentpagesize}", _report.Criteria, DateTime.Now.ToString()); #endif var startTime = Stopwatch.StartNew(); yield return reportStatusCleint.GetAsync( $"{_apiEndPoint.Data}?startFrom={startFrom}&pagesize={currentpagesize}", cancellationToken.Token).ContinueWith(responseTask => { startTime.Stop(); responseInSeconds = startTime.Elapsed.TotalSeconds; #if DEBUG System.Diagnostics.Debug.Print("End Call Report API => index => {0}, duration in sec. => {1}, startFrom =>{2}, pagesize=>{3}, url=>{4}, snapshot=> {5}, at=> {6}", idx++, responseInSeconds, startFrom, currentpagesize, $"{_apiEndPoint.Data}?startFrom={startFrom}&pagesize={currentpagesize}", _report.Criteria, DateTime.Now.ToString()); #endif startFrom += currentpagesize; return GetDataTableFromResponseAsync(responseTask.Result, cancellationToken.Token).ContinueWith(transformationTask => { return transformationTask.Result; }).Result; }); } } public Task GetDownloadDataAsync(HttpClient reportStatusCleint, HttpRequestBase httpRequest, int startFrom, int pagesize, Action<HttpResponseMessage> responseCallBack) { const int TIME_OUT = 3; double? responseInSeconds = null; var cancellationToken = new CancellationTokenSource(TimeSpan.FromHours(TIME_OUT)); string httpMessage = string.Empty; #if DEBUG System.Diagnostics.Debug.Print("Begin Call Report API => startFrom =>{0}, pagesize=>{1}, url=>{2}, snapshot=> {3}, at=> {4}", startFrom, pagesize, $"{_apiEndPoint.Data}?pagesize={pagesize}&startFrom={startFrom}", _report.Criteria, DateTime.Now.ToString()); #endif var startTime = Stopwatch.StartNew(); return reportStatusCleint.GetAsync( $"{_apiEndPoint.Data}?pagesize={pagesize}&startFrom={startFrom}", cancellationToken.Token).ContinueWith(responsetask => { startTime.Stop(); responseInSeconds = startTime.Elapsed.TotalSeconds; #if DEBUG Debug.Print("End Call Report API => duration in sec. => {0}, startFrom =>{1}, pagesize=>{2}, url=>{3}, snapshot=> {4}, at=> {5}", responseInSeconds, startFrom, pagesize, $"{_apiEndPoint.Data}?pagesize={pagesize}&startFrom={startFrom}", _report.Criteria, DateTime.Now.ToString()); #endif responseCallBack(responsetask.Result); }); } #region Helpers public Func<Employee, DownloadView> TransformToDownloadView = (emplpyee) => { if (emplpyee == null) return new DownloadView(); return new DownloadView() { Id = emplpyee.Id, EmployeId = emplpyee.EmployeeId, Bithdate = emplpyee.Bithdate, City = emplpyee.City, Country = emplpyee.Country, Gender = Enum.GetName(typeof(Gender), emplpyee.Gender), Mobile = emplpyee.Mobile, Name = emplpyee.Name, Organization = emplpyee.Organization?.Name, WorkingCountry = emplpyee.Organization?.Country, WorkingAddress = emplpyee.Organization?.Address }; }; public Func<DownloadView, object[]> TransformToRow = (dView) => { if (dView == null) return null; return dView.GetType().GetProperties().Select(prop => { return prop.GetValue(dView); }).ToArray(); }; public Func<IEnumerable<object[]>, DataTable> BuildDataTable = (rows) => { DataTable dt = new DataTable(); var colNum = rows.FirstOrDefault()?.Count() ?? 0; if (colNum == 0) return dt; Enumerable.Range(0, colNum).ToList().ForEach(ixd => { dt.Columns.Add(); }); foreach (var row in rows) { if (row == null) continue; dt.Rows.Add(row); } return dt; }; public Task<DataTable> GetDataTableFromResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken) { string httpMessage; var responseModel = Utilities.GetHttpModel<IEnumerable<Employee>>(response, out httpMessage); var dataTable = BuildDataTable(responseModel .Select(TransformToDownloadView) .Select(TransformToRow)); return Task.Factory.StartNew(() => { return dataTable; }, cancellationToken); } public DataTable GetDataTableFromResponse(HttpResponseMessage response) { string httpMessage; var responseModel = Utilities.GetHttpModel<IEnumerable<Employee>>(response, out httpMessage); var dataTable = BuildDataTable(responseModel .Select(TransformToDownloadView) .Select(TransformToRow)); return dataTable; } public HttpClient CreateClient(string baseUrl) { var httpClient = new HttpClient() { BaseAddress = new Uri(baseUrl) }; httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(CONTENT_TYPE)); return httpClient; } public HttpClient GetReportStatsHttpClient(HttpRequestBase httpRequest, int? limitDownloadRecords = null) { // Getting API client and check identity var userIdentity = HttpContext.Current.GetOwinContext().Authentication.User; var reportApiClient = CreateClient(_apiEndPoint.BaseUrl); if (string.IsNullOrEmpty(_report.Criteria)) // New request { // Submit request HttpResponseMessage reportApiresponse = reportApiClient.GetAsync( _apiEndPoint.Statistics).Result; if (!reportApiresponse.IsSuccessStatusCode) { reportApiresponse.EnsureSuccessStatusCode(); } string httpMessage; var responseModel = Utilities.GetHttpModel<ResultBreif>(reportApiresponse, out httpMessage); //TODO: remove overriding total records, in real cases this number should be controlled by back-end api, which refelcts how many records available for this request. if (limitDownloadRecords.HasValue) _report.TotalRecords = limitDownloadRecords.Value; else _report.TotalRecords = responseModel.TotalRecords; _report.ReportName = responseModel.ReportName; _report.Criteria = responseModel.Criteria; } return reportApiClient; } public static Func<int, int?, double?, int> getDownloadPageSize = (totalRecords, lastPayLoad, responseTime) => { var locker = new object(); lock (locker) { int proposdPayLoad = (int)((THREESHOLD / (responseTime ?? THREESHOLD)) * (lastPayLoad ?? INITIAL_PAYLOAD)); var minProposedPayLoad = Math.Min(proposdPayLoad, MAX_PAYLOAD); if (totalRecords <= INITIAL_PAYLOAD) return Math.Min(proposdPayLoad, totalRecords); return Math.Min(minProposedPayLoad, (totalRecords - INITIAL_PAYLOAD)); } }; public T getModelFromString<T>(string modelAsStr) { var nameValue = HttpUtility.ParseQueryString(modelAsStr); var modelAsJson = JsonConvert.SerializeObject(nameValue?.AllKeys.ToDictionary(k => k, k => nameValue[k])); return JsonConvert.DeserializeObject<T>(modelAsJson); } #endregion } }
#nullable enable using System; using Content.Server.Atmos; using Content.Server.Explosions; using Content.Server.GameObjects.Components.Body.Respiratory; using Content.Server.GameObjects.Components.GUI; using Content.Server.Interfaces; using Content.Server.Utility; using Content.Shared.Atmos; using Content.Shared.Audio; using Content.Shared.GameObjects.Components.Atmos.GasTank; using Content.Shared.GameObjects.Components.Inventory; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.GameObjects.Verbs; using Content.Shared.Interfaces.GameObjects.Components; using Content.Shared.Utility; using Robust.Server.GameObjects.Components.UserInterface; using Robust.Server.GameObjects.EntitySystems; using Robust.Server.Interfaces.GameObjects; using Robust.Server.Interfaces.Player; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameObjects.EntitySystemMessages; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Serialization; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Atmos { [RegisterComponent] [ComponentReference(typeof(IActivate))] public class GasTankComponent : SharedGasTankComponent, IExamine, IGasMixtureHolder, IUse, IDropped, IActivate { private const float MaxExplosionRange = 14f; private const float DefaultOutputPressure = Atmospherics.OneAtmosphere; private float _pressureResistance; private int _integrity = 3; [ViewVariables] private BoundUserInterface? _userInterface; [ViewVariables] public GasMixture? Air { get; set; } /// <summary> /// Distributed pressure. /// </summary> [ViewVariables] public float OutputPressure { get; private set; } /// <summary> /// Tank is connected to internals. /// </summary> [ViewVariables] public bool IsConnected { get; set; } /// <summary> /// Represents that tank is functional and can be connected to internals. /// </summary> public bool IsFunctional => GetInternalsComponent() != null; /// <summary> /// Pressure at which tanks start leaking. /// </summary> public float TankLeakPressure { get; set; } = 30 * Atmospherics.OneAtmosphere; /// <summary> /// Pressure at which tank spills all contents into atmosphere. /// </summary> public float TankRupturePressure { get; set; } = 40 * Atmospherics.OneAtmosphere; /// <summary> /// Base 3x3 explosion. /// </summary> public float TankFragmentPressure { get; set; } = 50 * Atmospherics.OneAtmosphere; /// <summary> /// Increases explosion for each scale kPa above threshold. /// </summary> public float TankFragmentScale { get; set; } = 10 * Atmospherics.OneAtmosphere; public override void Initialize() { base.Initialize(); _userInterface = Owner.GetUIOrNull(SharedGasTankUiKey.Key); if (_userInterface != null) { _userInterface.OnReceiveMessage += UserInterfaceOnOnReceiveMessage; } } public void OpenInterface(IPlayerSession session) { _userInterface?.Open(session); UpdateUserInterface(true); } public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(this, x => x.Air, "air", new GasMixture()); serializer.DataField(this, x => x.OutputPressure, "outputPressure", DefaultOutputPressure); serializer.DataField(this, x => x.TankLeakPressure, "tankLeakPressure", 30 * Atmospherics.OneAtmosphere); serializer.DataField(this, x => x.TankRupturePressure, "tankRupturePressure", 40 * Atmospherics.OneAtmosphere); serializer.DataField(this, x => x.TankFragmentPressure, "tankFragmentPressure", 50 * Atmospherics.OneAtmosphere); serializer.DataField(this, x => x.TankFragmentScale, "tankFragmentScale", 10 * Atmospherics.OneAtmosphere); serializer.DataField(ref _pressureResistance, "pressureResistance", Atmospherics.OneAtmosphere * 5f); } public void Examine(FormattedMessage message, bool inDetailsRange) { message.AddMarkup(Loc.GetString("Pressure: [color=orange]{0}[/color] kPa.\n", Math.Round(Air?.Pressure ?? 0))); if (IsConnected) { message.AddMarkup(Loc.GetString("Connected to external component")); } } protected override void Shutdown() { base.Shutdown(); DisconnectFromInternals(); } public void Update() { Air?.React(this); CheckStatus(); UpdateUserInterface(); } public GasMixture? RemoveAir(float amount) { var gas = Air?.Remove(amount); CheckStatus(); return gas; } public GasMixture RemoveAirVolume(float volume) { if (Air == null) return new GasMixture(volume); var tankPressure = Air.Pressure; if (tankPressure < OutputPressure) { OutputPressure = tankPressure; UpdateUserInterface(); } var molesNeeded = OutputPressure * volume / (Atmospherics.R * Air.Temperature); var air = RemoveAir(molesNeeded); if (air != null) air.Volume = volume; else return new GasMixture(volume); return air; } public bool UseEntity(UseEntityEventArgs eventArgs) { if (!eventArgs.User.TryGetComponent(out IActorComponent? actor)) return false; OpenInterface(actor.playerSession); return true; } public void Activate(ActivateEventArgs eventArgs) { if (!eventArgs.User.TryGetComponent(out IActorComponent? actor)) return; OpenInterface(actor.playerSession); } public void ConnectToInternals() { if (IsConnected || !IsFunctional) return; var internals = GetInternalsComponent(); if (internals == null) return; IsConnected = internals.TryConnectTank(Owner); UpdateUserInterface(); } public void DisconnectFromInternals(IEntity? owner = null) { if (!IsConnected) return; IsConnected = false; GetInternalsComponent(owner)?.DisconnectTank(); UpdateUserInterface(); } private void UpdateUserInterface(bool initialUpdate = false) { _userInterface?.SetState( new GasTankBoundUserInterfaceState { TankPressure = Air?.Pressure ?? 0, OutputPressure = initialUpdate ? OutputPressure : (float?) null, InternalsConnected = IsConnected, CanConnectInternals = IsFunctional && GetInternalsComponent() != null }); } private void UserInterfaceOnOnReceiveMessage(ServerBoundUserInterfaceMessage message) { switch (message.Message) { case GasTankSetPressureMessage msg: OutputPressure = msg.Pressure; break; case GasTankToggleInternalsMessage _: ToggleInternals(); break; } } private void ToggleInternals() { if (IsConnected) { DisconnectFromInternals(); return; } ConnectToInternals(); } private InternalsComponent? GetInternalsComponent(IEntity? owner = null) { if (owner != null) return owner.GetComponentOrNull<InternalsComponent>(); return Owner.TryGetContainer(out var container) ? container.Owner.GetComponentOrNull<InternalsComponent>() : null; } public void AssumeAir(GasMixture giver) { Air?.Merge(giver); CheckStatus(); } private void CheckStatus() { if (Air == null) return; var pressure = Air.Pressure; if (pressure > TankFragmentPressure) { // Give the gas a chance to build up more pressure. for (var i = 0; i < 3; i++) { Air.React(this); } pressure = Air.Pressure; var range = (pressure - TankFragmentPressure) / TankFragmentScale; // Let's cap the explosion, yeah? if (range > MaxExplosionRange) { range = MaxExplosionRange; } Owner.SpawnExplosion((int) (range * 0.25f), (int) (range * 0.5f), (int) (range * 1.5f), 1); Owner.Delete(); return; } if (pressure > TankRupturePressure) { if (_integrity <= 0) { var tileAtmos = Owner.Transform.Coordinates.GetTileAtmosphere(); tileAtmos?.AssumeAir(Air); EntitySystem.Get<AudioSystem>().PlayAtCoords("Audio/Effects/spray.ogg", Owner.Transform.Coordinates, AudioHelpers.WithVariation(0.125f)); Owner.Delete(); return; } _integrity--; return; } if (pressure > TankLeakPressure) { if (_integrity <= 0) { var tileAtmos = Owner.Transform.Coordinates.GetTileAtmosphere(); if (tileAtmos == null) return; var leakedGas = Air.RemoveRatio(0.25f); tileAtmos.AssumeAir(leakedGas); } else { _integrity--; } return; } if (_integrity < 3) _integrity++; } /// <summary> /// Open interaction window /// </summary> [Verb] private sealed class ControlVerb : Verb<GasTankComponent> { public override bool RequireInteractionRange => true; protected override void GetData(IEntity user, GasTankComponent component, VerbData data) { data.Visibility = VerbVisibility.Invisible; if (!user.HasComponent<IActorComponent>()) { return; } data.Visibility = VerbVisibility.Visible; data.Text = "Open Control Panel"; } protected override void Activate(IEntity user, GasTankComponent component) { if (!user.TryGetComponent<IActorComponent>(out var actor)) { return; } component.OpenInterface(actor.playerSession); } } public void Dropped(DroppedEventArgs eventArgs) { DisconnectFromInternals(eventArgs.User); } } }
/* * 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 ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.SimpleSystemsManagement.Model; namespace Amazon.SimpleSystemsManagement { /// <summary> /// Interface for accessing SimpleSystemsManagement /// /// Amazon EC2 Simple Systems Manager (SSM) enables you to configure and manage your EC2 /// instances. You can create a configuration document and then associate it with one /// or more running instances. /// /// /// <para> /// You can use a configuration document to automate the following tasks for your Windows /// instances: /// </para> /// <ul> <li> /// <para> /// Join an AWS Directory /// </para> /// </li> <li> /// <para> /// Install, repair, or uninstall software using an MSI package /// </para> /// </li> <li> /// <para> /// Run PowerShell scripts /// </para> /// </li> <li> /// <para> /// Configure CloudWatch Logs to monitor applications and systems /// </para> /// </li> </ul> /// <para> /// Note that configuration documents are not supported on Linux instances. /// </para> /// </summary> public partial interface IAmazonSimpleSystemsManagement : IDisposable { #region CreateAssociation /// <summary> /// Associates the specified configuration document with the specified instance. /// /// /// <para> /// When you associate a configuration document with an instance, the configuration agent /// on the instance processes the configuration document and configures the instance as /// specified. /// </para> /// /// <para> /// If you associate a configuration document with an instance that already has an associated /// configuration document, we replace the current configuration document with the new /// configuration document. /// </para> /// </summary> /// <param name="instanceId">The ID of the instance.</param> /// <param name="name">The name of the configuration document.</param> /// /// <returns>The response from the CreateAssociation service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationAlreadyExistsException"> /// The specified association already exists. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationLimitExceededException"> /// You can have at most 2,000 active associations. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> CreateAssociationResponse CreateAssociation(string instanceId, string name); /// <summary> /// Associates the specified configuration document with the specified instance. /// /// /// <para> /// When you associate a configuration document with an instance, the configuration agent /// on the instance processes the configuration document and configures the instance as /// specified. /// </para> /// /// <para> /// If you associate a configuration document with an instance that already has an associated /// configuration document, we replace the current configuration document with the new /// configuration document. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAssociation service method.</param> /// /// <returns>The response from the CreateAssociation service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationAlreadyExistsException"> /// The specified association already exists. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationLimitExceededException"> /// You can have at most 2,000 active associations. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> CreateAssociationResponse CreateAssociation(CreateAssociationRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateAssociation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateAssociation operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateAssociation /// operation.</returns> IAsyncResult BeginCreateAssociation(CreateAssociationRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateAssociation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAssociation.</param> /// /// <returns>Returns a CreateAssociationResult from SimpleSystemsManagement.</returns> CreateAssociationResponse EndCreateAssociation(IAsyncResult asyncResult); #endregion #region CreateAssociationBatch /// <summary> /// Associates the specified configuration documents with the specified instances. /// /// /// <para> /// When you associate a configuration document with an instance, the configuration agent /// on the instance processes the configuration document and configures the instance as /// specified. /// </para> /// /// <para> /// If you associate a configuration document with an instance that already has an associated /// configuration document, we replace the current configuration document with the new /// configuration document. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAssociationBatch service method.</param> /// /// <returns>The response from the CreateAssociationBatch service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationLimitExceededException"> /// You can have at most 2,000 active associations. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.DuplicateInstanceIdException"> /// You cannot specify an instance ID in more than one association. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> CreateAssociationBatchResponse CreateAssociationBatch(CreateAssociationBatchRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateAssociationBatch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateAssociationBatch operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateAssociationBatch /// operation.</returns> IAsyncResult BeginCreateAssociationBatch(CreateAssociationBatchRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateAssociationBatch operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAssociationBatch.</param> /// /// <returns>Returns a CreateAssociationBatchResult from SimpleSystemsManagement.</returns> CreateAssociationBatchResponse EndCreateAssociationBatch(IAsyncResult asyncResult); #endregion #region CreateDocument /// <summary> /// Creates a configuration document. /// /// /// <para> /// After you create a configuration document, you can use <a>CreateAssociation</a> to /// associate it with one or more running instances. /// </para> /// </summary> /// <param name="content">A valid JSON file. For more information about the contents of this file, see <a href="http://docs.aws.amazon.com/ssm/latest/APIReference/aws-ssm-document.html">Configuration Document</a>.</param> /// <param name="name">A name for the configuration document.</param> /// /// <returns>The response from the CreateDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.DocumentAlreadyExistsException"> /// The specified configuration document already exists. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.DocumentLimitExceededException"> /// You can have at most 100 active configuration documents. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentContentException"> /// The content for the configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.MaxDocumentSizeExceededException"> /// The size limit of a configuration document is 64 KB. /// </exception> CreateDocumentResponse CreateDocument(string content, string name); /// <summary> /// Creates a configuration document. /// /// /// <para> /// After you create a configuration document, you can use <a>CreateAssociation</a> to /// associate it with one or more running instances. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDocument service method.</param> /// /// <returns>The response from the CreateDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.DocumentAlreadyExistsException"> /// The specified configuration document already exists. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.DocumentLimitExceededException"> /// You can have at most 100 active configuration documents. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentContentException"> /// The content for the configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.MaxDocumentSizeExceededException"> /// The size limit of a configuration document is 64 KB. /// </exception> CreateDocumentResponse CreateDocument(CreateDocumentRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateDocument operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDocument operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateDocument /// operation.</returns> IAsyncResult BeginCreateDocument(CreateDocumentRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateDocument operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateDocument.</param> /// /// <returns>Returns a CreateDocumentResult from SimpleSystemsManagement.</returns> CreateDocumentResponse EndCreateDocument(IAsyncResult asyncResult); #endregion #region DeleteAssociation /// <summary> /// Disassociates the specified configuration document from the specified instance. /// /// /// <para> /// When you disassociate a configuration document from an instance, it does not change /// the configuration of the instance. To change the configuration state of an instance /// after you disassociate a configuration document, you must create a new configuration /// document with the desired configuration and associate it with the instance. /// </para> /// </summary> /// <param name="instanceId">The ID of the instance.</param> /// <param name="name">The name of the configuration document.</param> /// /// <returns>The response from the DeleteAssociation service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationDoesNotExistException"> /// The specified association does not exist. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.TooManyUpdatesException"> /// There are concurrent updates for a resource that supports one update at a time. /// </exception> DeleteAssociationResponse DeleteAssociation(string instanceId, string name); /// <summary> /// Disassociates the specified configuration document from the specified instance. /// /// /// <para> /// When you disassociate a configuration document from an instance, it does not change /// the configuration of the instance. To change the configuration state of an instance /// after you disassociate a configuration document, you must create a new configuration /// document with the desired configuration and associate it with the instance. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAssociation service method.</param> /// /// <returns>The response from the DeleteAssociation service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationDoesNotExistException"> /// The specified association does not exist. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.TooManyUpdatesException"> /// There are concurrent updates for a resource that supports one update at a time. /// </exception> DeleteAssociationResponse DeleteAssociation(DeleteAssociationRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteAssociation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAssociation operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteAssociation /// operation.</returns> IAsyncResult BeginDeleteAssociation(DeleteAssociationRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteAssociation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAssociation.</param> /// /// <returns>Returns a DeleteAssociationResult from SimpleSystemsManagement.</returns> DeleteAssociationResponse EndDeleteAssociation(IAsyncResult asyncResult); #endregion #region DeleteDocument /// <summary> /// Deletes the specified configuration document. /// /// /// <para> /// You must use <a>DeleteAssociation</a> to disassociate all instances that are associated /// with the configuration document before you can delete it. /// </para> /// </summary> /// <param name="name">The name of the configuration document.</param> /// /// <returns>The response from the DeleteDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociatedInstancesException"> /// You must disassociate a configuration document from all instances before you can delete /// it. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> DeleteDocumentResponse DeleteDocument(string name); /// <summary> /// Deletes the specified configuration document. /// /// /// <para> /// You must use <a>DeleteAssociation</a> to disassociate all instances that are associated /// with the configuration document before you can delete it. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDocument service method.</param> /// /// <returns>The response from the DeleteDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociatedInstancesException"> /// You must disassociate a configuration document from all instances before you can delete /// it. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> DeleteDocumentResponse DeleteDocument(DeleteDocumentRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteDocument operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDocument operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDocument /// operation.</returns> IAsyncResult BeginDeleteDocument(DeleteDocumentRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteDocument operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDocument.</param> /// /// <returns>Returns a DeleteDocumentResult from SimpleSystemsManagement.</returns> DeleteDocumentResponse EndDeleteDocument(IAsyncResult asyncResult); #endregion #region DescribeAssociation /// <summary> /// Describes the associations for the specified configuration document or instance. /// </summary> /// <param name="instanceId">The ID of the instance.</param> /// <param name="name">The name of the configuration document.</param> /// /// <returns>The response from the DescribeAssociation service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationDoesNotExistException"> /// The specified association does not exist. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> DescribeAssociationResponse DescribeAssociation(string instanceId, string name); /// <summary> /// Describes the associations for the specified configuration document or instance. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeAssociation service method.</param> /// /// <returns>The response from the DescribeAssociation service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationDoesNotExistException"> /// The specified association does not exist. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> DescribeAssociationResponse DescribeAssociation(DescribeAssociationRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeAssociation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeAssociation operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAssociation /// operation.</returns> IAsyncResult BeginDescribeAssociation(DescribeAssociationRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeAssociation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAssociation.</param> /// /// <returns>Returns a DescribeAssociationResult from SimpleSystemsManagement.</returns> DescribeAssociationResponse EndDescribeAssociation(IAsyncResult asyncResult); #endregion #region DescribeDocument /// <summary> /// Describes the specified configuration document. /// </summary> /// <param name="name">The name of the configuration document.</param> /// /// <returns>The response from the DescribeDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> DescribeDocumentResponse DescribeDocument(string name); /// <summary> /// Describes the specified configuration document. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDocument service method.</param> /// /// <returns>The response from the DescribeDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> DescribeDocumentResponse DescribeDocument(DescribeDocumentRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeDocument operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDocument operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeDocument /// operation.</returns> IAsyncResult BeginDescribeDocument(DescribeDocumentRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeDocument operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeDocument.</param> /// /// <returns>Returns a DescribeDocumentResult from SimpleSystemsManagement.</returns> DescribeDocumentResponse EndDescribeDocument(IAsyncResult asyncResult); #endregion #region GetDocument /// <summary> /// Gets the contents of the specified configuration document. /// </summary> /// <param name="name">The name of the configuration document.</param> /// /// <returns>The response from the GetDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> GetDocumentResponse GetDocument(string name); /// <summary> /// Gets the contents of the specified configuration document. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDocument service method.</param> /// /// <returns>The response from the GetDocument service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> GetDocumentResponse GetDocument(GetDocumentRequest request); /// <summary> /// Initiates the asynchronous execution of the GetDocument operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetDocument operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetDocument /// operation.</returns> IAsyncResult BeginGetDocument(GetDocumentRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetDocument operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetDocument.</param> /// /// <returns>Returns a GetDocumentResult from SimpleSystemsManagement.</returns> GetDocumentResponse EndGetDocument(IAsyncResult asyncResult); #endregion #region ListAssociations /// <summary> /// Lists the associations for the specified configuration document or instance. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssociations service method.</param> /// /// <returns>The response from the ListAssociations service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidNextTokenException"> /// The specified token is not valid. /// </exception> ListAssociationsResponse ListAssociations(ListAssociationsRequest request); /// <summary> /// Initiates the asynchronous execution of the ListAssociations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListAssociations operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListAssociations /// operation.</returns> IAsyncResult BeginListAssociations(ListAssociationsRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListAssociations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAssociations.</param> /// /// <returns>Returns a ListAssociationsResult from SimpleSystemsManagement.</returns> ListAssociationsResponse EndListAssociations(IAsyncResult asyncResult); #endregion #region ListDocuments /// <summary> /// Describes one or more of your configuration documents. /// </summary> /// /// <returns>The response from the ListDocuments service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidNextTokenException"> /// The specified token is not valid. /// </exception> ListDocumentsResponse ListDocuments(); /// <summary> /// Describes one or more of your configuration documents. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDocuments service method.</param> /// /// <returns>The response from the ListDocuments service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidNextTokenException"> /// The specified token is not valid. /// </exception> ListDocumentsResponse ListDocuments(ListDocumentsRequest request); /// <summary> /// Initiates the asynchronous execution of the ListDocuments operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDocuments operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDocuments /// operation.</returns> IAsyncResult BeginListDocuments(ListDocumentsRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListDocuments operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDocuments.</param> /// /// <returns>Returns a ListDocumentsResult from SimpleSystemsManagement.</returns> ListDocumentsResponse EndListDocuments(IAsyncResult asyncResult); #endregion #region UpdateAssociationStatus /// <summary> /// Updates the status of the configuration document associated with the specified instance. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAssociationStatus service method.</param> /// /// <returns>The response from the UpdateAssociationStatus service method, as returned by SimpleSystemsManagement.</returns> /// <exception cref="Amazon.SimpleSystemsManagement.Model.AssociationDoesNotExistException"> /// The specified association does not exist. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidDocumentException"> /// The configuration document is not valid. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.InvalidInstanceIdException"> /// You must specify the ID of a running instance. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.StatusUnchangedException"> /// The updated status is the same as the current status. /// </exception> /// <exception cref="Amazon.SimpleSystemsManagement.Model.TooManyUpdatesException"> /// There are concurrent updates for a resource that supports one update at a time. /// </exception> UpdateAssociationStatusResponse UpdateAssociationStatus(UpdateAssociationStatusRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateAssociationStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateAssociationStatus operation on AmazonSimpleSystemsManagementClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateAssociationStatus /// operation.</returns> IAsyncResult BeginUpdateAssociationStatus(UpdateAssociationStatusRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the UpdateAssociationStatus operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateAssociationStatus.</param> /// /// <returns>Returns a UpdateAssociationStatusResult from SimpleSystemsManagement.</returns> UpdateAssociationStatusResponse EndUpdateAssociationStatus(IAsyncResult asyncResult); #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace VanillaJq.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using Microsoft.Extensions.Options; using System; using System.Collections.Generic; namespace DaaSDemo.Provisioning { using Common.Options; using KubeClient.Models; using Models.Data; /// <summary> /// Factory methods for common Kubernetes resource specifications. /// </summary> public class KubeSpecs { /// <summary> /// Create a new <see cref="KubeResources"/>. /// </summary> /// <param name="names"> /// The Kubernetes resource-naming strategy. /// </param> /// <param name="kubeOptions"> /// Application-level Kubernetes settings. /// </param> /// <param name="provisioningOptions"> /// Application-level provisioning options. /// </param> public KubeSpecs(KubeNames names, IOptions<KubernetesOptions> kubeOptions, IOptions<ProvisioningOptions> provisioningOptions) { if (names == null) throw new ArgumentNullException(nameof(names)); if (kubeOptions == null) throw new ArgumentNullException(nameof(kubeOptions)); if (provisioningOptions == null) throw new ArgumentNullException(nameof(provisioningOptions)); Names = names; KubeOptions = kubeOptions.Value; ProvisioningOptions = provisioningOptions.Value; } /// <summary> /// Application-level Kubernetes settings. /// </summary> public KubeNames Names { get; } /// <summary> /// Application-level Kubernetes settings. /// </summary> public KubernetesOptions KubeOptions { get; } /// <summary> /// Application-level provisioning options. /// </summary> public ProvisioningOptions ProvisioningOptions { get; } /// <summary> /// Build a <see cref="PersistentVolumeClaimSpecV1"/> for the specified server. /// </summary> /// <param name="server"> /// A <see cref="DatabaseServer"/> representing the target server. /// </param> /// <returns> /// The configured <see cref="PersistentVolumeClaimSpecV1"/>. /// </returns> public PersistentVolumeClaimSpecV1 DataVolumeClaim(DatabaseServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); return new PersistentVolumeClaimSpecV1 { AccessModes = new List<string> { "ReadWriteOnce" }, StorageClassName = KubeOptions.DatabaseStorageClass, Resources = new ResourceRequirementsV1 { Requests = new Dictionary<string, string> { ["storage"] = $"{server.Settings.Storage.SizeMB}Mi" } } }; } /// <summary> /// Build a <see cref="DeploymentSpecV1Beta1"/> for the specified server. /// </summary> /// <param name="server"> /// A <see cref="DatabaseServer"/> representing the target server. /// </param> /// <returns> /// The configured <see cref="DeploymentSpecV1Beta1"/>. /// </returns> public DeploymentSpecV1Beta1 Deployment(DatabaseServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); string baseName = Names.BaseName(server); var deploymentSpec = new DeploymentSpecV1Beta1 { Replicas = 1, MinReadySeconds = 30, Strategy = new DeploymentStrategyV1Beta1 { Type = "Recreate" // Shut down the old instance before starting the new one }, Selector = new LabelSelectorV1 { MatchLabels = new Dictionary<string, string> { ["k8s-app"] = baseName } }, Template = new PodTemplateSpecV1 { Metadata = new ObjectMetaV1 { Labels = new Dictionary<string, string> { ["k8s-app"] = baseName, ["cloud.dimensiondata.daas.server-id"] = server.Id, ["cloud.dimensiondata.daas.server-kind"] = server.Kind.ToString() } }, Spec = new PodSpecV1 { TerminationGracePeriodSeconds = 60, ImagePullSecrets = new List<LocalObjectReferenceV1> { new LocalObjectReferenceV1 { Name = "daas-registry" } }, Containers = new List<ContainerV1>(), Volumes = new List<VolumeV1> { new VolumeV1 { Name = "data", PersistentVolumeClaim = new PersistentVolumeClaimVolumeSourceV1 { ClaimName = Names.DataVolumeClaim(server) } } } } } }; PodSpecV1 podSpec = deploymentSpec.Template.Spec; switch (server.Kind) { case DatabaseServerKind.SqlServer: { // SQL Server podSpec.Containers.Add(new ContainerV1 { Name = "sql-server", Image = ProvisioningOptions.Images.SQL, Resources = new ResourceRequirementsV1 { Requests = new Dictionary<string, string> { ["memory"] = "4Gi" // SQL Server for Linux requires at least 4 GB of RAM }, Limits = new Dictionary<string, string> { ["memory"] = "6Gi" // If you're using more than 6 GB of RAM, then you should probably host stand-alone } }, Env = new List<EnvVarV1> { new EnvVarV1 { Name = "ACCEPT_EULA", Value = "Y" }, new EnvVarV1 { Name = "SA_PASSWORD", ValueFrom = new EnvVarSourceV1 { SecretKeyRef = new SecretKeySelectorV1 { Name = Names.CredentialsSecret(server), Key = "sa-password" } } } }, Ports = new List<ContainerPortV1> { new ContainerPortV1 { ContainerPort = 1433 } }, VolumeMounts = new List<VolumeMountV1> { new VolumeMountV1 { Name = "data", SubPath = baseName, MountPath = "/var/opt/mssql" } } }); // Prometheus exporter podSpec.Containers.Add(new ContainerV1 { Name = "prometheus-exporter", Image = ProvisioningOptions.Images.SQLExporter, Env = new List<EnvVarV1> { new EnvVarV1 { Name = "SERVER", Value = "127.0.0.1", }, new EnvVarV1 { Name = "USERNAME", Value = "sa" }, new EnvVarV1 { Name = "PASSWORD", ValueFrom = new EnvVarSourceV1 { SecretKeyRef = new SecretKeySelectorV1 { Name = Names.CredentialsSecret(server), Key = "sa-password" } } }, new EnvVarV1 { Name = "DEBUG", Value = "app" } }, Ports = new List<ContainerPortV1> { new ContainerPortV1 { ContainerPort = 4000 } } }); break; } case DatabaseServerKind.RavenDB: { podSpec.Containers.Add(new ContainerV1 { Name = "ravendb", Image = ProvisioningOptions.Images.RavenDB, Resources = new ResourceRequirementsV1 { Requests = new Dictionary<string, string> { ["memory"] = "1Gi" }, Limits = new Dictionary<string, string> { ["memory"] = "3Gi" } }, Env = new List<EnvVarV1> { new EnvVarV1 { Name = "UNSECURED_ACCESS_ALLOWED", Value = "PublicNetwork" } }, Ports = new List<ContainerPortV1> { new ContainerPortV1 { Name = "http", ContainerPort = 8080 }, new ContainerPortV1 { Name = "tcp", ContainerPort = 38888 } }, VolumeMounts = new List<VolumeMountV1> { new VolumeMountV1 { Name = "data", SubPath = baseName, MountPath = "/databases" } } }); break; } default: { throw new NotSupportedException($"Unsupported server kind ({server.Kind})."); } } return deploymentSpec; } /// <summary> /// Build an internally-facing <see cref="ServiceSpecV1"/> for the specified server. /// </summary> /// <param name="server"> /// A <see cref="DatabaseServer"/> representing the target server. /// </param> /// <returns> /// The configured <see cref="ServiceSpecV1"/>. /// </returns> public ServiceSpecV1 InternalService(DatabaseServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); string baseName = Names.BaseName(server); var spec = new ServiceSpecV1 { Ports = new List<ServicePortV1>(), Selector = new Dictionary<string, string> { ["k8s-app"] = baseName } }; switch (server.Kind) { case DatabaseServerKind.SqlServer: { spec.Ports.Add(new ServicePortV1 { Name = "sql-server", Port = 1433, Protocol = "TCP" }); spec.Ports.Add(new ServicePortV1 { Name = "prometheus-exporter", Port = 4000, Protocol = "TCP" }); break; } case DatabaseServerKind.RavenDB: { spec.Ports.Add(new ServicePortV1 { Name = "http", Port = 8080, Protocol = "TCP" }); spec.Ports.Add(new ServicePortV1 { Name = "tcp", Port = 38888, Protocol = "TCP" }); break; } default: { throw new NotSupportedException($"Unsupported server type ({server.Kind})."); } } return spec; } /// <summary> /// Build an externally-facing <see cref="ServiceSpecV1"/> for the specified server. /// </summary> /// <param name="server"> /// A <see cref="DatabaseServer"/> representing the target server. /// </param> /// <returns> /// The configured <see cref="ServiceSpecV1"/>. /// </returns> public ServiceSpecV1 ExternalService(DatabaseServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); string baseName = Names.BaseName(server); var spec = new ServiceSpecV1 { Type = "NodePort", Ports = new List<ServicePortV1>(), Selector = new Dictionary<string, string> { ["k8s-app"] = baseName } }; switch (server.Kind) { case DatabaseServerKind.SqlServer: { spec.Ports.Add(new ServicePortV1 { Name = "sql-server", Port = 1433, Protocol = "TCP" }); break; } case DatabaseServerKind.RavenDB: { spec.Ports.Add(new ServicePortV1 { Name = "http", Port = 8080, Protocol = "TCP" }); spec.Ports.Add(new ServicePortV1 { Name = "tcp", Port = 38888, Protocol = "TCP" }); break; } default: { throw new NotSupportedException($"Unsupported server type ({server.Kind})."); } } return spec; } /// <summary> /// Build a <see cref="PrometheusServiceMonitorSpecV1"/> for the specified server. /// </summary> /// <param name="server"> /// A <see cref="DatabaseServer"/> representing the target server. /// </param> /// <returns> /// The configured <see cref="PrometheusServiceMonitorSpecV1"/>. /// </returns> public PrometheusServiceMonitorSpecV1 ServiceMonitor(DatabaseServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); string baseName = Names.BaseName(server); return new PrometheusServiceMonitorSpecV1 { JobLabel = baseName, Selector = new LabelSelectorV1 { MatchLabels = new Dictionary<string, string> { ["cloud.dimensiondata.daas.server-id"] = server.Id, ["cloud.dimensiondata.daas.service-type"] = "internal" } }, EndPoints = new List<PrometheusServiceMonitorEndPointV1> { new PrometheusServiceMonitorEndPointV1 { Port = "prometheus-exporter" } } }; } } }
using System; using System.Diagnostics; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BytesRef = Lucene.Net.Util.BytesRef; using FieldInvertState = Lucene.Net.Index.FieldInvertState; using NumericDocValues = Lucene.Net.Index.NumericDocValues; using SmallSingle = Lucene.Net.Util.SmallSingle; namespace Lucene.Net.Search.Similarities { /* * 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. */ /// <summary> /// A subclass of <see cref="Similarity"/> that provides a simplified API for its /// descendants. Subclasses are only required to implement the <see cref="Score(BasicStats, float, float)"/> /// and <see cref="ToString()"/> methods. Implementing /// <see cref="Explain(Explanation, BasicStats, int, float, float)"/> is optional, /// inasmuch as <see cref="SimilarityBase"/> already provides a basic explanation of the score /// and the term frequency. However, implementers of a subclass are encouraged to /// include as much detail about the scoring method as possible. /// <para/> /// Note: multi-word queries such as phrase queries are scored in a different way /// than Lucene's default ranking algorithm: whereas it "fakes" an IDF value for /// the phrase as a whole (since it does not know it), this class instead scores /// phrases as a summation of the individual term scores. /// <para/> /// @lucene.experimental /// </summary> public abstract class SimilarityBase : Similarity { /// <summary> /// For <see cref="Log2(double)"/>. Precomputed for efficiency reasons. </summary> private static readonly double LOG_2 = Math.Log(2); /// <summary> /// True if overlap tokens (tokens with a position of increment of zero) are /// discounted from the document's length. /// </summary> private bool discountOverlaps = true; // LUCENENET Specific: made private, since it can be get/set through property /// <summary> /// Sole constructor. (For invocation by subclass /// constructors, typically implicit.) /// </summary> public SimilarityBase() { } /// <summary> /// Determines whether overlap tokens (Tokens with /// 0 position increment) are ignored when computing /// norm. By default this is <c>true</c>, meaning overlap /// tokens do not count when computing norms. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="ComputeNorm(FieldInvertState)"/> public virtual bool DiscountOverlaps { set { discountOverlaps = value; } get { return discountOverlaps; } } public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { BasicStats[] stats = new BasicStats[termStats.Length]; for (int i = 0; i < termStats.Length; i++) { stats[i] = NewStats(collectionStats.Field, queryBoost); FillBasicStats(stats[i], collectionStats, termStats[i]); } return stats.Length == 1 ? stats[0] : new MultiSimilarity.MultiStats(stats) as SimWeight; } /// <summary> /// Factory method to return a custom stats object </summary> protected internal virtual BasicStats NewStats(string field, float queryBoost) { return new BasicStats(field, queryBoost); } /// <summary> /// Fills all member fields defined in <see cref="BasicStats"/> in <paramref name="stats"/>. /// Subclasses can override this method to fill additional stats. /// </summary> protected internal virtual void FillBasicStats(BasicStats stats, CollectionStatistics collectionStats, TermStatistics termStats) { // #positions(field) must be >= #positions(term) Debug.Assert(collectionStats.SumTotalTermFreq == -1 || collectionStats.SumTotalTermFreq >= termStats.TotalTermFreq); long numberOfDocuments = collectionStats.MaxDoc; long docFreq = termStats.DocFreq; long totalTermFreq = termStats.TotalTermFreq; // codec does not supply totalTermFreq: substitute docFreq if (totalTermFreq == -1) { totalTermFreq = docFreq; } long numberOfFieldTokens; float avgFieldLength; long sumTotalTermFreq = collectionStats.SumTotalTermFreq; if (sumTotalTermFreq <= 0) { // field does not exist; // We have to provide something if codec doesnt supply these measures, // or if someone omitted frequencies for the field... negative values cause // NaN/Inf for some scorers. numberOfFieldTokens = docFreq; avgFieldLength = 1; } else { numberOfFieldTokens = sumTotalTermFreq; avgFieldLength = (float)numberOfFieldTokens / numberOfDocuments; } // TODO: add sumDocFreq for field (numberOfFieldPostings) stats.NumberOfDocuments = numberOfDocuments; stats.NumberOfFieldTokens = numberOfFieldTokens; stats.AvgFieldLength = avgFieldLength; stats.DocFreq = docFreq; stats.TotalTermFreq = totalTermFreq; } /// <summary> /// Scores the document <c>doc</c>. /// <para>Subclasses must apply their scoring formula in this class.</para> </summary> /// <param name="stats"> the corpus level statistics. </param> /// <param name="freq"> the term frequency. </param> /// <param name="docLen"> the document length. </param> /// <returns> the score. </returns> public abstract float Score(BasicStats stats, float freq, float docLen); /// <summary> /// Subclasses should implement this method to explain the score. <paramref name="expl"/> /// already contains the score, the name of the class and the doc id, as well /// as the term frequency and its explanation; subclasses can add additional /// clauses to explain details of their scoring formulae. /// <para>The default implementation does nothing.</para> /// </summary> /// <param name="expl"> the explanation to extend with details. </param> /// <param name="stats"> the corpus level statistics. </param> /// <param name="doc"> the document id. </param> /// <param name="freq"> the term frequency. </param> /// <param name="docLen"> the document length. </param> protected internal virtual void Explain(Explanation expl, BasicStats stats, int doc, float freq, float docLen) { } /// <summary> /// Explains the score. The implementation here provides a basic explanation /// in the format <em>Score(name-of-similarity, doc=doc-id, /// freq=term-frequency), computed from:</em>, and /// attaches the score (computed via the <see cref="Score(BasicStats, float, float)"/> /// method) and the explanation for the term frequency. Subclasses content with /// this format may add additional details in /// <see cref="Explain(Explanation, BasicStats, int, float, float)"/>. /// </summary> /// <param name="stats"> the corpus level statistics. </param> /// <param name="doc"> the document id. </param> /// <param name="freq"> the term frequency and its explanation. </param> /// <param name="docLen"> the document length. </param> /// <returns> the explanation. </returns> public virtual Explanation Explain(BasicStats stats, int doc, Explanation freq, float docLen) { Explanation result = new Explanation(); result.Value = Score(stats, freq.Value, docLen); result.Description = "score(" + this.GetType().Name + ", doc=" + doc + ", freq=" + freq.Value + "), computed from:"; result.AddDetail(freq); Explain(result, stats, doc, freq.Value, docLen); return result; } public override SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context) { if (stats is MultiSimilarity.MultiStats) { // a multi term query (e.g. phrase). return the summation, // scoring almost as if it were boolean query SimWeight[] subStats = ((MultiSimilarity.MultiStats)stats).subStats; SimScorer[] subScorers = new SimScorer[subStats.Length]; for (int i = 0; i < subScorers.Length; i++) { BasicStats basicstats = (BasicStats)subStats[i]; subScorers[i] = new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field)); } return new MultiSimilarity.MultiSimScorer(subScorers); } else { BasicStats basicstats = (BasicStats)stats; return new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field)); } } /// <summary> /// Subclasses must override this method to return the name of the <see cref="Similarity"/> /// and preferably the values of parameters (if any) as well. /// </summary> public override abstract string ToString(); // ------------------------------ Norm handling ------------------------------ /// <summary> /// Norm -> document length map. </summary> private static readonly float[] NORM_TABLE = new float[256]; static SimilarityBase() { for (int i = 0; i < 256; i++) { float floatNorm = SmallSingle.SByte315ToSingle((sbyte)i); NORM_TABLE[i] = 1.0f / (floatNorm * floatNorm); } } /// <summary> /// Encodes the document length in the same way as <see cref="TFIDFSimilarity"/>. </summary> public override long ComputeNorm(FieldInvertState state) { float numTerms; if (discountOverlaps) { numTerms = state.Length - state.NumOverlap; } else { numTerms = state.Length; } return EncodeNormValue(state.Boost, numTerms); } /// <summary> /// Decodes a normalization factor (document length) stored in an index. </summary> /// <see cref="EncodeNormValue(float,float)"/> protected internal virtual float DecodeNormValue(byte norm) { return NORM_TABLE[norm & 0xFF]; // & 0xFF maps negative bytes to positive above 127 } /// <summary> /// Encodes the length to a byte via <see cref="SmallSingle"/>. </summary> protected internal virtual byte EncodeNormValue(float boost, float length) { return SmallSingle.SingleToByte315((boost / (float)Math.Sqrt(length))); } // ----------------------------- Static methods ------------------------------ /// <summary> /// Returns the base two logarithm of <c>x</c>. </summary> public static double Log2(double x) { // Put this to a 'util' class if we need more of these. return Math.Log(x) / LOG_2; } // --------------------------------- Classes --------------------------------- /// <summary> /// Delegates the <see cref="Score(int, float)"/> and /// <see cref="Explain(int, Explanation)"/> methods to /// <see cref="SimilarityBase.Score(BasicStats, float, float)"/> and /// <see cref="SimilarityBase.Explain(BasicStats, int, Explanation, float)"/>, /// respectively. /// </summary> private class BasicSimScorer : SimScorer { private readonly SimilarityBase outerInstance; private readonly BasicStats stats; private readonly NumericDocValues norms; internal BasicSimScorer(SimilarityBase outerInstance, BasicStats stats, NumericDocValues norms) { this.outerInstance = outerInstance; this.stats = stats; this.norms = norms; } public override float Score(int doc, float freq) { // We have to supply something in case norms are omitted return outerInstance.Score(stats, freq, norms == null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc))); } public override Explanation Explain(int doc, Explanation freq) { return outerInstance.Explain(stats, doc, freq, norms == null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc))); } public override float ComputeSlopFactor(int distance) { return 1.0f / (distance + 1); } public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload) { return 1f; } } } }
#region License... //----------------------------------------------------------------------------- // Date: 20/12/15 Time: 9:00 // Module: CSScriptLib.Eval.Roslyn.cs // // This module contains the definition of the Roslyn Evaluator class. Which wraps the common functionality // of the Mono.CScript.Evaluator class (compiler as service) // // Written by Oleg Shilo ([email protected]) //---------------------------------------------- // The MIT License (MIT) // Copyright (c) 2016 Oleg Shilo // // 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 License... using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Emit; //using Microsoft.CodeAnalysis; //using Microsoft.CodeAnalysis.CSharp.Scripting using Microsoft.CodeAnalysis.Scripting; using csscript; using CSScripting; using CSScripting.CodeDom; // <summary> //<package id="Microsoft.Net.Compilers" version="1.2.0-beta-20151211-01" targetFramework="net45" developmentDependency="true" /> // Roslyn limitations: // Script cannot have namespaces // File-less (in-memory assemblies) cannot be referenced // The compiled assembly is a file-less assembly so it cannot be referenced in other scripts in a normal way but only via Roslyn // All script types are nested classes !???? // Compiling time is heavily affected by number of ref assemblies (Mono is not affected) // Everything (e.g. class code) is compiled as a nested class with the parent class name // "Submission#N" and the number-sign makes it extremely difficult to reference from other scripts // </summary> namespace CSScriptLib { /// <summary> /// The information about the location of the compiler output - assembly and pdb file. /// </summary> public class CompileInfo { /// <summary> /// Gets or sets the compiler options for csc.exe. /// <para> /// This property is only applcable for CodeDOM based script execution as Roslyn engine does /// not accept string options for compilation. /// </para> /// </summary> /// <value>The compiler options.</value> public string CompilerOptions { get; set; } string assemblyFile; /// <summary> /// The assembly file path. If not specified it will be composed as "&lt;RootClass&gt;.dll". /// </summary> public string AssemblyFile { get { if (assemblyFile == null) return $"{RootClass}.dll".GetFullPath(); else return assemblyFile.GetFullPath(); } set => assemblyFile = value; } /// <summary> /// The PDB file path. /// <para> /// Even if the this value is specified the file will not be generated unless <see /// cref="CSScript.EvaluatorConfig"/>.DebugBuild is set to <c>true</c>. /// </para> /// </summary> public string PdbFile { set; get; } /// <summary> /// Gets or sets the root class name. /// <para> /// This setting is required as Roslyn cannot produce compiled scripts with the user script /// class defined as a top level class. Thus all user defined classes are in fact nested /// classes with the root class named by Roslyn as "Submission#0". This leads to the /// complications when user wants to reference script class in another script. Specifically /// because C# treats "Submission#0" as an illegal class name. /// </para> /// <para> /// C# helps the situation by allowing user specified root name <see /// cref="CSScriptLib.CompileInfo.RootClass"/>, which is by default is "css_root". /// </para> /// </summary> /// <value>The root class name.</value> public string RootClass { set; get; } = Globals.RootClassName; /// <summary> /// Gets or sets a value indicating whether to prefer loading compiled script from the /// assembly file when it is available. /// </summary> /// <value><c>true</c> if [prefer loading from file]; otherwise, <c>false</c>.</value> public bool PreferLoadingFromFile { set; get; } = true; } /// <summary> /// The exception that is thrown when a the script compiler error occurs. /// </summary> [Serializable] public class CompilerException : ApplicationException { /// <summary> /// Gets or sets the error count associated with the last script compilation. /// </summary> /// <value>The error count.</value> public int ErrorCount { get; set; } /// <summary> /// Initialises a new instance of the <see cref="CompilerException"/> class. /// </summary> public CompilerException() { } /// <summary> /// Initialises a new instance of the <see cref="CompilerException"/> class. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> public CompilerException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of the <see cref="CompilerException"/> class. /// </summary> /// <param name="message">The message.</param> public CompilerException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="CompilerException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public CompilerException(string message, Exception exception) : base(message, exception) { } /// <summary> /// Creates the CompilerException instance from the specified compiler errors. /// </summary> /// <param name="Errors">The compiler errors.</param> /// <param name="hideCompilerWarnings">if set to <c>true</c> hide compiler warnings.</param> /// <param name="resolveAutogenFilesRefs"> /// if set to <c>true</c> all references to the path of the derived auto-generated files /// (e.g. errors in the decorated classless scripts) will be replaced with the path of the /// original files (e.g. classless script itself). /// </param> /// <returns>The method result.</returns> public static CompilerException Create(IEnumerable<CompilerError> Errors, bool hideCompilerWarnings, bool resolveAutogenFilesRefs) { var compileErr = new StringBuilder(); int errorCount = 0; foreach (CompilerError err in Errors) { if (!err.IsWarning) errorCount++; if (err.IsWarning && hideCompilerWarnings) continue; if (err.FileName.HasText()) { string file = err.FileName; int line = err.Line; if (resolveAutogenFilesRefs) CoreExtensions.NormaliseFileReference(ref file, ref line); compileErr.Append(file) .Append("(") .Append(line) .Append(",") .Append(err.Column) .Append("): "); } else { compileErr.Append("BUILD: "); } if (err.IsWarning) compileErr.Append("warning "); else compileErr.Append("error "); compileErr.Append(err.ErrorNumber) .Append(": ") .Append(err.ErrorText.Trim(' ')) .Append(Environment.NewLine); } var retval = new CompilerException(compileErr.ToString()); retval.Data.Add("Errors", Errors); retval.ErrorCount = errorCount; return retval; } } static class localExtensions { public static (string file, int line) Translate(this Dictionary<(int, int), (string, int)> mapping, int line) { foreach ((int start, int end) range in mapping.Keys) if (range.start <= line && line <= range.end) { (string file, int lineOffset) = mapping[range]; return (file, line - range.start + lineOffset); } return ("", 0); } static public string[] SeparateUsingsFromCode(this string code) { SyntaxTree tree = CSharpSyntaxTree.ParseText(code); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); int pos = root.Usings.FullSpan.End; return new[] { code.Substring(0, pos).TrimEnd(), code.Substring(pos) }; } } /// <summary> /// </summary> /// <seealso cref="CSScriptLib.IEvaluator"/> public class RoslynEvaluator : EvaluatorBase<RoslynEvaluator>, IEvaluator { ScriptOptions compilerSettings = ScriptOptions.Default; /// <summary> /// Loads and returns set of referenced assemblies. /// <para>Notre: the set of assemblies is cleared on Reset.</para> /// </summary> /// <returns>The method result.</returns> public override Assembly[] GetReferencedAssemblies() { // Note all ref assemblies are already loaded as the Evaluator interface is "align" to // behave as Mono evaluator, which only referenced already loaded assemblies but not // file locations var assemblies = CompilerSettings.MetadataReferences .OfType<PortableExecutableReference>() .Select(r => Assembly.LoadFile(r.FilePath)) .ToArray(); return assemblies; } /// <summary> /// Gets or sets the compiler settings. /// </summary> /// <value>The compiler settings.</value> public ScriptOptions CompilerSettings { get => compilerSettings; set => compilerSettings = value; } /// <summary> /// Loads the assemblies implementing Roslyn compilers. /// <para> /// Roslyn compilers are extremely heavy and loading the compiler assemblies for with the /// first evaluation call can take a significant time to complete (in some cases up to 4 /// seconds) while the consequent calls are very fast. /// </para> /// <para> /// You may want to call this method to pre-load the compiler assembly your script /// evaluation performance. /// </para> /// </summary> public static void LoadCompilers() { CSharpScript.EvaluateAsync("1 + 2"); //this will loaded all required assemblies } /// <summary> /// Compiles the specified script text. /// </summary> /// <param name="scriptText">The script text.</param> /// <param name="scriptFile">The script file.</param> /// <param name="info">The information.</param> /// <returns>The method result.</returns> /// <exception cref="CSScriptLib.CompilerException"></exception> override protected (byte[] asm, byte[] pdb) Compile(string scriptText, string scriptFile, CompileInfo info) { // http://www.michalkomorowski.com/2016/10/roslyn-how-to-create-custom-debuggable_27.html string tempScriptFile = null; try { if (scriptText == null && scriptFile != null) scriptText = File.ReadAllText(scriptFile); if (!DisableReferencingFromCode) { var localDir = this.GetType().Assembly.Location().GetDirName(); ReferenceAssembliesFromCode(scriptText, localDir); } int scriptHash = base.GetHashFor(scriptText, scriptFile); if (IsCachingEnabled) { if (scriptCache.ContainsKey(scriptHash)) return scriptCache[scriptHash]; } //////////////////////////////////////// var mapping = new Dictionary<(int, int), (string, int)>(); if (scriptFile == null && new CSharpParser(scriptText, false).Imports.Any()) { tempScriptFile = CSScript.GetScriptTempFile(); File.WriteAllText(tempScriptFile, scriptText); } if (scriptFile == null && tempScriptFile == null) { if (this.IsDebug) { tempScriptFile = CSScript.GetScriptTempFile(); File.WriteAllText(tempScriptFile, scriptText); scriptText = $"#line 1 \"{tempScriptFile}\"{Environment.NewLine}" + scriptText; } else scriptText = $"#line 1 \"script\"{Environment.NewLine}" + scriptText; } else { var parser = new ScriptParser(scriptFile ?? tempScriptFile, new[] { scriptFile?.GetDirName() }, false); var importedSources = new Dictionary<string, (int, string[])>(); // file, usings count, code lines var combinedScript = new List<string>(); var single_source = scriptFile.ChangeExtension(".g" + scriptFile.GetExtension()); foreach (string file in parser.FilesToCompile.Skip(1)) { var parts = File.ReadAllText(file).SeparateUsingsFromCode(); var usings = parts[0].GetLines(); var code = parts[1].GetLines(); importedSources[file] = (usings.Count(), code); add_code(file, usings, 0); } void add_code(string file, string[] codeLines, int lineOffset) { int start = combinedScript.Count; combinedScript.AddRange(codeLines); int end = combinedScript.Count; mapping[(start, end)] = (file, lineOffset); } combinedScript.Add($"#line 1 \"{(scriptFile ?? tempScriptFile)}\""); add_code(scriptFile, scriptText.GetLines(), 0); foreach (string file in importedSources.Keys) { (var usings_count, var code) = importedSources[file]; combinedScript.Add($"#line {usings_count + 1} \"{file}\""); // zos add_code(file, code, usings_count); } scriptText = combinedScript.JoinBy(Environment.NewLine); } //////////////////////////////////////// PrepareRefeAssemblies(); var compilation = CSharpScript.Create(scriptText, CompilerSettings) .GetCompilation(); // compilation.Options if (this.IsDebug) compilation = compilation.WithOptions(compilation.Options.WithOptimizationLevel(OptimizationLevel.Debug)); compilation = compilation.WithOptions(compilation.Options.WithScriptClassName(info?.RootClass ?? Globals.RootClassName) .WithOutputKind(OutputKind.DynamicallyLinkedLibrary)); using (var pdb = new MemoryStream()) using (var asm = new MemoryStream()) { var emitOptions = new EmitOptions(false, CSScript.EvaluatorConfig.PdbFormat); EmitResult result; if (IsDebug) { if (CSScript.EvaluatorConfig.PdbFormat == DebugInformationFormat.Embedded) result = compilation.Emit(asm, options: emitOptions); else result = compilation.Emit(asm, pdb, options: emitOptions); } else result = compilation.Emit(asm); if (!result.Success) { IEnumerable<Diagnostic> failures = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error); var message = new StringBuilder(); foreach (Diagnostic diagnostic in failures) { string error_location = ""; if (diagnostic.Location.IsInSource) { var error_pos = diagnostic.Location.GetLineSpan().StartLinePosition; int error_line = error_pos.Line + 1; int error_column = error_pos.Character + 1; var source = "<script>"; if (mapping.Any()) (source, error_line) = mapping.Translate(error_line); else error_line--; // no mapping as it was a single file so translation is minimal // the actual source contains an injected '#line' directive of // compiled with debug symbols so increment line after formatting error_location = $"{(source.HasText() ? source : "<script>")}({error_line},{ error_column}): "; } message.AppendLine($"{error_location}error {diagnostic.Id}: {diagnostic.GetMessage()}"); } var errors = message.ToString(); throw new CompilerException(errors); } else { (byte[], byte[]) binaries; asm.Seek(0, SeekOrigin.Begin); byte[] buffer = asm.GetBuffer(); if (info?.AssemblyFile != null) File.WriteAllBytes(info.AssemblyFile, buffer); if (IsDebug && CSScript.EvaluatorConfig.PdbFormat != DebugInformationFormat.Embedded) { pdb.Seek(0, SeekOrigin.Begin); byte[] pdbBuffer = pdb.GetBuffer(); if (info != null && info.PdbFile.IsEmpty() && info.AssemblyFile.IsNotEmpty()) info.PdbFile = Path.ChangeExtension(info.AssemblyFile, ".pdb"); if (info?.PdbFile != null) File.WriteAllBytes(info.PdbFile, pdbBuffer); binaries = (buffer, pdbBuffer); } else binaries = (buffer, null); if (IsCachingEnabled) scriptCache[scriptHash] = binaries; return binaries; } } } finally { if (this.IsDebug) CSScript.NoteTempFile(tempScriptFile); else tempScriptFile.FileDelete(false); } } /// <summary> /// References the given assembly. /// <para> /// It is safe to call this method multiple times for the same assembly. If the assembly /// already referenced it will not be referenced again. /// </para> /// </summary> /// <param name="assembly">The assembly instance.</param> /// <returns> /// The instance of the <see cref="T:CSScriptLib.IEvaluator"/> to allow fluent interface. /// </returns> /// <exception cref="System.Exception"> /// Current version of {EngineName} doesn't support referencing assemblies " + "which are /// not loaded from the file location. /// </exception> public override IEvaluator ReferenceAssembly(Assembly assembly) { //Microsoft.Net.Compilers.1.2.0 - beta if (assembly.Location.IsEmpty()) throw new Exception( $"Current version of Roslyn-based evaluator does not support referencing assemblies " + "which are not loaded from the file location."); if (!refAssemblies.Contains(assembly)) refAssemblies.Add(assembly); return this; } List<Assembly> refAssemblies = new List<Assembly>(); IEvaluator PrepareRefeAssemblies() { foreach (var assembly in FilterAssemblies(refAssemblies)) if (assembly != null)//this check is needed when trying to load partial name assemblies that result in null { if (!CompilerSettings.MetadataReferences.OfType<PortableExecutableReference>() .Any(r => r.FilePath.SamePathAs(assembly.Location))) // Future assembly aliases support: // MetadataReference.CreateFromFile("asm.dll", new // MetadataReferenceProperties().WithAliases(new[] { "lib_a", // "external_lib_a" } }) CompilerSettings = CompilerSettings.AddReferences(assembly); } var refs = CompilerSettings.MetadataReferences.OfType<PortableExecutableReference>() .Select(r => r.FilePath.GetFileName()) .OrderBy(x => x) .ToArray(); return this; } /// <summary> /// Resets Evaluator. /// <para> /// Resetting means clearing all referenced assemblies, recreating evaluation infrastructure /// (e.g. compiler setting) and reconnection to or recreation of the underlying compiling services. /// </para> /// <para> /// Optionally the default current AppDomain assemblies can be referenced automatically with /// <paramref name="referenceDomainAssemblies"/>. /// </para> /// </summary> /// <param name="referenceDomainAssemblies"> /// if set to <c>true</c> the default assemblies of the current AppDomain will be referenced /// (see <see /// cref="M:CSScriptLib.EvaluatorBase`1.ReferenceDomainAssemblies(CSScriptLib.DomainAssemblies)"/> method). /// </param> /// <returns>The freshly initialized instance of the <see cref="T:CSScriptLib.IEvaluator"/>.</returns> public override IEvaluator Reset(bool referenceDomainAssemblies = true) { CompilerSettings = ScriptOptions.Default; if (referenceDomainAssemblies) ReferenceDomainAssemblies(); return this; } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. The math library included in this project, in addition to being a derivative of the works of Ogre, also include derivative work of the free portion of the Wild Magic mathematics source code that is distributed with the excellent book Game Engine Design. http://www.wild-magic.com/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Collections.Generic; namespace Axiom.MathLib { /// <summary> /// This is a class which exposes static methods for various common math functions. Currently, /// the methods simply wrap the methods of the System.Math class (with the exception of a few added extras). /// This is in case the implementation needs to be swapped out with a faster C++ implementation, if /// deemed that the System.Math methods are not up to far speed wise. /// </summary> /// TODO: Add overloads for all methods for all instrinsic data types (i.e. float, short, etc). public sealed class MathUtil { /// <summary> /// Empty private constructor. This class has nothing but static methods/properties, so a public default /// constructor should not be created by the compiler. This prevents instance of this class from being /// created. /// </summary> private MathUtil() {} static Random random = new Random(); #region Constant public const float PI = (float)Math.PI; public const float TWO_PI = (float)Math.PI * 2.0f; public const float RADIANS_PER_DEGREE = PI / 180.0f; public const float DEGREES_PER_RADIAN = 180.0f / PI; #endregion #region Static Methods /// <summary> /// Converts degrees to radians. /// </summary> /// <param name="degrees"></param> /// <returns></returns> public static float DegreesToRadians(float degrees) { return degrees * RADIANS_PER_DEGREE; } /// <summary> /// Converts radians to degrees. /// </summary> /// <param name="radians"></param> /// <returns></returns> public static float RadiansToDegrees(float radians) { return radians * DEGREES_PER_RADIAN; } /// <summary> /// Returns the sine of the angle. /// </summary> /// <param name="angle"></param> /// <returns></returns> public static float Sin(float angle) { return (float)Math.Sin(angle); } /// <summary> /// Builds a reflection matrix for the specified plane. /// </summary> /// <param name="plane"></param> /// <returns></returns> public static Matrix4 BuildReflectionMatrix(Plane plane) { Vector3 normal = plane.Normal; return new Matrix4( -2 * normal.x * normal.x + 1, -2 * normal.x * normal.y, -2 * normal.x * normal.z, -2 * normal.x * plane.D, -2 * normal.y * normal.x, -2 * normal.y * normal.y + 1, -2 * normal.y * normal.z, -2 * normal.y * plane.D, -2 * normal.z * normal.x, -2 * normal.z * normal.y, -2 * normal.z * normal.z + 1, -2 * normal.z * plane.D, 0, 0, 0, 1); } /// <summary> /// Calculate a face normal, including the w component which is the offset from the origin. /// </summary> /// <param name="v1"></param> /// <param name="v2"></param> /// <param name="v3"></param> /// <returns></returns> public static Vector4 CalculateFaceNormal(Vector3 v1, Vector3 v2, Vector3 v3) { Vector3 normal = CalculateBasicFaceNormal(v1, v2, v3); // Now set up the w (distance of tri from origin return new Vector4(normal.x, normal.y, normal.z, -(normal.Dot(v1))); } /// <summary> /// Calculate a face normal, no w-information. /// </summary> /// <param name="v1"></param> /// <param name="v2"></param> /// <param name="v3"></param> /// <returns></returns> public static Vector3 CalculateBasicFaceNormal(Vector3 v1, Vector3 v2, Vector3 v3) { Vector3 normal = (v2 - v1).Cross(v3 - v1); normal.Normalize(); return normal; } /// <summary> /// Calculates the tangent space vector for a given set of positions / texture coords. /// </summary> /// <remarks> /// Adapted from bump mapping tutorials at: /// http://www.paulsprojects.net/tutorials/simplebump/simplebump.html /// author : [email protected] /// </remarks> /// <param name="position1"></param> /// <param name="position2"></param> /// <param name="position3"></param> /// <param name="u1"></param> /// <param name="v1"></param> /// <param name="u2"></param> /// <param name="v2"></param> /// <param name="u3"></param> /// <param name="v3"></param> /// <returns></returns> public static Vector3 CalculateTangentSpaceVector( Vector3 position1, Vector3 position2, Vector3 position3, float u1, float v1, float u2, float v2, float u3, float v3) { // side0 is the vector along one side of the triangle of vertices passed in, // and side1 is the vector along another side. Taking the cross product of these returns the normal. Vector3 side0 = position1 - position2; Vector3 side1 = position3 - position1; // Calculate face normal Vector3 normal = side1.Cross(side0); normal.Normalize(); // Now we use a formula to calculate the tangent. float deltaV0 = v1 - v2; float deltaV1 = v3 - v1; Vector3 tangent = deltaV1 * side0 - deltaV0 * side1; tangent.Normalize(); // Calculate binormal float deltaU0 = u1 - u2; float deltaU1 = u3 - u1; Vector3 binormal = deltaU1 * side0 - deltaU0 * side1; binormal.Normalize(); // Now, we take the cross product of the tangents to get a vector which // should point in the same direction as our normal calculated above. // If it points in the opposite direction (the dot product between the normals is less than zero), // then we need to reverse the s and t tangents. // This is because the triangle has been mirrored when going from tangent space to object space. // reverse tangents if necessary. Vector3 tangentCross = tangent.Cross(binormal); if (tangentCross.Dot(normal) < 0.0f) { tangent = -tangent; binormal = -binormal; } return tangent; } /// <summary> /// Returns the cosine of the angle. /// </summary> /// <param name="angle"></param> /// <returns></returns> public static float Cos(float angle) { return (float)Math.Cos(angle); } /// <summary> /// Returns the arc cosine of the angle. /// </summary> /// <param name="angle"></param> /// <returns></returns> public static float ACos(float angle) { // HACK: Ok, this needs to be looked at. The decimal precision of float values can sometimes be // *slightly* off from what is loaded from .skeleton files. In some scenarios when we end up having // a cos value calculated above that is just over 1 (i.e. 1.000000012), which the ACos of is Nan, thus // completly throwing off node transformations and rotations associated with an animation. if(angle > 1) { angle = 1.0f; } return (float)Math.Acos(angle); } /// <summary> /// Returns the arc sine of the angle. /// </summary> /// <param name="angle"></param> /// <returns></returns> public static float ASin(float angle) { return (float)Math.Asin(angle); } /// <summary> /// Inverse square root. /// </summary> /// <param name="number"></param> /// <returns></returns> public static float InvSqrt(float number) { return 1 / Sqrt(number); } /// <summary> /// Returns the square root of a number. /// </summary> /// <remarks>This is one of the more expensive math operations. Avoid when possible.</remarks> /// <param name="number"></param> /// <returns></returns> public static float Sqrt(float number) { return (float)Math.Sqrt(number); } /// <summary> /// Returns the absolute value of the supplied number. /// </summary> /// <param name="number"></param> /// <returns></returns> public static float Abs(float number) { return Math.Abs(number); } public static bool FloatEqual(float a, float b) { return FloatEqual(a, b, .00001f); } public static bool FloatEqualTolerent(float a, float b) { return FloatEqual(a, b, .0001f); } /// <summary> /// Compares float values for equality, taking into consideration /// that floating point values should never be directly compared using /// ==. 2 floats could be conceptually equal, but vary by a /// .000001 which would fail in a direct comparison. To circumvent that, /// a tolerance value is used to see if the difference between the 2 floats /// is less than the desired amount of accuracy. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="tolerance"></param> /// <returns></returns> public static bool FloatEqual(float a, float b, float tolerance) { if (Math.Abs(b - a) <= tolerance) { return true; } return false; } /// <summary> /// Returns the tangent of the angle. /// </summary> /// <param name="angle"></param> /// <returns></returns> public static float Tan(float angle) { return (float)Math.Tan(angle); } /// <summary> /// Used to quickly determine the greater value between two values. /// </summary> /// <param name="value1"></param> /// <param name="value2"></param> /// <returns></returns> public static float Max(float value1, float value2) { if(float.IsNaN(value1) || float.IsNaN(value2)) return float.NaN; return (value1 > value2)? value1: value2; } public static float Max(float value1, float value2, float value3) { if(float.IsNaN(value1) || float.IsNaN(value2) || float.IsNaN(value3)) return float.NaN; float max12 = (value1 > value2)? value1: value2; return (max12 > value3)? max12: value3; } public static float Min(float value1, float value2, float value3) { if(float.IsNaN(value1) || float.IsNaN(value2) || float.IsNaN(value3)) return float.NaN; float min12 = (value1 < value2)? value1: value2; return (min12 < value3)? min12: value3; } public static float Max(params float[] vals) { if(vals.Length == 0) throw new ArgumentException("There must be at least one value to compare"); float max = vals[0]; for(int i = 1; i<vals.Length; i++) { float val = vals[i]; if(float.IsNaN(val)) return float.NaN; if(val > max) max = val; } return max; } public static float Min(params float[] vals) { if(vals.Length == 0) throw new ArgumentException("There must be at least one value to compare"); float min = vals[0]; for(int i = 1; i<vals.Length; i++) { float val = vals[i]; if(float.IsNaN(val)) return float.NaN; if(val < min) min = val; } return min; } /// <summary> /// Used to quickly determine the lesser value between two values. /// </summary> /// <param name="value1"></param> /// <param name="value2"></param> /// <returns></returns> public static float Min(float value1, float value2) { return (value1 < value2 || float.IsNaN(value1))? value1: value2; } /// <summary> /// Returns a random value between the specified min and max values. /// </summary> /// <param name="min">Minimum value.</param> /// <param name="max">Maximum value.</param> /// <returns>A random value in the range [min,max].</returns> public static float RangeRandom(float min, float max) { return (max - min) * UnitRandom() + min; } /// <summary> /// /// </summary> /// <returns></returns> public static float UnitRandom() { return (float)random.Next(Int32.MaxValue) / (float)Int32.MaxValue; } /// <summary> /// /// </summary> /// <returns></returns> public static float SymmetricRandom() { return 2.0f * UnitRandom() - 1.0f; } /// <summary> /// Checks wether a given point is inside a triangle, in a /// 2-dimensional (Cartesian) space. /// </summary> /// <remarks> /// The vertices of the triangle must be given in either /// trigonometrical (anticlockwise) or inverse trigonometrical /// (clockwise) order. /// </remarks> /// <param name="px"> /// The X-coordinate of the point. /// </param> /// <param name="py"> /// The Y-coordinate of the point. /// </param> /// <param name="ax"> /// The X-coordinate of the triangle's first vertex. /// </param> /// <param name="ay"> /// The Y-coordinate of the triangle's first vertex. /// </param> /// <param name="bx"> /// The X-coordinate of the triangle's second vertex. /// </param> /// <param name="by"> /// The Y-coordinate of the triangle's second vertex. /// </param> /// <param name="cx"> /// The X-coordinate of the triangle's third vertex. /// </param> /// <param name="cy"> /// The Y-coordinate of the triangle's third vertex. /// </param> /// <returns> /// <list type="bullet"> /// <item> /// <description><b>true</b> - the point resides in the triangle.</description> /// </item> /// <item> /// <description><b>false</b> - the point is outside the triangle</description> /// </item> /// </list> /// </returns> public static bool PointInTri2D( float px, float py, float ax, float ay, float bx, float by, float cx, float cy ) { float v1x, v2x, v1y, v2y; bool bClockwise; v1x = bx - ax; v1y = by - ay; v2x = px - bx; v2y = py - by; bClockwise = ( v1x * v2y - v1y * v2x >= 0.0 ); v1x = cx - bx; v1y = cy - by; v2x = px - cx; v2y = py - cy; if( ( v1x * v2y - v1y * v2x >= 0.0 ) != bClockwise ) return false; v1x = ax - cx; v1y = ay - cy; v2x = px - ax; v2y = py - ay; if( ( v1x * v2y - v1y * v2x >= 0.0 ) != bClockwise ) return false; return true; } static public float GaussianDistribution(float x, float offset, float scale) { double nom = Math.Exp(-1 * ((x-offset) * (x - offset)) / (2 * scale * scale)); double denom = scale * Math.Sqrt(2 * Math.PI); return (float)(nom / denom); } #region Intersection Methods /// <summary> /// Tests an intersection between a ray and a box. /// </summary> /// <param name="ray"></param> /// <param name="box"></param> /// <returns>A Pair object containing whether the intersection occurred, and the distance between the 2 objects.</returns> public static IntersectResult Intersects(Ray ray, AxisAlignedBox box) { if(box.IsNull) { return new IntersectResult(false, 0); } float lowt = 0.0f; float t; bool hit = false; Vector3 hitPoint; Vector3 min = box.Minimum; Vector3 max = box.Maximum; // check origin inside first if(ray.origin > min && ray.origin < max) { return new IntersectResult(true, 0.0f); } // check each face in turn, only check closest 3 // Min X if(ray.origin.x < min.x && ray.direction.x > 0) { t = (min.x - ray.origin.x) / ray.direction.x; if(t > 0) { // substitue t back into ray and check bounds and distance hitPoint = ray.origin + ray.direction * t; if(hitPoint.y >= min.y && hitPoint.y <= max.y && hitPoint.z >= min.z && hitPoint.z <= max.z && (!hit || t < lowt)) { hit = true; lowt = t; } } } // Max X if(ray.origin.x > max.x && ray.direction.x < 0) { t = (max.x - ray.origin.x) / ray.direction.x; if(t > 0) { // substitue t back into ray and check bounds and distance hitPoint = ray.origin + ray.direction * t; if(hitPoint.y >= min.y && hitPoint.y <= max.y && hitPoint.z >= min.z && hitPoint.z <= max.z && (!hit || t < lowt)) { hit = true; lowt = t; } } } // Min Y if(ray.origin.y < min.y && ray.direction.y > 0) { t = (min.y - ray.origin.y) / ray.direction.y; if(t > 0) { // substitue t back into ray and check bounds and distance hitPoint = ray.origin + ray.direction * t; if(hitPoint.x >= min.x && hitPoint.x <= max.x && hitPoint.z >= min.z && hitPoint.z <= max.z && (!hit || t < lowt)) { hit = true; lowt = t; } } } // Max Y if(ray.origin.y > max.y && ray.direction.y < 0) { t = (max.y - ray.origin.y) / ray.direction.y; if(t > 0) { // substitue t back into ray and check bounds and distance hitPoint = ray.origin + ray.direction * t; if(hitPoint.x >= min.x && hitPoint.x <= max.x && hitPoint.z >= min.z && hitPoint.z <= max.z && (!hit || t < lowt)) { hit = true; lowt = t; } } } // Min Z if(ray.origin.z < min.z && ray.direction.z > 0) { t = (min.z - ray.origin.z) / ray.direction.z; if(t > 0) { // substitue t back into ray and check bounds and distance hitPoint = ray.origin + ray.direction * t; if(hitPoint.x >= min.x && hitPoint.x <= max.x && hitPoint.y >= min.y && hitPoint.y <= max.y && (!hit || t < lowt)) { hit = true; lowt = t; } } } // Max Z if(ray.origin.z > max.z && ray.direction.z < 0) { t = (max.z - ray.origin.z) / ray.direction.z; if(t > 0) { // substitue t back into ray and check bounds and distance hitPoint = ray.origin + ray.direction * t; if(hitPoint.x >= min.x && hitPoint.x <= max.x && hitPoint.y >= min.y && hitPoint.y <= max.y && (!hit || t < lowt)) { hit = true; lowt = t; } } } return new IntersectResult(hit, lowt); } /// <summary> /// Tests an intersection between two boxes. /// </summary> /// <param name="boxA"> /// The primary box. /// </param> /// <param name="boxB"> /// The box to test intersection with boxA. /// </param> /// <returns> /// <list type="bullet"> /// <item> /// <description>None - There was no intersection between the 2 boxes.</description> /// </item> /// <item> /// <description>Contained - boxA is fully within boxB.</description> /// </item> /// <item> /// <description>Contains - boxB is fully within boxA.</description> /// </item> /// <item> /// <description>Partial - boxA is partially intersecting with boxB.</description> /// </item> /// </list> /// </returns> /// Submitted by: romout public static Intersection Intersects(AxisAlignedBox boxA, AxisAlignedBox boxB) { // grab the max and mix vectors for both boxes for comparison Vector3 minA = boxA.Minimum; Vector3 maxA = boxA.Maximum; Vector3 minB = boxB.Minimum; Vector3 maxB = boxB.Maximum; if ((minB.x < minA.x) && (maxB.x > maxA.x) && (minB.y < minA.y) && (maxB.y > maxA.y) && (minB.z < minA.z) && (maxB.z > maxA.z)) { // boxA is within boxB return Intersection.Contained; } if ((minB.x > minA.x) && (maxB.x < maxA.x) && (minB.y > minA.y) && (maxB.y < maxA.y) && (minB.z > minA.z) && (maxB.z < maxA.z)) { // boxB is within boxA return Intersection.Contains; } if ((minB.x > maxA.x) || (minB.y > maxA.y) || (minB.z > maxA.z) || (maxB.x < minA.x) || (maxB.y < minA.y) || (maxB.z < minA.z)) { // not interesting at all return Intersection.None; } // if we got this far, they are partially intersecting return Intersection.Partial; } public static IntersectResult Intersects(Ray ray, Sphere sphere) { return Intersects(ray, sphere, false); } /// <summary> /// Ray/Sphere intersection test. /// </summary> /// <param name="ray"></param> /// <param name="sphere"></param> /// <param name="discardInside"></param> /// <returns>Struct that contains a bool (hit?) and distance.</returns> public static IntersectResult Intersects(Ray ray, Sphere sphere, bool discardInside) { Vector3 rayDir = ray.Direction; //Adjust ray origin relative to sphere center Vector3 rayOrig = ray.Origin - sphere.Center; float radius = sphere.Radius; // check origin inside first if((rayOrig.LengthSquared <= radius * radius) && discardInside) { return new IntersectResult(true, 0); } // mmm...sweet quadratics // Build coeffs which can be used with std quadratic solver // ie t = (-b +/- sqrt(b*b* + 4ac)) / 2a float a = rayDir.Dot(rayDir); float b = 2 * rayOrig.Dot(rayDir); float c = rayOrig.Dot(rayOrig) - (radius * radius); // calc determinant float d = (b * b) - (4 * a * c); if(d < 0) { // no intersection return new IntersectResult(false, 0); } else { // BTW, if d=0 there is one intersection, if d > 0 there are 2 // But we only want the closest one, so that's ok, just use the // '-' version of the solver float t = ( -b - MathUtil.Sqrt(d) ) / (2 * a); if (t < 0) { t = ( -b + MathUtil.Sqrt(d)) / (2 * a); } return new IntersectResult(true, t); } } /// <summary> /// Ray/Plane intersection test. /// </summary> /// <param name="ray"></param> /// <param name="plane"></param> /// <returns>Struct that contains a bool (hit?) and distance.</returns> public static IntersectResult Intersects(Ray ray, Plane plane) { float denom = plane.Normal.Dot(ray.Direction); if(MathUtil.Abs(denom) < float.Epsilon) { // Parellel return new IntersectResult(false, 0); } else { float nom = plane.Normal.Dot(ray.Origin) + plane.D; float t = -(nom/denom); return new IntersectResult(t >= 0, t); } } /// <summary> /// Sphere/Box intersection test. /// </summary> /// <param name="sphere"></param> /// <param name="box"></param> /// <returns>True if there was an intersection, false otherwise.</returns> public static bool Intersects(Sphere sphere, AxisAlignedBox box) { if (box.IsNull) return false; // Use splitting planes Vector3 center = sphere.Center; float radius = sphere.Radius; Vector3 min = box.Minimum; Vector3 max = box.Maximum; // just test facing planes, early fail if sphere is totally outside if (center.x < min.x && min.x - center.x > radius) { return false; } if (center.x > max.x && center.x - max.x > radius) { return false; } if (center.y < min.y && min.y - center.y > radius) { return false; } if (center.y > max.y && center.y - max.y > radius) { return false; } if (center.z < min.z && min.z - center.z > radius) { return false; } if (center.z > max.z && center.z - max.z > radius) { return false; } // Must intersect return true; } /// <summary> /// Plane/Box intersection test. /// </summary> /// <param name="plane"></param> /// <param name="box"></param> /// <returns>True if there was an intersection, false otherwise.</returns> public static bool Intersects(Plane plane, AxisAlignedBox box) { if (box.IsNull) return false; // Get corners of the box Vector3[] corners = box.Corners; // Test which side of the plane the corners are // Intersection occurs when at least one corner is on the // opposite side to another PlaneSide lastSide = plane.GetSide(corners[0]); for (int corner = 1; corner < 8; corner++) { if (plane.GetSide(corners[corner]) != lastSide) { return true; } } return false; } /// <summary> /// Sphere/Plane intersection test. /// </summary> /// <param name="sphere"></param> /// <param name="plane"></param> /// <returns>True if there was an intersection, false otherwise.</returns> public static bool Intersects(Sphere sphere, Plane plane) { return MathUtil.Abs(plane.Normal.Dot(sphere.Center)) <= sphere.Radius; } /// <summary> /// Ray/PlaneBoundedVolume intersection test. /// </summary> /// <param name="ray"></param> /// <param name="volume"></param> /// <returns>Struct that contains a bool (hit?) and distance.</returns> public static IntersectResult Intersects(Ray ray, PlaneBoundedVolume volume) { List<Plane> planes = volume.planes; float maxExtDist = 0.0f; float minIntDist = float.PositiveInfinity; float dist, denom, nom; for (int i=0; i < planes.Count; i++) { Plane plane = planes[i]; denom = plane.Normal.Dot(ray.Direction); if (MathUtil.Abs(denom) < float.Epsilon) { // Parallel if (plane.GetSide(ray.Origin) == volume.outside) return new IntersectResult(false, 0); continue; } nom = plane.Normal.Dot(ray.Origin) + plane.D; dist = -(nom/denom); if (volume.outside == PlaneSide.Negative) nom = -nom; if (dist > 0.0f) { if (nom > 0.0f) { if (maxExtDist < dist) maxExtDist = dist; } else { if (minIntDist > dist) minIntDist = dist; } } else { //Ray points away from plane if (volume.outside == PlaneSide.Negative) denom = -denom; if (denom > 0.0f) return new IntersectResult(false, 0); } } if (maxExtDist > minIntDist) return new IntersectResult(false, 0); return new IntersectResult(true, maxExtDist); } #endregion Intersection Methods #endregion Static Methods } #region Structs /// <summary> /// Simple struct to allow returning a complex intersection result. /// </summary> public struct IntersectResult { #region Fields /// <summary> /// Did the intersection test result in a hit? /// </summary> public bool Hit; /// <summary> /// If Hit was true, this will hold a query specific distance value. /// i.e. for a Ray-Box test, the distance will be the distance from the start point /// of the ray to the point of intersection. /// </summary> public float Distance; #endregion Fields /// <summary> /// Constructor. /// </summary> /// <param name="hit"></param> /// <param name="distance"></param> public IntersectResult(bool hit, float distance) { this.Hit = hit; this.Distance = distance; } } #endregion Structs }
using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using NServiceKit.Text.Json; namespace NServiceKit.Text.Common { /// <summary>Provides a contract for mapping properties to their type accessors.</summary> internal interface IPropertyNameResolver { /// <summary>Gets type accessor for property.</summary> /// <param name="propertyName"> Name of the property.</param> /// <param name="typeAccessorMap">The type accessor map.</param> /// <returns>The type accessor for property.</returns> TypeAccessor GetTypeAccessorForProperty(string propertyName, Dictionary<string, TypeAccessor> typeAccessorMap); } /// <summary> /// The default behavior is that the target model must match property names exactly. /// </summary> internal class DefaultPropertyNameResolver : IPropertyNameResolver { /// <summary>Gets type accessor for property.</summary> /// <param name="propertyName"> Name of the property.</param> /// <param name="typeAccessorMap">The type accessor map.</param> /// <returns>The type accessor for property.</returns> public virtual TypeAccessor GetTypeAccessorForProperty(string propertyName, Dictionary<string, TypeAccessor> typeAccessorMap) { TypeAccessor typeAccessor; typeAccessorMap.TryGetValue(propertyName, out typeAccessor); return typeAccessor; } } /// <summary> /// The lenient behavior is that properties on the target model can be .NET-cased, while the /// source JSON can differ. /// </summary> internal class LenientPropertyNameResolver : DefaultPropertyNameResolver { /// <summary>Gets type accessor for property.</summary> /// <param name="propertyName"> Name of the property.</param> /// <param name="typeAccessorMap">The type accessor map.</param> /// <returns>The type accessor for property.</returns> public override TypeAccessor GetTypeAccessorForProperty(string propertyName, Dictionary<string, TypeAccessor> typeAccessorMap) { TypeAccessor typeAccessor; // camelCase is already supported by default, so no need to add another transform in the tree return typeAccessorMap.TryGetValue(TransformFromLowercaseUnderscore(propertyName), out typeAccessor) ? typeAccessor : base.GetTypeAccessorForProperty(propertyName, typeAccessorMap); } /// <summary>Transform from lowercase underscore.</summary> /// <param name="propertyName">Name of the property.</param> /// <returns>A string.</returns> private static string TransformFromLowercaseUnderscore(string propertyName) { // "lowercase-hyphen" -> "lowercase_underscore" -> LowercaseUnderscore return propertyName.Replace("-","_").ToTitleCase(); } } /// <summary>A deserialize type reference json.</summary> internal static class DeserializeTypeRefJson { /// <summary>The default property name resolver.</summary> public static readonly IPropertyNameResolver DefaultPropertyNameResolver = new DefaultPropertyNameResolver(); /// <summary>The lenient property name resolver.</summary> public static readonly IPropertyNameResolver LenientPropertyNameResolver = new LenientPropertyNameResolver(); /// <summary>The property name resolver.</summary> public static IPropertyNameResolver PropertyNameResolver = DefaultPropertyNameResolver; /// <summary>The serializer.</summary> private static readonly JsonTypeSerializer Serializer = (JsonTypeSerializer)JsonTypeSerializer.Instance; /// <summary>String to type.</summary> /// <exception cref="CreateSerializationError"> Thrown when a create serialization error error /// condition occurs.</exception> /// <exception cref="GetSerializationException">Thrown when a Get Serialization error condition /// occurs.</exception> /// <param name="type"> The type.</param> /// <param name="strType"> The type.</param> /// <param name="ctorFn"> The constructor function.</param> /// <param name="typeAccessorMap">The type accessor map.</param> /// <returns>An object.</returns> internal static object StringToType( Type type, string strType, EmptyCtorDelegate ctorFn, Dictionary<string, TypeAccessor> typeAccessorMap) { var index = 0; if (strType == null) return null; //if (!Serializer.EatMapStartChar(strType, ref index)) for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline if (strType[index++] != JsWriter.MapStartChar) throw DeserializeTypeRef.CreateSerializationError(type, strType); if (JsonTypeSerializer.IsEmptyMap(strType, index)) return ctorFn(); object instance = null; var strTypeLength = strType.Length; while (index < strTypeLength) { var propertyName = JsonTypeSerializer.ParseJsonString(strType, ref index); //Serializer.EatMapKeySeperator(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline if (strType.Length != index) index++; var propertyValueStr = Serializer.EatValue(strType, ref index); var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1; //if we already have an instance don't check type info, because then we will have a half deserialized object //we could throw here or just use the existing instance. if (instance == null && possibleTypeInfo && propertyName == JsWriter.TypeAttr) { var explicitTypeName = Serializer.ParseString(propertyValueStr); var explicitType = AssemblyUtils.FindType(explicitTypeName); if (explicitType != null && !explicitType.IsInterface() && !explicitType.IsAbstract()) { instance = explicitType.CreateInstance(); } if (instance == null) { Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr); } else { //If __type info doesn't match, ignore it. if (!type.InstanceOfType(instance)) { instance = null; } else { var derivedType = instance.GetType(); if (derivedType != type) { var derivedTypeConfig = new TypeConfig(derivedType); var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer); if (map != null) { typeAccessorMap = map; } } } } Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); continue; } if (instance == null) instance = ctorFn(); var typeAccessor = PropertyNameResolver.GetTypeAccessorForProperty(propertyName, typeAccessorMap); var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null; if (propType != null) { try { if (typeAccessor != null) { //var parseFn = Serializer.GetParseFn(propType); var parseFn = JsonReader.GetParseFn(propType); var propertyValue = parseFn(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline if (index != strType.Length) { var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar; index++; if (success) for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline } continue; } catch (Exception e) { if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e); else Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr); } } if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null) { try { var propertyValue = typeAccessor.GetProperty(propertyValueStr); typeAccessor.SetProperty(instance, propertyValue); } catch (Exception e) { if (JsConfig.ThrowOnDeserializationError) throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, typeAccessor.PropertyType, e); else Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr); } } //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index); for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline if (index != strType.Length) { var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar; index++; if (success) for (; index < strType.Length; index++) { var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c]) break; } //Whitespace inline } } return instance; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Tools; using Xunit; namespace System.Numerics.Tests { public class op_modulusTest { private static int s_samples = 10; private static Random s_temp = new Random(-210220377); private static Random s_random = new Random(100); [Fact] public static void RunRemainderTestsPositive() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Remainder Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "b%"); } // Remainder Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "b%"); } // Remainder Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "b%"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "b%"); } } [Fact] public static void RunRemainderNegative() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Remainder Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "b%"); Assert.Throws<DivideByZeroException>(() => { VerifyRemainderString(Print(tempByteArray2) + Print(tempByteArray1) + "b%"); }); } // Remainder Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "b%"); Assert.Throws<DivideByZeroException>(() => { VerifyRemainderString(Print(tempByteArray2) + Print(tempByteArray1) + "b%"); }); } } [Fact] public static void RunRemainderBoundary() { 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 VerifyRemainderString(Math.Pow(2, 32) + " 2 b%"); // 32 bit boundary n1=0 n2=1 VerifyRemainderString(Math.Pow(2, 33) + " 2 b%"); } [Fact] public static void RunRemainderAxiomXModX() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X%X = 0 VerifyIdentityString(Int32.MaxValue + " " + Int32.MaxValue + " b%", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + Int64.MaxValue + " b%", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + randBigInt + "b%", BigInteger.Zero.ToString()); } } [Fact] public static void RunRemainderAxiomXY() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X%(X + Y) = X where Y is 1 if x>=0 and -1 if x<0 VerifyIdentityString((new BigInteger(Int32.MaxValue) + 1) + " " + Int32.MaxValue + " b%", Int32.MaxValue.ToString()); VerifyIdentityString((new BigInteger(Int64.MaxValue) + 1) + " " + Int64.MaxValue + " b%", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { byte[] test = GetRandomByteArray(s_random); String randBigInt = Print(test); BigInteger modify = new BigInteger(1); if ((test[test.Length - 1] & 0x80) != 0) { modify = BigInteger.Negate(modify); } VerifyIdentityString(randBigInt + modify.ToString() + " bAdd " + randBigInt + "b%", randBigInt.Substring(0, randBigInt.Length - 1)); } } [Fact] public static void RunRemainderAxiomXMod1() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X%1 = 0 VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " b%", BigInteger.Zero.ToString()); VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " b%", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(BigInteger.One + " " + randBigInt + "b%", BigInteger.Zero.ToString()); } } [Fact] public static void RunRemainderAxiom0ModX() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: 0%X = 0 VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b%", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b%", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " b%", BigInteger.Zero.ToString()); } } private static void VerifyRemainderString(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); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Net.Http; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using SafeCurlHandle = Interop.libcurl.SafeCurlHandle; using CURLoption = Interop.libcurl.CURLoption; using CURLcode = Interop.libcurl.CURLcode; using CURLINFO = Interop.libcurl.CURLINFO; using CURLProxyType = Interop.libcurl.curl_proxytype; namespace System.Net.Http { internal class CurlHandler : HttpMessageHandler { #region Constants private const string UriSchemeHttps = "https"; private readonly static string[] AuthenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes #endregion #region Fields private volatile bool _anyOperationStarted; private volatile bool _disposed; private bool _automaticRedirection = true; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; #endregion internal CurlHandler() { } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); if (value) { _proxyPolicy = ProxyUsePolicy.UseCustomProxy; } else { _proxyPolicy = ProxyUsePolicy.DoNotUseProxy; } } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { CheckDisposedOrStarted(); _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return ClientCertificateOption.Manual; } set { if (ClientCertificateOption.Manual != value) { throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option); } } } #endregion protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if (request.Content != null) { throw NotImplemented.ByDesignWithMessage("HTTP requests with a body are not yet supported"); } CheckDisposed(); SetOperationStarted(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create RequestCompletionSource object and save current values of handler settings. RequestCompletionSource state = new RequestCompletionSource(); state.CancellationToken = cancellationToken; state.RequestMessage = request; state.Handler = this; Task.Factory.StartNew( s => { var rcs = (RequestCompletionSource)s; rcs.Handler.StartRequest(rcs); }, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return state.Task; } #region Private methods private void StartRequest(RequestCompletionSource state) { HttpResponseMessage responseMessage = null; SafeCurlHandle requestHandle = null; if (state.CancellationToken.IsCancellationRequested) { state.TrySetCanceled(); return; } var cancellationTokenRegistration = state.CancellationToken.Register(x => ((RequestCompletionSource) x).TrySetCanceled(), state); try { requestHandle = CreateRequestHandle(state); state.CancellationToken.ThrowIfCancellationRequested(); int result = Interop.libcurl.curl_easy_perform(requestHandle); if (CURLcode.CURLE_OK != result) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } // TODO: Handle requests with body state.CancellationToken.ThrowIfCancellationRequested(); responseMessage = CreateResponseMessage(requestHandle, state.RequestMessage); state.TrySetResult(responseMessage); } catch (Exception ex) { HandleAsyncException(state, ex); } finally { SafeCurlHandle.DisposeAndClearHandle(ref requestHandle); cancellationTokenRegistration.Dispose(); } } private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private SafeCurlHandle CreateRequestHandle(RequestCompletionSource state) { // TODO: If this impacts perf, optimize using a handle pool SafeCurlHandle requestHandle = Interop.libcurl.curl_easy_init(); if (requestHandle.IsInvalid) { throw new HttpRequestException(SR.net_http_client_execution_error); } Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_URL, state.RequestMessage.RequestUri.OriginalString); if (_automaticRedirection) { Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_FOLLOWLOCATION, 1); } SetProxyOptions(state, requestHandle); // TODO: Handle headers and other options return requestHandle; } private static void SetProxyOptions(RequestCompletionSource state, SafeCurlHandle requestHandle) { var requestUri = state.RequestMessage.RequestUri; Debug.Assert(state.Handler != null); if (state.Handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy) { Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXY, string.Empty); return; } if ((state.Handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) || (state.Handler.Proxy == null)) { return; } Debug.Assert( (state.Handler.Proxy != null) && (state.Handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy)); if (state.Handler.Proxy.IsBypassed(requestUri)) { Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXY, string.Empty); return; } var proxyUri = state.Handler.Proxy.GetProxy(requestUri); if (proxyUri == null) { return; } Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXYTYPE, CURLProxyType.CURLPROXY_HTTP); Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri); Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); NetworkCredential credentials = GetCredentials(state.Handler.Proxy.Credentials, requestUri); if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } string credentialText; if (string.IsNullOrEmpty(credentials.Domain)) { credentialText = string.Format("{0}:{1}", credentials.UserName, credentials.Password); } else { credentialText = string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain); } Interop.libcurl.curl_easy_setopt(requestHandle, CURLoption.CURLOPT_PROXYUSERPWD, credentialText); } } private static NetworkCredential GetCredentials(ICredentials proxyCredentials, Uri requestUri) { if (proxyCredentials == null) { return null; } foreach (var authScheme in AuthenticationSchemes) { NetworkCredential proxyCreds = proxyCredentials.GetCredential(requestUri, authScheme); if (proxyCreds != null) { return proxyCreds; } } return null; } private HttpResponseMessage CreateResponseMessage(SafeCurlHandle requestHandle, HttpRequestMessage request) { var response = new HttpResponseMessage(); long httpStatusCode = 0; int result = Interop.libcurl.curl_easy_getinfo(requestHandle, CURLINFO.CURLINFO_RESPONSE_CODE, ref httpStatusCode); if (CURLcode.CURLE_OK != result) { throw new HttpRequestException(SR.net_http_client_execution_error, GetCurlException(result)); } response.StatusCode = (HttpStatusCode)httpStatusCode; // TODO: Do error processing if needed and return actual response response.Content = new StringContent("SendAsync to " + request.RequestUri.OriginalString + " returned: " + response.StatusCode); return response; } private void HandleAsyncException(RequestCompletionSource state, Exception ex) { if (ex is OperationCanceledException) { // If the exception was due to the cancellation token being canceled, throw cancellation exception. Debug.Assert(state.CancellationToken.IsCancellationRequested); state.TrySetCanceled(); } else if (ex is HttpRequestException) { state.TrySetException(ex); } else { state.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex)); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private string GetCurlErrorString(int code) { IntPtr ptr = Interop.libcurl.curl_easy_strerror(code); return Marshal.PtrToStringAnsi(ptr); } private Exception GetCurlException(int code) { return new Exception(GetCurlErrorString(code)); } #endregion private sealed class RequestCompletionSource : TaskCompletionSource<HttpResponseMessage> { public CancellationToken CancellationToken { get; set; } public HttpRequestMessage RequestMessage { get; set; } public CurlHandler Handler { get; set; } } private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
using NUnit.Framework; namespace DotSpatial.Projections.Tests.Projected { /// <summary> /// This class contains all the tests for the StatePlaneNad1983Feet category of Projected coordinate systems /// </summary> [TestFixture] public class StatePlaneNad1983Feet { /// <summary> /// Creates a new instance of the Africa Class /// </summary> [SetUp] public void Initialize() { } [Test] public void NAD1983StatePlaneAlabamaEastFIPS0101Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlabamaEastFIPS0101Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlabamaWestFIPS0102Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlabamaWestFIPS0102Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska10FIPS5010Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska10FIPS5010Feet; Tester.TestProjection(pStart); } [Test] [Ignore("Verify this test")] public void NAD1983StatePlaneAlaska1FIPS5001Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska1FIPS5001Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska2FIPS5002Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska2FIPS5002Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska3FIPS5003Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska3FIPS5003Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska4FIPS5004Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska4FIPS5004Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska5FIPS5005Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska5FIPS5005Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska6FIPS5006Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska6FIPS5006Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska7FIPS5007Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska7FIPS5007Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska8FIPS5008Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska8FIPS5008Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneAlaska9FIPS5009Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneAlaska9FIPS5009Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneArizonaCentralFIPS0202Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneArizonaCentralFIPS0202Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneArizonaEastFIPS0201Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneArizonaEastFIPS0201Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneArizonaWestFIPS0203Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneArizonaWestFIPS0203Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneArkansasNorthFIPS0301Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneArkansasNorthFIPS0301Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneArkansasSouthFIPS0302Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneArkansasSouthFIPS0302Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneCaliforniaIFIPS0401Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneCaliforniaIFIPS0401Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneCaliforniaIIFIPS0402Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneCaliforniaIIFIPS0402Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneCaliforniaIIIFIPS0403Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneCaliforniaIIIFIPS0403Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneCaliforniaIVFIPS0404Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneCaliforniaIVFIPS0404Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneCaliforniaVFIPS0405Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneCaliforniaVFIPS0405Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneCaliforniaVIFIPS0406Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneCaliforniaVIFIPS0406Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneColoradoCentralFIPS0502Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneColoradoCentralFIPS0502Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneColoradoNorthFIPS0501Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneColoradoNorthFIPS0501Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneColoradoSouthFIPS0503Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneColoradoSouthFIPS0503Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneConnecticutFIPS0600Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneConnecticutFIPS0600Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneDelawareFIPS0700Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneDelawareFIPS0700Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneFloridaEastFIPS0901Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneFloridaEastFIPS0901Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneFloridaNorthFIPS0903Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneFloridaNorthFIPS0903Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneFloridaWestFIPS0902Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneFloridaWestFIPS0902Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneGeorgiaEastFIPS1001Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneGeorgiaEastFIPS1001Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneGeorgiaWestFIPS1002Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneGeorgiaWestFIPS1002Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneGuamFIPS5400Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneGuamFIPS5400Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneHawaii1FIPS5101Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneHawaii1FIPS5101Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneHawaii2FIPS5102Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneHawaii2FIPS5102Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneHawaii3FIPS5103Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneHawaii3FIPS5103Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneHawaii4FIPS5104Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneHawaii4FIPS5104Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneHawaii5FIPS5105Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneHawaii5FIPS5105Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIdahoCentralFIPS1102Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIdahoCentralFIPS1102Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIdahoEastFIPS1101Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIdahoEastFIPS1101Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIdahoWestFIPS1103Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIdahoWestFIPS1103Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIllinoisEastFIPS1201Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIllinoisEastFIPS1201Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIllinoisWestFIPS1202Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIllinoisWestFIPS1202Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIndianaEastFIPS1301Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIndianaEastFIPS1301Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIndianaWestFIPS1302Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIndianaWestFIPS1302Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIowaNorthFIPS1401Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIowaNorthFIPS1401Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneIowaSouthFIPS1402Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneIowaSouthFIPS1402Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneKansasNorthFIPS1501Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneKansasNorthFIPS1501Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneKansasSouthFIPS1502Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneKansasSouthFIPS1502Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneKentuckyFIPS1600Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneKentuckyFIPS1600Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneKentuckyNorthFIPS1601Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneKentuckyNorthFIPS1601Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneKentuckySouthFIPS1602Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneKentuckySouthFIPS1602Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneLouisianaNorthFIPS1701Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneLouisianaNorthFIPS1701Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneLouisianaSouthFIPS1702Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneLouisianaSouthFIPS1702Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMaineEastFIPS1801Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMaineEastFIPS1801Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMaineWestFIPS1802Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMaineWestFIPS1802Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMarylandFIPS1900Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMarylandFIPS1900Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMassachusettsIslandFIPS2002Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMassachusettsIslandFIPS2002Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMassachusettsMainlandFIPS2001Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMassachusettsMainlandFIPS2001Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMichiganCentralFIPS2112Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMichiganCentralFIPS2112Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMichiganNorthFIPS2111Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMichiganNorthFIPS2111Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMichiganSouthFIPS2113Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMichiganSouthFIPS2113Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMinnesotaCentralFIPS2202Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMinnesotaCentralFIPS2202Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMinnesotaNorthFIPS2201Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMinnesotaNorthFIPS2201Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMinnesotaSouthFIPS2203Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMinnesotaSouthFIPS2203Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMississippiEastFIPS2301Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMississippiEastFIPS2301Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMississippiWestFIPS2302Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMississippiWestFIPS2302Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMissouriCentralFIPS2402Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMissouriCentralFIPS2402Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMissouriEastFIPS2401Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMissouriEastFIPS2401Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMissouriWestFIPS2403Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMissouriWestFIPS2403Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneMontanaFIPS2500Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneMontanaFIPS2500Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNebraskaFIPS2600Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNebraskaFIPS2600Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNevadaCentralFIPS2702Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNevadaCentralFIPS2702Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNevadaEastFIPS2701Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNevadaEastFIPS2701Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNevadaWestFIPS2703Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNevadaWestFIPS2703Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewHampshireFIPS2800Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewHampshireFIPS2800Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewJerseyFIPS2900Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewJerseyFIPS2900Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewMexicoCentralFIPS3002Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewMexicoCentralFIPS3002Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewMexicoEastFIPS3001Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewMexicoEastFIPS3001Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewMexicoWestFIPS3003Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewMexicoWestFIPS3003Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewYorkCentralFIPS3102Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewYorkCentralFIPS3102Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewYorkEastFIPS3101Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewYorkEastFIPS3101Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewYorkLongIslandFIPS3104Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewYorkLongIslandFIPS3104Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNewYorkWestFIPS3103Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNewYorkWestFIPS3103Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNorthCarolinaFIPS3200Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNorthCarolinaFIPS3200Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNorthDakotaNorthFIPS3301Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNorthDakotaNorthFIPS3301Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneNorthDakotaSouthFIPS3302Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneNorthDakotaSouthFIPS3302Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneOhioNorthFIPS3401Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneOhioNorthFIPS3401Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneOhioSouthFIPS3402Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneOhioSouthFIPS3402Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneOklahomaNorthFIPS3501Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneOklahomaNorthFIPS3501Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneOklahomaSouthFIPS3502Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneOklahomaSouthFIPS3502Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneOregonNorthFIPS3601Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneOregonNorthFIPS3601Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneOregonSouthFIPS3602Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneOregonSouthFIPS3602Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlanePennsylvaniaNorthFIPS3701Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlanePennsylvaniaNorthFIPS3701Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlanePennsylvaniaSouthFIPS3702Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlanePennsylvaniaSouthFIPS3702Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlanePRVirginIslandsFIPS5200Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlanePRVirginIslandsFIPS5200Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneRhodeIslandFIPS3800Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneRhodeIslandFIPS3800Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneSouthCarolinaFIPS3900Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneSouthCarolinaFIPS3900Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneSouthDakotaNorthFIPS4001Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneSouthDakotaNorthFIPS4001Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneSouthDakotaSouthFIPS4002Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneSouthDakotaSouthFIPS4002Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneTennesseeFIPS4100Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneTennesseeFIPS4100Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneTexasCentralFIPS4203Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneTexasCentralFIPS4203Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneTexasNorthCentralFIPS4202Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneTexasNorthCentralFIPS4202Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneTexasNorthFIPS4201Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneTexasNorthFIPS4201Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneTexasSouthCentralFIPS4204Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneTexasSouthCentralFIPS4204Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneTexasSouthFIPS4205Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneTexasSouthFIPS4205Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneUtahCentralFIPS4302Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneUtahCentralFIPS4302Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneUtahNorthFIPS4301Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneUtahNorthFIPS4301Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneUtahSouthFIPS4303Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneUtahSouthFIPS4303Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneVermontFIPS4400Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneVermontFIPS4400Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneVirginiaNorthFIPS4501Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneVirginiaNorthFIPS4501Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneVirginiaSouthFIPS4502Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneVirginiaSouthFIPS4502Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWashingtonNorthFIPS4601Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWashingtonNorthFIPS4601Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWashingtonSouthFIPS4602Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWashingtonSouthFIPS4602Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWestVirginiaNorthFIPS4701Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWestVirginiaNorthFIPS4701Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWestVirginiaSouthFIPS4702Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWestVirginiaSouthFIPS4702Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWisconsinCentralFIPS4802Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWisconsinCentralFIPS4802Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWisconsinNorthFIPS4801Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWisconsinNorthFIPS4801Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWisconsinSouthFIPS4803Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWisconsinSouthFIPS4803Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWyomingEastCentralFIPS4902Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWyomingEastCentralFIPS4902Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWyomingEastFIPS4901Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWyomingEastFIPS4901Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWyomingWestCentralFIPS4903Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWyomingWestCentralFIPS4903Feet; Tester.TestProjection(pStart); } [Test] public void NAD1983StatePlaneWyomingWestFIPS4904Feet() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.StatePlaneNad1983Feet.NAD1983StatePlaneWyomingWestFIPS4904Feet; Tester.TestProjection(pStart); } } }
// // 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.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql { /// <summary> /// Contains the operation to create restore requests for Azure SQL /// Databases. /// </summary> internal partial class RestoreDatabaseOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IRestoreDatabaseOperations { /// <summary> /// Initializes a new instance of the RestoreDatabaseOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RestoreDatabaseOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Issues a restore request for an Azure SQL Database. /// </summary> /// <param name='sourceServerName'> /// Required. The name of the Azure SQL Database Server where the /// source database is, or was, hosted. /// </param> /// <param name='parameters'> /// Required. Additional parameters for the Create Restore Database /// Operation request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response to the Create Restore Database Operation /// request. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.RestoreDatabaseOperationCreateResponse> CreateAsync(string sourceServerName, RestoreDatabaseOperationCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (sourceServerName == null) { throw new ArgumentNullException("sourceServerName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.SourceDatabaseName == null) { throw new ArgumentNullException("parameters.SourceDatabaseName"); } if (parameters.TargetDatabaseName == null) { throw new ArgumentNullException("parameters.TargetDatabaseName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("sourceServerName", sourceServerName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + sourceServerName.Trim() + "/restoredatabaseoperations"; 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 httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(serviceResourceElement); XElement sourceDatabaseNameElement = new XElement(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure")); sourceDatabaseNameElement.Value = parameters.SourceDatabaseName; serviceResourceElement.Add(sourceDatabaseNameElement); if (parameters.SourceDatabaseDeletionDate != null) { XElement sourceDatabaseDeletionDateElement = new XElement(XName.Get("SourceDatabaseDeletionDate", "http://schemas.microsoft.com/windowsazure")); sourceDatabaseDeletionDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.SourceDatabaseDeletionDate.Value.ToUniversalTime()); serviceResourceElement.Add(sourceDatabaseDeletionDateElement); } if (parameters.TargetServerName != null) { XElement targetServerNameElement = new XElement(XName.Get("TargetServerName", "http://schemas.microsoft.com/windowsazure")); targetServerNameElement.Value = parameters.TargetServerName; serviceResourceElement.Add(targetServerNameElement); } XElement targetDatabaseNameElement = new XElement(XName.Get("TargetDatabaseName", "http://schemas.microsoft.com/windowsazure")); targetDatabaseNameElement.Value = parameters.TargetDatabaseName; serviceResourceElement.Add(targetDatabaseNameElement); if (parameters.PointInTime != null) { XElement targetUtcPointInTimeElement = new XElement(XName.Get("TargetUtcPointInTime", "http://schemas.microsoft.com/windowsazure")); targetUtcPointInTimeElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PointInTime.Value.ToUniversalTime()); serviceResourceElement.Add(targetUtcPointInTimeElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result RestoreDatabaseOperationCreateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RestoreDatabaseOperationCreateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); if (serviceResourceElement2 != null) { RestoreDatabaseOperation serviceResourceInstance = new RestoreDatabaseOperation(); result.Operation = serviceResourceInstance; XElement requestIDElement = serviceResourceElement2.Element(XName.Get("RequestID", "http://schemas.microsoft.com/windowsazure")); if (requestIDElement != null) { string requestIDInstance = requestIDElement.Value; serviceResourceInstance.Id = requestIDInstance; } XElement sourceDatabaseNameElement2 = serviceResourceElement2.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure")); if (sourceDatabaseNameElement2 != null) { string sourceDatabaseNameInstance = sourceDatabaseNameElement2.Value; serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance; } XElement sourceDatabaseDeletionDateElement2 = serviceResourceElement2.Element(XName.Get("SourceDatabaseDeletionDate", "http://schemas.microsoft.com/windowsazure")); if (sourceDatabaseDeletionDateElement2 != null && string.IsNullOrEmpty(sourceDatabaseDeletionDateElement2.Value) == false) { DateTime sourceDatabaseDeletionDateInstance = DateTime.Parse(sourceDatabaseDeletionDateElement2.Value, CultureInfo.InvariantCulture); serviceResourceInstance.SourceDatabaseDeletionDate = sourceDatabaseDeletionDateInstance; } XElement targetServerNameElement2 = serviceResourceElement2.Element(XName.Get("TargetServerName", "http://schemas.microsoft.com/windowsazure")); if (targetServerNameElement2 != null) { string targetServerNameInstance = targetServerNameElement2.Value; serviceResourceInstance.TargetServerName = targetServerNameInstance; } XElement targetDatabaseNameElement2 = serviceResourceElement2.Element(XName.Get("TargetDatabaseName", "http://schemas.microsoft.com/windowsazure")); if (targetDatabaseNameElement2 != null) { string targetDatabaseNameInstance = targetDatabaseNameElement2.Value; serviceResourceInstance.TargetDatabaseName = targetDatabaseNameInstance; } XElement targetUtcPointInTimeElement2 = serviceResourceElement2.Element(XName.Get("TargetUtcPointInTime", "http://schemas.microsoft.com/windowsazure")); if (targetUtcPointInTimeElement2 != null) { DateTime targetUtcPointInTimeInstance = DateTime.Parse(targetUtcPointInTimeElement2.Value, CultureInfo.InvariantCulture); serviceResourceInstance.PointInTime = targetUtcPointInTimeInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Xamarin.Auth; using System.Security.Policy; namespace Auth0.SDK { /// <summary> /// A simple client to Authenticate Users with Auth0. /// </summary> public partial class Auth0Client { protected string Domain { get; set; } protected string ClientId { get; set; } public Auth0Client (string domain, string clientId) { this.Domain = domain; this.ClientId = clientId; this.DeviceIdProvider = new DeviceIdProvider(); } public Auth0User CurrentUser { get; protected set; } /// <summary> /// The component used to generate the device's unique id /// </summary> public IDeviceIdProvider DeviceIdProvider { get; set; } public bool RetrieveProfile { get; set; } public string CallbackUrl { get { return string.Format(Auth0Constants.DefaultCallback, this.Domain); } } /// <summary> /// Log a user into an Auth0 application given an user name and password. /// </summary> /// <returns>Task that will complete when the user has finished authentication.</returns> /// <param name="connection" type="string">The name of the connection to use in Auth0. Connection defines an Identity Provider.</param> /// <param name="userName" type="string">User name.</param> /// <param name="password type="string"">User password.</param> public Task<Auth0User> LoginAsync(string connection, string userName, string password, bool withRefreshToken = false, string scope = "openid") { var endpoint = string.Format(Auth0Constants.ResourceOwnerEndpoint, this.Domain); var scopeParameter = IncreaseScopeWithOfflineAccess (withRefreshToken, scope); var parameters = new Dictionary<string, string> { { "client_id", this.ClientId }, { "connection", connection }, { "username", userName }, { "password", password }, { "grant_type", "password" }, { "scope", scopeParameter } }; if (ScopeHasOfflineAccess (scopeParameter)) { var deviceId = this.DeviceIdProvider.GetDeviceId ().Result; parameters ["device"] = deviceId; } var request = new Request ("POST", new Uri(endpoint), parameters); return request.GetResponseAsync ().ContinueWith<Auth0User>(t => { try { var text = t.Result.GetResponseText(); var data = JObject.Parse(text).ToObject<Dictionary<string, string>>(); if (data.ContainsKey ("error")) { throw new AuthException ("Error authenticating: " + data["error"]); } else if (data.ContainsKey ("access_token")) { this.SetupCurrentUser (data); } else { throw new AuthException ("Expected access_token in access token response, but did not receive one."); } } catch (Exception ex) { throw ex; } return this.CurrentUser; }); } /// <summary> /// Verifies if the jwt for the current user has expired. /// </summary> /// <returns>true if the token has expired, false otherwise.</returns> /// <remarks>Must be logged in before invoking.</remarks> public bool HasTokenExpired() { if (string.IsNullOrEmpty(this.CurrentUser.IdToken)) { throw new InvalidOperationException("You need to login first."); } return TokenValidator.HasExpired(this.CurrentUser.IdToken); } /// <summary> /// Renews the idToken (JWT) /// </summary> /// <returns>The refreshed token.</returns> /// <remarks>The JWT must not have expired.</remarks> /// <param name="options">Additional parameters.</param> public Task<JObject> RenewIdToken(Dictionary<string, string> options = null) { if (string.IsNullOrEmpty(this.CurrentUser.IdToken)) { throw new InvalidOperationException("You need to login first."); } options = options ?? new Dictionary<string, string>(); if (!options.ContainsKey("scope")) { options["scope"] = "passthrough"; } return this.GetDelegationToken( api: "app", idToken: this.CurrentUser.IdToken, options: options); } /// <summary> /// Renews the idToken (JWT) /// </summary> /// <returns>The refreshed token.</returns> /// <param name="refreshToken" type="string">The refresh token to use. If null, the logged in users token will be used.</param> /// <param name="options">Additional parameters.</param> public async Task<JObject> RefreshToken( string refreshToken = "", Dictionary<string, string> options = null) { var emptyToken = string.IsNullOrEmpty(refreshToken); if (emptyToken && (this.CurrentUser == null || string.IsNullOrEmpty(this.CurrentUser.RefreshToken))) { throw new InvalidOperationException( "The current user's refresh token could not be retrieved or no refresh token was provided as parameter."); } return await this.GetDelegationToken( api: "app", refreshToken: emptyToken ? this.CurrentUser.RefreshToken : refreshToken, options: options); } /// <summary> /// Get a delegation token /// </summary> /// <returns>Delegation token result.</returns> /// <param name="api">The type of the API to be used.</param> /// <param name="idToken">The string representing the JWT. Useful only if not expired.</param> /// <param name="refreshToken">The refresh token.</param> /// <param name="targetClientId">The clientId of the target application for which to obtain a delegation token.</param> /// <param name="options">Additional parameters.</param> public async Task<JObject> GetDelegationToken( string api = "", string idToken = "", string refreshToken = "", string targetClientId = "", Dictionary<string, string> options = null) { if (!(string.IsNullOrEmpty(idToken) || string.IsNullOrEmpty(refreshToken))) { throw new InvalidOperationException( "You must provide either the idToken parameter or the refreshToken parameter, not both."); } if (string.IsNullOrEmpty(idToken) && string.IsNullOrEmpty(refreshToken)) { if (this.CurrentUser == null || string.IsNullOrEmpty(this.CurrentUser.IdToken)){ throw new InvalidOperationException( "You need to login first or specify a value for idToken or refreshToken parameter."); } idToken = this.CurrentUser.IdToken; } options = options ?? new Dictionary<string, string>(); options["id_token"] = idToken; options["api_type"] = api; options["refresh_token"] = refreshToken; options["target"] = targetClientId; options["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"; options ["client_id"] = this.ClientId; var endpoint = string.Format(Auth0Constants.DelegationEndpoint, this.Domain); options = options .Where (kvp => !string.IsNullOrEmpty (kvp.Value)) .ToDictionary (kvp => kvp.Key, kvp => kvp.Value); var request = new Request ("POST", new Uri(endpoint), options); var result = await request.GetResponseAsync (); try { var text = result.GetResponseText(); var data = JObject.Parse(text); JToken temp = null; if(data.TryGetValue("id_token", out temp)) { var jwt = temp.Value<string>(); this.CurrentUser = this.CurrentUser ?? new Auth0User() { RefreshToken = refreshToken }; this.CurrentUser.IdToken = jwt; } return data; } catch (Exception) { throw; } } /// <summary> /// Log a user out of a Auth0 application. /// </summary> public void Logout() { this.CurrentUser = null; WebAuthenticator.ClearCookies(); } /// <summary> /// Gets the WebRedirectAuthenticator. /// </summary> /// <returns>The authenticator.</returns> /// <param name="connection">Connection name.</param> /// <param name="scope">OpenID scope.</param> /// <param name="deviceName">The device name to use if gettting a refresh token.</param> protected virtual async Task<WebRedirectAuthenticator> GetAuthenticator(string connection, string scope) { // Generate state to include in startUri var chars = new char[16]; var rand = new Random (); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next ((int)'a', (int)'z' + 1); } var redirectUri = this.CallbackUrl; var authorizeUri = !string.IsNullOrWhiteSpace (connection) ? string.Format(Auth0Constants.AuthorizeUrl, this.Domain, this.ClientId, Uri.EscapeDataString(redirectUri), connection, scope) : string.Format(Auth0Constants.LoginWidgetUrl, this.Domain, this.ClientId, Uri.EscapeDataString(redirectUri), scope); if (ScopeHasOfflineAccess("offline_access")) { var deviceId = Uri.EscapeDataString(await this.DeviceIdProvider.GetDeviceId()); authorizeUri += string.Format("&device={0}", deviceId); } var state = new string (chars); var startUri = new Uri (authorizeUri + "&state=" + state); var endUri = new Uri (redirectUri); var auth = new WebRedirectAuthenticator (startUri, endUri); auth.ClearCookiesBeforeLogin = false; return auth; } private static string IncreaseScopeWithOfflineAccess(bool withRefreshToken, string scope) { if (withRefreshToken && !ScopeHasOfflineAccess(scope)) { scope += " offline_access"; } return scope; } private static bool ScopeHasOfflineAccess(string scope) { return scope .Split(new string[0], StringSplitOptions.RemoveEmptyEntries) .Any(e => e.Equals("offline_access", StringComparison.InvariantCultureIgnoreCase)); } protected void SetupCurrentUser(IDictionary<string, string> accountProperties) { if (this.RetrieveProfile) { var endpoint = string.Format(Auth0Constants.UserInfoEndpoint, this.Domain, accountProperties["access_token"]); var request = new Request("GET", new Uri(endpoint)); request.GetResponseAsync().ContinueWith(t => { try { var text = t.Result.GetResponseText(); if (t.Result.StatusCode != System.Net.HttpStatusCode.OK) { throw new InvalidOperationException(text); } accountProperties.Add("profile", text); } catch (Exception ex) { throw ex; } finally { this.CurrentUser = new Auth0User(accountProperties); } }).Wait(); } else { this.CurrentUser = new Auth0User(accountProperties); } } } }
--- /dev/null 2016-03-07 15:57:52.000000000 -0500 +++ src/System.Globalization.Extensions/src/SR.cs 2016-03-07 15:58:17.783206000 -0500 @@ -0,0 +1,198 @@ +using System; +using System.Resources; + +namespace FxResources.System.Globalization.Extensions +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.Globalization.Extensions.SR"; + + internal static String Arg_OutOfMemoryException + { + get + { + return SR.GetResourceString("Arg_OutOfMemoryException", null); + } + } + + internal static String Argument_IdnBadLabelSize + { + get + { + return SR.GetResourceString("Argument_IdnBadLabelSize", null); + } + } + + internal static String Argument_IdnBadPunycode + { + get + { + return SR.GetResourceString("Argument_IdnBadPunycode", null); + } + } + + internal static String Argument_IdnIllegalName + { + get + { + return SR.GetResourceString("Argument_IdnIllegalName", null); + } + } + + internal static String Argument_InvalidCharSequence + { + get + { + return SR.GetResourceString("Argument_InvalidCharSequence", null); + } + } + + internal static String Argument_InvalidCharSequenceNoIndex + { + get + { + return SR.GetResourceString("Argument_InvalidCharSequenceNoIndex", null); + } + } + + internal static String Argument_InvalidFlag + { + get + { + return SR.GetResourceString("Argument_InvalidFlag", null); + } + } + + internal static String Argument_InvalidNormalizationForm + { + get + { + return SR.GetResourceString("Argument_InvalidNormalizationForm", null); + } + } + + internal static String ArgumentOutOfRange_Index + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_Index", null); + } + } + + internal static String ArgumentOutOfRange_IndexCountBuffer + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_IndexCountBuffer", null); + } + } + + internal static String ArgumentOutOfRange_NeedNonNegNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Globalization.Extensions.SR); + } + } + + internal static String UnknownError_Num + { + get + { + return SR.GetResourceString("UnknownError_Num", null); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2, p3); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace FlatBuffers { /// <summary> /// Class that represents a single FlatBuffers schema (fbs) file /// </summary> public class FlatBuffersSchema { private FlatBuffersSchemaTypeDependencyNode _rootTypeNode; private readonly TypeModelRegistry _typeModelRegistry; private readonly List<FlatBuffersSchemaTypeDependencyNode> _nodes = new List<FlatBuffersSchemaTypeDependencyNode>(); private readonly HashSet<string> _metadataAttributes = new HashSet<string>(); /// <summary> /// Gets the RootType for this schema /// </summary> public FlatBuffersSchemaTypeDependencyNode RootType { get { return _rootTypeNode; } } /// <summary> /// Gets a Boolean to indiciate if this schema has a <see cref="RootType"/> set /// </summary> public bool HasRootType { get { return _rootTypeNode != null; } } /// <summary> /// Gets an enumerable of the user-specified attibutes used in this schema /// </summary> public IEnumerable<string> UserMetadataAttributes { get { return _metadataAttributes; } } internal FlatBuffersSchema(TypeModelRegistry typeModelRegistry) { _typeModelRegistry = typeModelRegistry; } internal FlatBuffersSchema() : this(TypeModelRegistry.Default) { } /// <summary> /// Gets an enumerable of the types contained in this schema /// </summary> public IEnumerable<FlatBuffersSchemaTypeDependencyNode> AllTypes { get { return _nodes; } } /// <summary> /// Adds a .NET type to the schema. Type will be reflected into a <see cref="TypeModel"/> /// </summary> /// <typeparam name="T">The type to add to the schema</typeparam> /// <returns>A dependency node for the type</returns> public FlatBuffersSchemaTypeDependencyNode AddType<T>() { return AddType(typeof(T)); } /// <summary> /// Adds a .NET type to the schema. Type will be reflected into a <see cref="TypeModel"/> /// </summary> /// <param name="type">The type to add to the schema</param> /// <returns>A dependency node for the type</returns> public FlatBuffersSchemaTypeDependencyNode AddType(Type type) { var typeModel = _typeModelRegistry.GetTypeModel(type); return AddType(typeModel); } /// <summary> /// Adds a <see cref="TypeModel"/> to the schema /// </summary> /// <param name="typeModel">The type to add to the schema</param> /// <returns>A dependency node for the type</returns> public FlatBuffersSchemaTypeDependencyNode AddType(TypeModel typeModel) { var node = GetDependencyNode(typeModel, null); return AddNode(node); } /// <summary> /// Sets the Root <see cref="TypeModel"/> of this schema /// </summary> /// <typeparam name="T">The root type</typeparam> /// <returns>A dependency node for the root type</returns> public FlatBuffersSchemaTypeDependencyNode SetRootType<T>() { return SetRootType(typeof (T)); } /// <summary> /// Sets the Root <see cref="TypeModel"/> of this schema /// </summary> /// <param name="type">The root type</param> /// <returns>A dependency node for the root type</returns> public FlatBuffersSchemaTypeDependencyNode SetRootType(Type type) { var typeModel = _typeModelRegistry.GetTypeModel(type); return SetRootType(typeModel); } /// <summary> /// Sets the Root <see cref="TypeModel"/> of this schema /// </summary> /// <param name="typeModel">The root type</param> /// <returns>A dependency node for the root type</returns> public FlatBuffersSchemaTypeDependencyNode SetRootType(TypeModel typeModel) { if (HasRootType) { throw new FlatBuffersSchemaException("Schema already has a root type"); } if (!typeModel.IsObject) { throw new FlatBuffersSchemaException("Type must be a Table or Struct type to be used as a root type"); } var node = AddType(typeModel); _rootTypeNode = node; return node; } private FlatBuffersSchemaTypeDependencyNode AddNode(FlatBuffersSchemaTypeDependencyNode node) { var typeModel = node.TypeModel; if (!typeModel.IsObject && !typeModel.IsEnum && !typeModel.IsUnion) { return null; } // TODO: Perhaps a dictionary? if (_nodes.Any(i => i.TypeModel.Name == typeModel.Name)) { throw new ArgumentException("TypeModel already exists"); } var dependentTypes = GetDependentTypes(node); foreach (var depType in dependentTypes) { if (_nodes.All(i => i.TypeModel.Name != depType.TypeModel.Name)) { if (depType.TypeModel != null) AddType(depType.TypeModel); } } node.AddDependencies(dependentTypes); _nodes.Add(node); return node; } private void CollectMetadata(TypeDefinition def) { foreach (var meta in def.Metadata.Items.Where(i=>i.IsUserMetaData)) { _metadataAttributes.Add(meta.Key); } } private FlatBuffersSchemaTypeDependencyNode GetDependencyNode(TypeModel typeModel, FlatBuffersSchemaTypeDependencyNode parent) { var dep = _nodes.FirstOrDefault(i => i.TypeModel.Name == typeModel.Name); return dep ?? new FlatBuffersSchemaTypeDependencyNode(typeModel, parent); } private List<FlatBuffersSchemaTypeDependencyNode> GetDependentTypes(FlatBuffersSchemaTypeDependencyNode node) { var deps = new List<FlatBuffersSchemaTypeDependencyNode>(); var typeModel = node.TypeModel; if (!typeModel.IsObject) { return deps; } var structDef = typeModel.StructDef; foreach (var field in structDef.Fields) { if (field.TypeModel.IsVector && field.TypeModel.ElementType == BaseType.Struct) { var elementType = field.TypeModel.GetElementTypeModel(); if (elementType != null) { deps.Add(GetDependencyNode(elementType, node)); } continue; } if (!field.TypeModel.IsObject && !field.TypeModel.IsEnum && !field.TypeModel.IsUnion && !field.TypeModel.IsUnion) continue; if (field.TypeModel.IsUnion) { var unionDeps = field.TypeModel.UnionDef.Fields.Where(i=>i.MemberType != null).Select(i => GetDependencyNode(i.MemberType, node)); foreach (var u in unionDeps) { if (deps.All(i => i.TypeModel != null && i.TypeModel.Name != u.TypeModel.Name)) { deps.Add(GetDependencyNode(u.TypeModel, node)); } } } if (field.TypeModel.IsVector && field.TypeModel.ElementType == BaseType.Struct) { var elementType = field.TypeModel.GetElementTypeModel(); if (elementType != null) { deps.Add(GetDependencyNode(elementType, node)); } continue; } if (field.HasNestedFlatBufferType) { if (deps.All(i => i.TypeModel.Name != field.NestedFlatBufferType.Name)) { deps.Add(GetDependencyNode(field.NestedFlatBufferType, node)); } } if (deps.All(i => i.TypeModel.Name != field.TypeModel.Name)) { deps.Add(GetDependencyNode(field.TypeModel, node)); } } return deps; } /// <summary> /// Writes this schema to the specified <see cref="TextWriter"/> using the default options /// </summary> /// <param name="writer">TextWriter to emit the schema to</param> public void WriteTo(TextWriter writer) { WriteTo(writer, FlatBuffersSchemaTypeWriterOptions.Default); } /// <summary> /// Writes this schema to the specified <see cref="TextWriter"/> /// </summary> /// <param name="writer">TextWriter to emit the schema to</param> /// <param name="options">Options to use when writing the schema</param> public void WriteTo(TextWriter writer, FlatBuffersSchemaTypeWriterOptions options) { var schemaWriter = new FlatBuffersSchemaTypeWriter(writer, options); var resolved = TraverseTypeGraph(); WriteUserMetadata(schemaWriter); foreach (var node in resolved) { schemaWriter.Write(node.TypeModel); } WriteFooter(schemaWriter); } private void WriteFooter(FlatBuffersSchemaTypeWriter schemaWriter) { if (HasRootType) { schemaWriter.WriteRootType(RootType.TypeModel.Name); if (RootType.TypeModel.IsTable) { var structDef = RootType.TypeModel.StructDef; if (structDef.HasIdentifier) { schemaWriter.WriteFileIdentifier(structDef.Identifier); } } } } /// <summary> /// Traverses the type graph, resolving dependencies. /// </summary> /// <returns>Resolved, ordered list of types</returns> private IEnumerable<FlatBuffersSchemaTypeDependencyNode> TraverseTypeGraph() { var results = new List<FlatBuffersSchemaTypeDependencyNode>(); var visited = new List<TypeModel>(); // These types are the 'leaf' types, eg: have no parents var leafNodes = _nodes.Where(i => i.Parent == null).ToList(); // write those out with no deps first VisitRankedTypes(results, leafNodes.Where(i => !i.DependentTypes.Any()), visited); // remove already visited nodes leafNodes.RemoveAll(i => visited.Any(n => n.Name == i.TypeModel.Name)); // resolve deps for those nodes with deps var seen = new List<FlatBuffersSchemaTypeDependencyNode>(); var resolved = new List<FlatBuffersSchemaTypeDependencyNode>(); foreach (var node in leafNodes) { ResolveDependency(node, resolved, seen); } // Write out the rest of the types in order VisitRankedTypes(results, resolved, visited); return results; } private void WriteUserMetadata(FlatBuffersSchemaTypeWriter schemaTypeWriter) { foreach (var meta in _metadataAttributes.OrderBy(i => i)) { schemaTypeWriter.WriteAttribute(meta); } if (_metadataAttributes.Any()) { schemaTypeWriter.WriteLine(); } } private void VisitRankedTypes(ICollection<FlatBuffersSchemaTypeDependencyNode> results, IEnumerable<FlatBuffersSchemaTypeDependencyNode> types, ICollection<TypeModel> visited) { Func<TypeModel, int> typeOrderFunc = (type) => { // Ordering func will order classes of type: // enum // union // struct // table if (type.IsEnum) { return 0; } if (type.IsUnion) { return 1; } return type.IsStruct ? 2 : 3; }; // Ranking is as follows: // 'type category', 'name' var ranked = types.GroupBy(i => typeOrderFunc(i.TypeModel)) .SelectMany(g => g.OrderBy(y => y.TypeModel.Name) .Select((x, i) => new { g.Key, Item = x, Rank = i + 1 })); foreach (var node in ranked.OrderBy(i => i.Key).ThenBy(i => i.Rank)) { var typeModel = node.Item.TypeModel; if (visited.Any(i => i.Name == typeModel.Name)) continue; // apply user types CollectMetadata(typeModel); results.Add(node.Item); visited.Add(typeModel); } } private void CollectMetadata(TypeModel typeModel) { if (typeModel.IsObject) { CollectMetadata(typeModel.StructDef); foreach (var field in typeModel.StructDef.Fields) { CollectMetadata(field); } } else if (typeModel.IsEnum) { CollectMetadata(typeModel.EnumDef); } } private void ResolveDependency(FlatBuffersSchemaTypeDependencyNode node, ICollection<FlatBuffersSchemaTypeDependencyNode> resolved, ICollection<FlatBuffersSchemaTypeDependencyNode> seen) { seen.Add(node); foreach (var dep in node.DependentTypes) { if (resolved.All(i => i.TypeModel.Name != dep.TypeModel.Name)) { if (seen.Any(i => i.TypeModel.Name == dep.TypeModel.Name)) { throw new Exception(string.Format("Circular dependency detected between {0} -> {1}", node.TypeModel.Name, dep.TypeModel.Name)); } ResolveDependency(dep, resolved, seen); } } resolved.Add(node); } } }
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.GetUserAvatarUrls(ApplicationContext.ApplicationCache.StaticCache); if (urls == null) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not access Gravatar endpoint")); return urls; } [AppendUserModifiedHeader("id")] [FileUploadCleanupFilter(false)] [AdminUsersAuthorize] 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.GetUserAvatarUrls(staticCache)); } [AppendUserModifiedHeader("id")] [AdminUsersAuthorize] 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.GetUserAvatarUrls(ApplicationContext.ApplicationCache.StaticCache)); } /// <summary> /// Gets a user by Id /// </summary> /// <param name="id"></param> /// <returns></returns> [OutgoingEditorModelEvent] [AdminUsersAuthorize] 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 hideDisabledUsers = UmbracoConfig.For.UmbracoSettings().Security.HideDisabledUsersInBackoffice; 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)); } if (hideDisabledUsers) { if (userStates == null || userStates.Any() == false) { userStates = new[] { UserState.Active, UserState.Invited, UserState.LockedOut, UserState.Inactive }; } } 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, Security.CurrentUser.Email, user, userSave.Message); display.AddSuccessNotification(Services.TextService.Localize("speechBubbles/resendInviteHeader"), Services.TextService.Localize("speechBubbles/resendInviteSuccess", new[] { user.Name })); 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, string fromEmail, 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(), fromEmail }); 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> [OutgoingEditorModelEvent] 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); //this will change the password and raise appropriate events var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(Security.CurrentUser, found, userSave.ChangePassword, UserManager); if (passwordChangeResult.Success) { //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> [AdminUsersAuthorize("userIds")] 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> [AdminUsersAuthorize("userIds")] 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> [AdminUsersAuthorize("userIds")] 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() })); } [AdminUsersAuthorize("userIds")] 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")); } /// <summary> /// Deletes the non-logged in user provided id /// </summary> /// <param name="id">User Id</param> /// <remarks> /// Limited to users that haven't logged in to avoid issues with related records constrained /// with a foreign key on the user Id /// </remarks> [AdminUsersAuthorize] public HttpResponseMessage PostDeleteNonLoggedInUser(int id) { var user = Services.UserService.GetUserById(id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } // Check user hasn't logged in. If they have they may have made content changes which will mean // the Id is associated with audit trails, versions etc. and can't be removed. if (user.LastLoginDate != default(DateTime)) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var userName = user.Name; Services.UserService.Delete(user, true); return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/deleteUserSuccess", new[] { userName })); } 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; } } } }
// <copyright file="DescriptiveStatisticsTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // 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> using System.Linq; using MathNet.Numerics.Distributions; using MathNet.Numerics.Random; namespace MathNet.Numerics.UnitTests.StatisticsTests { using System.Collections.Generic; using NUnit.Framework; using Statistics; /// <summary> /// Running statistics tests. /// </summary> /// <remarks>NOTE: this class is not included into Silverlight version, because it uses data from local files. /// In Silverlight access to local files is forbidden, except several cases.</remarks> [TestFixture, Category("Statistics")] public class RunningStatisticsTests { /// <summary> /// Statistics data. /// </summary> readonly IDictionary<string, StatTestData> _data = new Dictionary<string, StatTestData>(); /// <summary> /// Initializes a new instance of the DescriptiveStatisticsTests class. /// </summary> public RunningStatisticsTests() { _data.Add("lottery", new StatTestData("NIST.Lottery.dat")); _data.Add("lew", new StatTestData("NIST.Lew.dat")); _data.Add("mavro", new StatTestData("NIST.Mavro.dat")); _data.Add("michelso", new StatTestData("NIST.Michelso.dat")); _data.Add("numacc1", new StatTestData("NIST.NumAcc1.dat")); _data.Add("numacc2", new StatTestData("NIST.NumAcc2.dat")); _data.Add("numacc3", new StatTestData("NIST.NumAcc3.dat")); _data.Add("numacc4", new StatTestData("NIST.NumAcc4.dat")); _data.Add("meixner", new StatTestData("NIST.Meixner.dat")); } /// <summary> /// <c>IEnumerable</c> Double. /// </summary> /// <param name="dataSet">Dataset name.</param> /// <param name="digits">Digits count.</param> /// <param name="skewness">Skewness value.</param> /// <param name="kurtosis">Kurtosis value.</param> /// <param name="median">Median value.</param> /// <param name="min">Min value.</param> /// <param name="max">Max value.</param> /// <param name="count">Count value.</param> [TestCase("lottery", 14, -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)] [TestCase("lew", 14, -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)] [TestCase("mavro", 11, 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)] [TestCase("michelso", 11, -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)] [TestCase("numacc1", 15, 0, double.NaN, 10000002, 10000001, 10000003, 3)] [TestCase("numacc2", 13, 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)] [TestCase("numacc3", 9, 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)] [TestCase("numacc4", 7, 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)] [TestCase("meixner", 8, -0.016649617280859657, 0.8171318629552635, -0.002042931016531602, -4.825626912281697, 5.3018298664184913, 10000)] public void ConsistentWithNist(string dataSet, int digits, double skewness, double kurtosis, double median, double min, double max, int count) { var data = _data[dataSet]; var stats = new RunningStatistics(data.Data); AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 10); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, digits); AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 8); AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 8); Assert.AreEqual(stats.Minimum, min); Assert.AreEqual(stats.Maximum, max); Assert.AreEqual(stats.Count, count); } [TestCase("lottery", 1e-8, -0.09268823, -0.09333165)] [TestCase("lew", 1e-8, -0.0502263, -0.05060664)] [TestCase("mavro", 1e-6, 0.6254181, 0.6449295)] [TestCase("michelso", 1e-8, -0.01825961, -0.01853886)] [TestCase("numacc1", 1e-8, 0, 0)] //[TestCase("numacc2", 1e-20, 3.254232e-15, 3.259118e-15)] TODO: accuracy //[TestCase("numacc3", 1e-14, 1.747103e-09, 1.749726e-09)] TODO: accuracy //[TestCase("numacc4", 1e-13, 2.795364e-08, 2.799561e-08)] TODO: accuracy [TestCase("meixner", 1e-8, -0.01664712, -0.01664962)] public void SkewnessConsistentWithR_e1071(string dataSet, double delta, double skewnessType1, double skewnessType2) { var data = _data[dataSet]; var stats = new RunningStatistics(data.Data); Assert.That(stats.Skewness, Is.EqualTo(skewnessType2).Within(delta), "Skewness"); Assert.That(stats.PopulationSkewness, Is.EqualTo(skewnessType1).Within(delta), "PopulationSkewness"); } [TestCase("lottery", -1.192781, -1.192561)] [TestCase("lew", -1.48876, -1.49605)] [TestCase("mavro", -0.858384, -0.8205238)] [TestCase("michelso", 0.2635305, 0.3396846)] [TestCase("numacc1", -1.5, double.NaN)] [TestCase("numacc2", -1.999, -2.003003)] [TestCase("numacc3", -1.999, -2.003003)] [TestCase("numacc4", -1.999, -2.003003)] [TestCase("meixner", 0.8161234, 0.8171319)] public void KurtosisConsistentWithR_e1071(string dataSet, double kurtosisType1, double kurtosisType2) { var data = _data[dataSet]; var stats = new RunningStatistics(data.Data); Assert.That(stats.Kurtosis, Is.EqualTo(kurtosisType2).Within(1e-6), "Kurtosis"); Assert.That(stats.PopulationKurtosis, Is.EqualTo(kurtosisType1).Within(1e-6), "PopulationKurtosis"); } [Test] public void ShortSequences() { var stats0 = new RunningStatistics(new double[0]); Assert.That(stats0.Skewness, Is.NaN); Assert.That(stats0.Kurtosis, Is.NaN); var stats1 = new RunningStatistics(new[] { 1.0 }); Assert.That(stats1.Skewness, Is.NaN); Assert.That(stats1.Kurtosis, Is.NaN); var stats2 = new RunningStatistics(new[] { 1.0, 2.0 }); Assert.That(stats2.Skewness, Is.NaN); Assert.That(stats2.Kurtosis, Is.NaN); var stats3 = new RunningStatistics(new[] { 1.0, 2.0, -3.0 }); Assert.That(stats3.Skewness, Is.Not.NaN); Assert.That(stats3.Kurtosis, Is.NaN); var stats4 = new RunningStatistics(new[] { 1.0, 2.0, -3.0, -4.0 }); Assert.That(stats4.Skewness, Is.Not.NaN); Assert.That(stats4.Kurtosis, Is.Not.NaN); } [Test] public void ZeroVarianceSequence() { var stats = new RunningStatistics(new[] { 2.0, 2.0, 2.0, 2.0 }); Assert.That(stats.Skewness, Is.NaN); Assert.That(stats.Kurtosis, Is.NaN); } [Test] public void Combine() { var rnd = new SystemRandomSource(10); var a = Generate.Random(200, new Erlang(2, 0.2, rnd)); var b = Generate.Random(100, new Beta(1.2, 1.4, rnd)); var c = Generate.Random(150, new Rayleigh(0.8, rnd)); var d = a.Concat(b).Concat(c).ToArray(); var x = new RunningStatistics(d); var y = new RunningStatistics(a); y.PushRange(b); y.PushRange(c); var za = new RunningStatistics(a); var zb = new RunningStatistics(b); var zc = new RunningStatistics(c); var z = za + zb + zc; Assert.That(x.Mean, Is.EqualTo(d.Mean()).Within(1e-12), "Mean Reference"); Assert.That(y.Mean, Is.EqualTo(x.Mean).Within(1e-12), "Mean y"); Assert.That(z.Mean, Is.EqualTo(x.Mean).Within(1e-12), "Mean z"); Assert.That(x.Variance, Is.EqualTo(d.Variance()).Within(1e-12), "Variance Reference"); Assert.That(y.Variance, Is.EqualTo(x.Variance).Within(1e-12), "Variance y"); Assert.That(z.Variance, Is.EqualTo(x.Variance).Within(1e-12), "Variance z"); Assert.That(x.PopulationVariance, Is.EqualTo(d.PopulationVariance()).Within(1e-12), "PopulationVariance Reference"); Assert.That(y.PopulationVariance, Is.EqualTo(x.PopulationVariance).Within(1e-12), "PopulationVariance y"); Assert.That(z.PopulationVariance, Is.EqualTo(x.PopulationVariance).Within(1e-12), "PopulationVariance z"); Assert.That(x.StandardDeviation, Is.EqualTo(d.StandardDeviation()).Within(1e-12), "StandardDeviation Reference"); Assert.That(y.StandardDeviation, Is.EqualTo(x.StandardDeviation).Within(1e-12), "StandardDeviation y"); Assert.That(z.StandardDeviation, Is.EqualTo(x.StandardDeviation).Within(1e-12), "StandardDeviation z"); Assert.That(x.PopulationStandardDeviation, Is.EqualTo(d.PopulationStandardDeviation()).Within(1e-12), "PopulationStandardDeviation Reference"); Assert.That(y.PopulationStandardDeviation, Is.EqualTo(x.PopulationStandardDeviation).Within(1e-12), "PopulationStandardDeviation y"); Assert.That(z.PopulationStandardDeviation, Is.EqualTo(x.PopulationStandardDeviation).Within(1e-12), "PopulationStandardDeviation z"); Assert.That(x.Skewness, Is.EqualTo(d.Skewness()).Within(1e-12), "Skewness Reference (not independent!)"); Assert.That(y.Skewness, Is.EqualTo(x.Skewness).Within(1e-12), "Skewness y"); Assert.That(z.Skewness, Is.EqualTo(x.Skewness).Within(1e-12), "Skewness z"); Assert.That(x.PopulationSkewness, Is.EqualTo(d.PopulationSkewness()).Within(1e-12), "PopulationSkewness Reference (not independent!)"); Assert.That(y.PopulationSkewness, Is.EqualTo(x.PopulationSkewness).Within(1e-12), "PopulationSkewness y"); Assert.That(z.PopulationSkewness, Is.EqualTo(x.PopulationSkewness).Within(1e-12), "PopulationSkewness z"); Assert.That(x.Kurtosis, Is.EqualTo(d.Kurtosis()).Within(1e-12), "Kurtosis Reference (not independent!)"); Assert.That(y.Kurtosis, Is.EqualTo(x.Kurtosis).Within(1e-12), "Kurtosis y"); Assert.That(z.Kurtosis, Is.EqualTo(x.Kurtosis).Within(1e-12), "Kurtosis z"); Assert.That(x.PopulationKurtosis, Is.EqualTo(d.PopulationKurtosis()).Within(1e-12), "PopulationKurtosis Reference (not independent!)"); Assert.That(y.PopulationKurtosis, Is.EqualTo(x.PopulationKurtosis).Within(1e-12), "PopulationKurtosis y"); Assert.That(z.PopulationKurtosis, Is.EqualTo(x.PopulationKurtosis).Within(1e-12), "PopulationKurtosis z"); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Adxstudio.Xrm.Core; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Text; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Metadata; namespace Adxstudio.Xrm.Web.UI.WebForms { public abstract class Expression : IEnumerable<Expression> { public IEnumerable<Expression> Operands { get; private set; } public virtual string Operator { get { return null; } } public delegate string ExpressionAction(Expression expression, IDictionary<Type, ExpressionAction> map); protected Expression() { } protected Expression(string name, object value) : this(new LeftLiteralExpression(name.Trim()), new RightLiteralExpression(value)) { } protected Expression(params Expression[] operands) { Operands = new List<Expression>(operands); } public static LiteralExpression Literal(object value) { return new LiteralExpression(value); } public static OrExpression operator |(Expression left, Expression right) { return new OrExpression(left, right); } public static OrExpression Or(params Expression[] operands) { return new OrExpression(operands); } public static AndExpression operator &(Expression left, Expression right) { return new AndExpression(left, right); } public static AndExpression And(params Expression[] operands) { return new AndExpression(operands); } public static NotExpression Not(Expression operand) { return new NotExpression(operand); } public static NoOpExpression NoOp(Expression operand) { return new NoOpExpression(operand); } public static LikeExpression Like(string name, object value) { return new LikeExpression(name, value); } public static NotLikeExpression NotLike(string name, object value) { return new NotLikeExpression(name, value); } public static Expression operator ==(Expression left, Expression right) { return new EqualsExpression(left, right); } public static EqualsExpression Equals(string name, object value) { return new EqualsExpression(name, value); } public static Expression operator !=(Expression left, Expression right) { return new NotEqualsExpression(left, right); } public static NotEqualsExpression NotEquals(string name, object value) { return new NotEqualsExpression(name, value); } public static Expression operator >(Expression left, Expression right) { return new GreaterThanExpression(left, right); } public static GreaterThanExpression GreaterThan(string name, object value) { return new GreaterThanExpression(name, value); } public static Expression operator >=(Expression left, Expression right) { return new GreaterThanOrEqualsExpression(left, right); } public static GreaterThanOrEqualsExpression GreaterThanOrEquals(string name, object value) { return new GreaterThanOrEqualsExpression(name, value); } public static Expression operator <(Expression left, Expression right) { return new LessThanExpression(left, right); } public static LessThanExpression LessThan(string name, object value) { return new LessThanExpression(name, value); } public static Expression operator <=(Expression left, Expression right) { return new LessThanOrEqualsExpression(left, right); } public static LessThanOrEqualsExpression LessThanOrEquals(string name, object value) { return new LessThanOrEqualsExpression(name, value); } public static bool IsNull(Expression expression) { return (expression as object) == null; } public override string ToString() { return ToString(null); } public virtual string ToString(IDictionary<Type, ExpressionAction> map) { if (map != null) { var type = GetType(); while (type != null) { if (map.ContainsKey(type)) { return map[type](this, map); } type = type.BaseType; } } return null; } public abstract bool Evaluate(IExpressionEvaluator evaluator); public void ForEachChild(Action<Expression> action) { foreach (var operand in this) { action(operand); } } public void ForEachDescendant(Action<Expression> action) { foreach (var operand in this) { action(operand); operand.ForEachDescendant(action); } } public void ForSubTree(Action<Expression> action) { action(this); foreach (var operand in this) { operand.ForSubTree(action); } } public IEnumerable<Expression> Descendants { get { foreach (var operand in this) { yield return operand; foreach (var expression in operand.Descendants) { yield return expression; } } } } public IEnumerable<Expression> SubTree { get { yield return this; foreach (var operand in this) { foreach (var expression in operand.SubTree) { yield return expression; } } } } public IEnumerable<Expression> GetSubTreeEnumerator(Predicate<Expression> match) { if (match(this)) { yield return this; } foreach (var operand in this) { foreach (var expression in operand.GetSubTreeEnumerator(match)) { yield return expression; } } } #region Parsing Methods public static Expression ParseCondition(string condition) { return ParseCondition(condition, ParseValue); } public static Expression ParseCondition(string condition, Func<string, string, object> parseValue) { using (var reader = new StringReader(condition)) { return RenderExpression(reader, parseValue); } } public static bool TryParseCondition(string condition, out Expression expression) { return TryParseCondition(condition, out expression, ParseValue); } public static bool TryParseCondition(string condition, out Expression expression, Func<string, string, object> parseValue) { try { using (var reader = new StringReader(condition)) { expression = RenderExpression(reader, parseValue); } return true; } catch { expression = null; } return false; } private static Expression GetExpression(string op, string name, List<Expression> operands, Func<string, string, object> parseValue) { // check if this is a logical expression if (op == "&") { if (operands == null || operands.Count == 0) { throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name)); } return And(operands.ToArray()); } if (op == "|") { if (operands == null || operands.Count == 0) { throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name)); } return Or(operands.ToArray()); } if (op == "!") { if (operands == null || operands.Count != 1) { throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name)); } return Not(operands[0]); } if (op == null) { if (operands == null || operands.Count != 1) { throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name)); } return NoOp(operands[0]); } // check if this is a conditional string var ops = name.Split(new[] { op }, 2, StringSplitOptions.None); if (ops.Length != 2) { throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name)); } var attributeName = ops[0]; var text = ops[1]; var containsWildcard = text != null && (Regex.IsMatch(text, @"[^\\]\*") || text.StartsWith("*")); var value = parseValue(attributeName, text); // if an '*' is detected in an '=' expression, promote to 'like' expression if ((op == "=" || op == "==") && containsWildcard) { op = "~="; } if (op == "=" || op == "==") { return Equals(attributeName, value); } if (op == "!=") { if (containsWildcard) { // if an '*' is detected in an '=' expression, promote to 'like' expression return NotLike(attributeName, value); } return NotEquals(attributeName, value); } if (op == "~=") { return Like(attributeName, value); } if (op == "<") { return LessThan(attributeName, value); } if (op == "<=") { return LessThanOrEquals(attributeName, value); } if (op == ">") { return GreaterThan(attributeName, value); } if (op == ">=") { return GreaterThanOrEquals(attributeName, value); } throw new InvalidOperationException(string.Format("Unknown operator symbol {0}.", op)); } private static Expression RenderExpression(StringReader reader, Func<string, string, object> parseValue) { var operands = new List<Expression>(); var name = new StringBuilder(); string op = null; var union = false; var unionAnd = false; var unionOperandCount = 0; while (true) { // pop the next character var value = reader.Read(); // reached end of string? if (value == -1) break; var current = Convert.ToChar(value); if (current == '\\') { // may be trying to escape a special character var next = Convert.ToChar(reader.Peek()); if (@"*()\@".Contains(next.ToString())) { // read the next character as a literal value reader.Read(); name.Append(current); name.Append(next); } else { // not a special character, continue normally name.Append(current); } } else if (current == '(') { // start a recursive call to handle sub-expression Expression operand = RenderExpression(reader, parseValue); operands.Add(operand); union = false; unionOperandCount++; } else if (current == ')') { // reached end of sub-expression if (union) { if (operands.Count <= unionOperandCount) { var operand = GetExpression(op, name.ToString(), operands, parseValue); operands.Add(operand); } return unionAnd ? GetExpression("&", "&", operands, parseValue) : GetExpression("|", "|", operands, parseValue); } return GetExpression(op, name.ToString(), operands, parseValue); } else if ("&|!=<>~".Contains(current.ToString())) { if ((op != null | operands.Count > 0) && (current.ToString() == "&" | current.ToString() == "|")) { if (op != null) { var operand = GetExpression(op, name.ToString(), operands, parseValue); operands.Add(operand); unionOperandCount++; name.Clear(); } op = current.ToString(); if (union && unionAnd && current.ToString() == "|") { var unionOperand = GetExpression("&", "&", operands, parseValue); operands.Clear(); operands.Add(unionOperand); unionOperandCount = 1; } if (union && !unionAnd && current.ToString() == "&") { var unionOperand = GetExpression("|", "|", operands, parseValue); operands.Clear(); operands.Add(unionOperand); unionOperandCount = 1; } union = true; unionAnd = current.ToString() == "&"; } else { // encountered an operator op = current.ToString(); name.Append(current); // check if this is a 2 character operator if (reader.Peek() > -1) { var next = Convert.ToChar(reader.Peek()); if ("=".Contains(next.ToString())) { // read the second character reader.Read(); op += next; name.Append(next); } } } } else { // this is a character in a literal value name.Append(current); } } if (union) { if (operands.Count <= unionOperandCount) { var operand = GetExpression(op, name.ToString(), operands, parseValue); operands.Add(operand); } return unionAnd ? GetExpression("&", "&", operands, parseValue) : GetExpression("|", "|", operands, parseValue); } // reached end of expression return GetExpression(op, name.ToString(), operands, parseValue); } private static object ParseValue(string attributeName, string text) { // try convert from string to value type object value; DateTime dateTimeValue; double doubleValue; bool boolValue; Guid guidValue; if (double.TryParse( text, NumberStyles.Any, CultureInfo.InvariantCulture, out doubleValue)) { value = doubleValue; } else if (DateTime.TryParse( text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dateTimeValue)) { value = dateTimeValue; } else if (bool.TryParse( text, out boolValue)) { value = boolValue; } else if (Guid.TryParse( text, out guidValue)) { value = guidValue; } else if (string.Compare(text, "null", StringComparison.InvariantCultureIgnoreCase) == 0) { value = null; } else { value = text; } return value; } #endregion /// <summary> /// Replaces parameterized literals (identifiers starting with '@') of the expression tree with the actual values provided by the dictionary. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public Expression SubstituteParameters(Dictionary<string, object> parameters) { return Clone( (expression, parent) => { if (expression is LiteralExpression && (expression as LiteralExpression).Value is string) { // replace '@' parameter identifiers into the actual parameter value var value = (expression as LiteralExpression).Value as string; if (value != null && value.StartsWith("@")) { if (parameters != null && parameters.ContainsKey(value)) { (expression as LiteralExpression).Value = parameters[value]; } else { value = value.TrimStart('@'); // the '@' character is optional in the parameter dictionary if (parameters != null && parameters.ContainsKey(value)) { (expression as LiteralExpression).Value = parameters[value]; } else { throw new InvalidOperationException(string.Format("The filter parameter {0} is missing an actual value in the dictionary.", value)); } } } } return expression; }); } public Expression Clone() { return Clone((expression, parent) => expression); } public Expression Clone(Func<Expression, Expression, Expression> convert) { return Clone(convert, null); } public abstract Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent); public IEnumerator<Expression> GetEnumerator() { if (Operands != null) { foreach (var operand in Operands) { yield return operand; } } } IEnumerator IEnumerable.GetEnumerator() { yield return GetEnumerator(); } public bool Equals(Expression other) { if (ReferenceEquals(null, other)) { return false; } return ReferenceEquals(this, other) || Equals(other.Operands, Operands); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == typeof(Expression) && Equals((Expression)obj); } public override int GetHashCode() { return (Operands != null ? Operands.GetHashCode() : 0); } } public class LiteralExpression : Expression { public object Value { get; set; } public LiteralExpression(object value) { if (value is string && !string.IsNullOrWhiteSpace((string)value)) { value = ((string)value).Trim(new[] { ' ', '\'' }); if (((string)value).ToLowerInvariant() == "null") { value = null; } } Value = value; } public override string ToString(IDictionary<Type, ExpressionAction> map) { var value = base.ToString(map) ?? (Value == null ? "NULL" : Value.ToString()); return value; } public override Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent) { return convert(new LiteralExpression(Value), parent); } public override bool Evaluate(IExpressionEvaluator evaluator) { // this method should be guarded from being called by all BinaryExpressions throw new NotSupportedException(string.Format("Unable to evaluate an expression of type {0} with the value {1}.", this, Value)); } } public class LeftLiteralExpression : LiteralExpression { public LeftLiteralExpression(object value) : base(value) { } public override Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent) { return convert(new LeftLiteralExpression(Value), parent); } } public class RightLiteralExpression : LiteralExpression { public RightLiteralExpression(object value) : base(value) { } public override Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent) { return convert(new RightLiteralExpression(Value), parent); } } public abstract class BooleanExpression : Expression { protected BooleanExpression(params Expression[] operands) : base(operands) { } public override string ToString(IDictionary<Type, ExpressionAction> map) { var value = base.ToString(map); if (value == null) { var ops = Operands.Select(operand => operand.ToString(map)).ToList(); var opsArray = new string[ops.Count]; ops.CopyTo(opsArray); //value = "(\n" + string.Join(" " + Operator + " ", opsArray) + "\n)\n"; value = string.Format("({0})", string.Join(" " + Operator + " ", opsArray)); } return value; } public override Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent) { return convert(Clone(Operands.Select(operand => operand.Clone(convert, this)).ToArray()), parent); } public override bool Evaluate(IExpressionEvaluator evaluator) { return Evaluate(Operands.Select(operand => operand.Evaluate(evaluator))); } public abstract Expression Clone(Expression[] operands); protected abstract bool Evaluate(IEnumerable<bool> operands); } public class OrExpression : BooleanExpression { public OrExpression(params Expression[] operands) : base(operands) { } public override string Operator { get { return "or"; } } public override Expression Clone(Expression[] operands) { return new OrExpression(operands); } protected override bool Evaluate(IEnumerable<bool> operands) { // find any expression that is true return operands.Any(operand => operand); } } public class AndExpression : BooleanExpression { public AndExpression(params Expression[] operands) : base(operands) { } public override string Operator { get { return "and"; } } public override Expression Clone(Expression[] operands) { return new AndExpression(operands); } protected override bool Evaluate(IEnumerable<bool> operands) { // find any expression that is false return !operands.Any(operand => !operand); } } public abstract class UnaryExpression : Expression { protected UnaryExpression(Expression operand) : base(operand) { } public Expression GetOperand() { var enumerator = Operands.GetEnumerator(); enumerator.MoveNext(); return enumerator.Current; } public override string ToString(IDictionary<Type, ExpressionAction> map) { var value = base.ToString(map); if (value == null) { var operand = GetOperand(); // default to postfix notation value = string.Format(@"{0} ({1})", Operator, operand.ToString(map)); } return value; } public override Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent) { var operand = GetOperand(); return convert(Clone(operand.Clone(convert, this)), parent); } public override bool Evaluate(IExpressionEvaluator evaluator) { // pass the operand through return Evaluate(GetOperand().Evaluate(evaluator)); } public abstract Expression Clone(Expression operand); protected abstract bool Evaluate(bool operand); } public class NotExpression : UnaryExpression { public NotExpression(Expression operand) : base(operand) { } public override string Operator { get { return "not"; } } public override Expression Clone(Expression operand) { return new NotExpression(operand); } protected override bool Evaluate(bool operand) { // negate the operand return !operand; } } public class NoOpExpression : UnaryExpression { public NoOpExpression(Expression operand) : base(operand) { } public override string ToString(IDictionary<Type, ExpressionAction> map) { var value = base.ToString(map); if (value == null) { var operand = GetOperand(); value = string.Format(@"({0})", operand.ToString(map)); } return value; } public override Expression Clone(Expression operand) { return new NoOpExpression(operand); } protected override bool Evaluate(bool operand) { // pass the operand through return operand; } } public abstract class BinaryExpression : Expression { protected BinaryExpression(Expression left, Expression right) : base(left, right) { } protected BinaryExpression(string name, object value) : base(name, value) { } public Expression Left { get { var enumerator = Operands.GetEnumerator(); enumerator.MoveNext(); return enumerator.Current; } } public Expression Right { get { var enumerator = Operands.GetEnumerator(); enumerator.MoveNext(); enumerator.MoveNext(); return enumerator.Current; } } public override string ToString(IDictionary<Type, ExpressionAction> map) { var value = base.ToString(map); if (value == null) { var ops = new List<LiteralExpression>(2); ops.AddRange(Operands.Cast<LiteralExpression>()); // default to infix notation value = string.Format(@"({1} {0} {2})", Operator, ops[0].ToString(map), ops[1].ToString(map)); } return value; } public override Expression Clone(Func<Expression, Expression, Expression> convert, Expression parent) { var left = Left.Clone(convert, this); var right = Right.Clone(convert, this); return convert(Clone(left, right), parent); } public override bool Evaluate(IExpressionEvaluator evaluator) { return evaluator.Evaluate(this); } public abstract Expression Clone(Expression left, Expression right); } public class LikeExpression : BinaryExpression { public LikeExpression(Expression left, Expression right) : base(left, right) { } public LikeExpression(string name, object value) : base(name, value) { } public override string Operator { get { return "like"; } } public override Expression Clone(Expression left, Expression right) { return new LikeExpression(left, right); } } public class NotLikeExpression : BinaryExpression { public NotLikeExpression(Expression left, Expression right) : base(left, right) { } public NotLikeExpression(string name, object value) : base(name, value) { } public override string Operator { get { return "not like"; } } public override Expression Clone(Expression left, Expression right) { return new NotLikeExpression(left, right); } } public class EqualsExpression : BinaryExpression { public EqualsExpression(Expression left, Expression right) : base(left, right) { } public EqualsExpression(string name, object value) : base(name, value) { } public override string Operator { get { return "="; } } public override Expression Clone(Expression left, Expression right) { return new EqualsExpression(left, right); } } public class NotEqualsExpression : BinaryExpression { public NotEqualsExpression(Expression left, Expression right) : base(left, right) { } public NotEqualsExpression(string name, object value) : base(name, value) { } public override string Operator { get { return "<>"; } } public override Expression Clone(Expression left, Expression right) { return new NotEqualsExpression(left, right); } } public class GreaterThanExpression : BinaryExpression { public GreaterThanExpression(Expression left, Expression right) : base(left, right) { } public GreaterThanExpression(string name, object value) : base(name, value) { } public override string Operator { get { return ">"; } } public override Expression Clone(Expression left, Expression right) { return new GreaterThanExpression(left, right); } } public class GreaterThanOrEqualsExpression : BinaryExpression { public GreaterThanOrEqualsExpression(Expression left, Expression right) : base(left, right) { } public GreaterThanOrEqualsExpression(string name, object value) : base(name, value) { } public override string Operator { get { return ">="; } } public override Expression Clone(Expression left, Expression right) { return new GreaterThanOrEqualsExpression(left, right); } } public class LessThanExpression : BinaryExpression { public LessThanExpression(Expression left, Expression right) : base(left, right) { } public LessThanExpression(string name, object value) : base(name, value) { } public override string Operator { get { return "<"; } } public override Expression Clone(Expression left, Expression right) { return new LessThanExpression(left, right); } } public class LessThanOrEqualsExpression : BinaryExpression { public LessThanOrEqualsExpression(Expression left, Expression right) : base(left, right) { } public LessThanOrEqualsExpression(string name, object value) : base(name, value) { } public override string Operator { get { return "<="; } } public override Expression Clone(Expression left, Expression right) { return new LessThanOrEqualsExpression(left, right); } } public interface IExpressionEvaluator { bool Evaluate(Expression expression); } public class EntityExpressionEvaluator : IExpressionEvaluator { protected Entity EvaluateEntity { get; private set; } protected OrganizationServiceContext ServiceContext { get; private set; } protected Dictionary<string, AttributeTypeCode?> AttributeTypeCodeDictionary { get; private set; } public EntityExpressionEvaluator(OrganizationServiceContext context, Entity entity) { ServiceContext = context; EvaluateEntity = entity; AttributeTypeCodeDictionary = MetadataHelper.BuildAttributeTypeCodeDictionary(context, entity.LogicalName); } public bool Evaluate(Expression expression) { if (expression is BinaryExpression) { var left = (expression as BinaryExpression).Left; var right = (expression as BinaryExpression).Right; if (expression is LikeExpression) { return Evaluate(left, right, Match, (value, type) => value); } if (expression is NotLikeExpression) { return Evaluate(left, right, (l, r) => !Match(l, r)); } if (expression is EqualsExpression) { return Evaluate(left, right, (l, r) => Compare(l, r) == 0); } if (expression is NotEqualsExpression) { return Evaluate(left, right, (l, r) => Compare(l, r) != 0); } if (expression is GreaterThanExpression) { return Evaluate(left, right, (l, r) => Compare(l, r) > 0); } if (expression is GreaterThanOrEqualsExpression) { return Evaluate(left, right, (l, r) => Compare(l, r) >= 0); } if (expression is LessThanExpression) { return Evaluate(left, right, (l, r) => Compare(l, r) < 0); } if (expression is LessThanOrEqualsExpression) { return Evaluate(left, right, (l, r) => Compare(l, r) <= 0); } } else if (expression is BooleanExpression) { if (expression is AndExpression) { return expression.Operands.Select(Evaluate).Aggregate(true, (current, value) => current & value); } if (expression is OrExpression) { return expression.Operands.Select(Evaluate).Aggregate(false, (current, value) => current | value); } } throw new NotSupportedException(string.Format("Unable to evaluate an expression of type {0}.", expression)); } protected bool Evaluate(Expression left, Expression right, Func<object, object, bool> compare) { return Evaluate(left, right, compare, null); } protected bool Evaluate(Expression left, Expression right, Func<object, object, bool> compare, Func<object, Type, object> convert) { object testValue; var attributeName = ((LeftLiteralExpression)left).Value as string; var expressionValue = ((RightLiteralExpression)right).Value; if (EvaluateEntity == null) { throw new NullReferenceException("EvaluateEntity is null."); } if (string.IsNullOrWhiteSpace(attributeName)) { throw new InvalidOperationException(string.Format("Unable to recognize the attribute {0} specified in the expression.", attributeName)); } var attributeTypeCode = AttributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value; if (attributeTypeCode == null) { throw new InvalidOperationException(string.Format("Unable to recognize the attribute {0} specified in the expression.", attributeName)); } var attributeValue = EvaluateEntity.Attributes.ContainsKey(attributeName) ? EvaluateEntity.Attributes[attributeName] : null; switch (attributeTypeCode) { case AttributeTypeCode.BigInt: if (expressionValue != null && !(expressionValue is long | expressionValue is double)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToInt64(expressionValue); break; case AttributeTypeCode.Boolean: if (expressionValue != null && !(expressionValue is bool)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : (bool)expressionValue; break; case AttributeTypeCode.Customer: var entityReference = EvaluateEntity.Attributes.ContainsKey(attributeName) ? (EntityReference)EvaluateEntity.Attributes[attributeName] : null; attributeValue = entityReference != null ? (object)entityReference.Id : null; if (expressionValue != null && !(expressionValue is Guid)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : (Guid)expressionValue; break; case AttributeTypeCode.DateTime: if (expressionValue != null && !(expressionValue is DateTime)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : ((DateTime)expressionValue).ToUniversalTime(); break; case AttributeTypeCode.Decimal: if (expressionValue != null && !(expressionValue is int | expressionValue is double | expressionValue is decimal)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToDecimal(expressionValue); break; case AttributeTypeCode.Double: if (expressionValue != null && !(expressionValue is int | expressionValue is double)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToDouble(expressionValue); break; case AttributeTypeCode.Integer: if (expressionValue != null && !(expressionValue is int | expressionValue is double)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue); break; case AttributeTypeCode.Lookup: var lookupEntityReference = EvaluateEntity.Attributes.ContainsKey(attributeName) ? (EntityReference)EvaluateEntity.Attributes[attributeName] : null; attributeValue = lookupEntityReference != null ? (object)lookupEntityReference.Id : null; if (expressionValue != null && !(expressionValue is Guid)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : (Guid)expressionValue; break; case AttributeTypeCode.Memo: if (expressionValue != null && !(expressionValue is string)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue as string; break; case AttributeTypeCode.Money: var money = EvaluateEntity.Attributes.ContainsKey(attributeName) ? (Money)EvaluateEntity.Attributes[attributeName] : null; attributeValue = money != null ? (object)Convert.ToDecimal(money.Value) : null; if (expressionValue != null && !(expressionValue is int | expressionValue is double | expressionValue is decimal)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToDecimal(expressionValue); break; case AttributeTypeCode.Picklist: var optionSetValue = EvaluateEntity.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEntity.Attributes[attributeName] : null; attributeValue = optionSetValue != null ? (object)optionSetValue.Value : null; if (expressionValue != null && !(expressionValue is int | expressionValue is double)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue); break; case AttributeTypeCode.State: var stateOptionSetValue = EvaluateEntity.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEntity.Attributes[attributeName] : null; attributeValue = stateOptionSetValue != null ? (object)stateOptionSetValue.Value : null; if (expressionValue != null && !(expressionValue is int | expressionValue is double)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue); break; case AttributeTypeCode.Status: var statusOptionSetValue = EvaluateEntity.Attributes.ContainsKey(attributeName) ? (OptionSetValue)EvaluateEntity.Attributes[attributeName] : null; attributeValue = statusOptionSetValue != null ? (object)statusOptionSetValue.Value : null; if (expressionValue != null && !(expressionValue is int | expressionValue is double)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : Convert.ToInt32(expressionValue); break; case AttributeTypeCode.String: if (expressionValue != null && !(expressionValue is string)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue as string; break; case AttributeTypeCode.Uniqueidentifier: if (expressionValue != null && !(expressionValue is Guid)) { throw new InvalidOperationException(string.Format("Attribute {0} specified in the expression is expecting a {1}. The value provided isn't valid.", attributeName, attributeTypeCode)); } testValue = expressionValue == null ? (object)null : (Guid)expressionValue; break; default: throw new InvalidOperationException(string.Format("Unsupported type of attribute {0} specified in the expression.", attributeName)); } return compare(attributeValue, testValue); } private static bool Match(object left, object right) { if (left == null && right == null) return true; // a Regex (ie. a like condition) will only work on string values var l = left != null ? left.ToString() : string.Empty; var r = right != null ? right.ToString() : string.Empty; var mask = new Mask(r); return mask.IsMatch(l); } private static int Compare(object left, object right) { if (left == null && right == null) return 0; if (left is IComparable) return (left as IComparable).CompareTo(right); if (right is IComparable) return (right as IComparable).CompareTo(left) * -1; throw new InvalidOperationException(string.Format("The value {0} can't be compared to the value {1}.", left, right)); } } }
using System; using System.Diagnostics; using System.Text; using Bitmask = System.UInt64; #if !MAX_VARIABLE_NUMBER using yVars = System.Int16; #else using yVars = System.Int32; #endif namespace Core { public partial class Walker { static WRC IncrAggDepth(Walker walker, Expr expr) { if (expr.OP == TK.AGG_FUNCTION) expr.OP2 += (byte)walker.u.I; return WRC.Continue; } static void IncrAggFunctionDepth(Expr expr, int n) { if (n > 0) { Walker w = new Walker(); w.ExprCallback = IncrAggDepth; w.u.I = n; w.WalkExpr(expr); } } static void ResolveAlias(Parse parse, ExprList list, int colId, Expr expr, string type, int subqueries) { Debug.Assert(colId >= 0 && colId < list.Exprs); Expr orig = list.Ids[colId].Expr; // The iCol-th column of the result set Debug.Assert(orig != null); Debug.Assert((orig.Flags & EP.Resolved) != 0); Context ctx = parse.Ctx; // The database connection Expr dup = Expr.Dup(ctx, orig, 0); // Copy of pOrig if (orig.OP != TK.COLUMN && (type.Length == 0 || type[0] != 'G')) { IncrAggFunctionDepth(dup, subqueries); dup = Expr.PExpr_(parse, TK.AS, dup, null, null); if (dup == null) return; if (list.Ids[colId].Alias == 0) list.Ids[colId].Alias = (ushort)(++parse.Alias.length); dup.TableId = list.Ids[colId].Alias; } if (expr.OP == TK.COLLATE) dup = Expr.AddCollateString(parse, dup, expr.u.Token); // Before calling sqlite3ExprDelete(), set the EP_Static flag. This prevents ExprDelete() from deleting the Expr structure itself, // allowing it to be repopulated by the memcpy() on the following line. E.ExprSetProperty(expr, EP.Static); Expr.Delete(ctx, ref expr); expr.memcpy(dup); if (!E.ExprHasProperty(expr, EP.IntValue) && expr.u.Token != null) { Debug.Assert((dup.Flags & (EP.Reduced | EP.TokenOnly)) == 0); dup.u.Token = expr.u.Token; dup.Flags2 |= EP2.MallocedToken; } C._tagfree(ctx, ref dup); } static bool NameInUsingClause(IdList using_, string colName) { if (using_ != null) for (int k = 0; k < using_.Ids.length; k++) if (string.Compare(using_.Ids[k].Name, colName, StringComparison.OrdinalIgnoreCase) == 0) return true; return false; } public static bool MatchSpanName(string span, string colName, string table, string dbName) { int n; for (n = 0; C._ALWAYS(span[n] != null) && span[n] != '.'; n++) { } if (dbName != null && (string.Compare(span, 0, dbName, 0, n, StringComparison.OrdinalIgnoreCase) != 0) || dbName[n] != 0) return false; span += n + 1; for (n = 0; C._ALWAYS(span[n] != null) && span[n] != '.'; n++) { } if (table != null && (string.Compare(span, 0, table, 0, n, StringComparison.OrdinalIgnoreCase) != 0 || table[n] != 0)) return false; span += n + 1; if (colName != null && string.Compare(span, colName) != 0) return false; return true; } static WRC LookupName(Parse parse, string dbName, string tableName, string colName, NameContext nc, Expr expr) { int cnt = 0; // Number of matching column names int cntTab = 0; // Number of matching table names int subquerys = 0; // How many levels of subquery Context ctx = parse.Ctx; // The database connection SrcList.SrcListItem item; // Use for looping over pSrcList items SrcList.SrcListItem match = null; // The matching pSrcList item NameContext topNC = nc; // First namecontext in the list Schema schema = null; // Schema of the expression bool isTrigger = false; int i, j; Debug.Assert(nc != null); // the name context cannot be NULL. Debug.Assert(colName != null); // The Z in X.Y.Z cannot be NULL Debug.Assert(!E.ExprHasAnyProperty(expr, EP.TokenOnly | EP.Reduced)); // Initialize the node to no-match expr.TableId = -1; expr.Table = null; E.ExprSetIrreducible(expr); // Translate the schema name in zDb into a pointer to the corresponding schema. If not found, pSchema will remain NULL and nothing will match // resulting in an appropriate error message toward the end of this routine if (dbName != null) { for (i = 0; i < ctx.DBs.length; i++) { Debug.Assert(ctx.DBs[i].Name != null); if (string.Compare(ctx.DBs[i].Name, dbName) == 0) { schema = ctx.DBs[i].Schema; break; } } } // Start at the inner-most context and move outward until a match is found while (nc != null && cnt == 0) { ExprList list; SrcList srcList = nc.SrcList; if (srcList != null) { for (i = 0; i < srcList.Srcs; i++) { item = srcList.Ids[i]; Table table = item.Table; Debug.Assert(table != null && table.Name != null); Debug.Assert(table.Cols.length > 0); if (item.Select != null && (item.Select.SelFlags & SF.NestedFrom) != 0) { bool hit = false; list = item.Select.EList; for (j = 0; j < list.Exprs; j++) { if (Walker.MatchSpanName(list.Ids[j].Span, colName, tableName, dbName)) { cnt++; cntTab = 2; match = item; expr.ColumnId = j; hit = true; } } if (hit || table == null) continue; } if (dbName != null && table.Schema != schema) continue; if (tableName != null) { string tableName2 = (item.Alias != null ? item.Alias : table.Name); Debug.Assert(tableName2 != null); if (!string.Equals(tableName2, tableName, StringComparison.OrdinalIgnoreCase)) continue; } if (cntTab++ == 0) match = item; Column col; for (j = 0; j < table.Cols.length; j++) { col = table.Cols[j]; if (string.Equals(col.Name, colName, StringComparison.InvariantCultureIgnoreCase)) { // If there has been exactly one prior match and this match is for the right-hand table of a NATURAL JOIN or is in a // USING clause, then skip this match. if (cnt == 1) { if ((item.Jointype & JT.NATURAL) != 0) continue; if (NameInUsingClause(item.Using, colName)) continue; } cnt++; match = item; // Substitute the rowid (column -1) for the INTEGER PRIMARY KEY expr.ColumnId = (j == table.PKey ? -1 : (short)j); break; } } } if (match != null) { expr.TableId = match.Cursor; expr.Table = match.Table; schema = expr.Table.Schema; } } #if !OMIT_TRIGGER // If we have not already resolved the name, then maybe it is a new.* or old.* trigger argument reference if (dbName == null && tableName != null && cnt == 0 && parse.TriggerTab != null) { TK op = parse.TriggerOp; Table table = null; Debug.Assert(op == TK.DELETE || op == TK.UPDATE || op == TK.INSERT); if (op != TK.DELETE && string.Equals("new", tableName, StringComparison.InvariantCultureIgnoreCase)) { expr.TableId = 1; table = parse.TriggerTab; } else if (op != TK.INSERT && string.Equals("old", tableName, StringComparison.InvariantCultureIgnoreCase)) { expr.TableId = 0; table = parse.TriggerTab; } if (table != null) { int colId; schema = table.Schema; cntTab++; for (colId = 0; colId < table.Cols.length; colId++) { Column col = table.Cols[colId]; if (string.Equals(col.Name, colName, StringComparison.InvariantCultureIgnoreCase)) { if (colId == table.PKey) colId = -1; break; } } if (colId >= table.Cols.length && Expr.IsRowid(colName)) colId = -1; // IMP: R-44911-55124 if (colId < table.Cols.length) { cnt++; if (colId < 0) expr.Aff = AFF.INTEGER; else if (expr.TableId == 0) { C.ASSERTCOVERAGE(colId == 31); C.ASSERTCOVERAGE(colId == 32); parse.Oldmask |= (colId >= 32 ? 0xffffffff : (((uint)1) << colId)); } else { C.ASSERTCOVERAGE(colId == 31); C.ASSERTCOVERAGE(colId == 32); parse.Newmask |= (colId >= 32 ? 0xffffffff : (((uint)1) << colId)); } expr.ColumnId = (short)colId; expr.Table = table; isTrigger = true; } } } #endif // Perhaps the name is a reference to the ROWID if (cnt == 0 && cntTab == 1 && Expr.IsRowid(colName)) { cnt = 1; expr.ColumnId = -1; // IMP: R-44911-55124 expr.Aff = AFF.INTEGER; } // If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z might refer to an result-set alias. This happens, for example, when // we are resolving names in the WHERE clause of the following command: // // SELECT a+b AS x FROM table WHERE x<10; // // In cases like this, replace pExpr with a copy of the expression that forms the result set entry ("a+b" in the example) and return immediately. // Note that the expression in the result set should have already been resolved by the time the WHERE clause is resolved. if (cnt == 0 && (list = nc.EList) != null && tableName == null) { for (j = 0; j < list.Exprs; j++) { string asName = list.Ids[j].Name; if (asName != null && string.Equals(asName, colName, StringComparison.InvariantCultureIgnoreCase)) { Debug.Assert(expr.Left == null && expr.Right == null); Debug.Assert(expr.x.List == null); Debug.Assert(expr.x.Select == null); Expr orig = list.Ids[j].Expr; if ((nc.NCFlags & NC.AllowAgg) == 0 && E.ExprHasProperty(orig, EP.Agg)) { parse.ErrorMsg("misuse of aliased aggregate %s", asName); return WRC.Abort; } ResolveAlias(parse, list, j, expr, "", subquerys); cnt = 1; match = null; Debug.Assert(tableName == null && dbName == null); goto lookupname_end; } } } // Advance to the next name context. The loop will exit when either we have a match (cnt>0) or when we run out of name contexts. if (cnt == 0) { nc = nc.Next; subquerys++; } } // If X and Y are NULL (in other words if only the column name Z is supplied) and the value of Z is enclosed in double-quotes, then // Z is a string literal if it doesn't match any column names. In that case, we need to return right away and not make any changes to // pExpr. // // Because no reference was made to outer contexts, the pNC->nRef fields are not changed in any context. if (cnt == 0 && tableName == null && E.ExprHasProperty(expr, EP.DblQuoted)) { expr.OP = TK.STRING; expr.Table = null; return WRC.Prune; } // cnt==0 means there was not match. cnt>1 means there were two or more matches. Either way, we have an error. if (cnt != 1) { string err = (cnt == 0 ? "no such column" : "ambiguous column name"); if (dbName != null) parse.ErrorMsg("%s: %s.%s.%s", err, dbName, tableName, colName); else if (tableName != null) parse.ErrorMsg("%s: %s.%s", err, tableName, colName); else parse.ErrorMsg("%s: %s", err, colName); parse.CheckSchema = 1; topNC.Errs++; } // If a column from a table in pSrcList is referenced, then record this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes // bit 0 to be set. Column 1 sets bit 1. And so forth. If the column number is greater than the number of bits in the bitmask // then set the high-order bit of the bitmask. if (expr.ColumnId >= 0 && match != null) { int n = expr.ColumnId; C.ASSERTCOVERAGE(n == BMS - 1); if (n >= BMS) n = BMS - 1; Debug.Assert(match.Cursor == expr.TableId); match.ColUsed |= ((Bitmask)1) << n; } // Clean up and return Expr.Delete(ctx, ref expr.Left); expr.Left = null; Expr.Delete(ctx, ref expr.Right); expr.Right = null; expr.OP = (isTrigger ? TK.TRIGGER : TK.COLUMN); lookupname_end: if (cnt == 1) { Debug.Assert(nc != null); Auth.Read(parse, expr, schema, nc.SrcList); // Increment the nRef value on all name contexts from TopNC up to the point where the name matched. for (; ; ) { Debug.Assert(topNC != null); topNC.Refs++; if (topNC == nc) break; topNC = topNC.Next; } return WRC.Prune; } return WRC.Abort; } public static Expr CreateColumnExpr(Context ctx, SrcList src, int srcId, int colId) { Expr p = Expr.Alloc(ctx, TK.COLUMN, null, false); if (p != null) { SrcList.SrcListItem item = src.Ids[srcId]; p.Table = item.Table; p.TableId = item.Cursor; if (p.Table.PKey == colId) p.ColumnId = -1; else { p.ColumnId = (yVars)colId; C.ASSERTCOVERAGE(colId == BMS); C.ASSERTCOVERAGE(colId == BMS - 1); item.ColUsed |= ((Bitmask)1) << (colId >= BMS ? BMS - 1 : colId); } E.ExprSetProperty(p, EP.Resolved); } return p; } static WRC ResolveExprStep(Walker walker, Expr expr) { NameContext nc = walker.u.NC; Debug.Assert(nc != null); Parse parse = nc.Parse; Debug.Assert(parse == walker.Parse); if (E.ExprHasAnyProperty(expr, EP.Resolved)) return WRC.Prune; E.ExprSetProperty(expr, EP.Resolved); #if !NDEBUG if (nc.SrcList != null && nc.SrcList.Allocs > 0) { SrcList srcList = nc.SrcList; for (int i = 0; i < nc.SrcList.Srcs; i++) Debug.Assert(srcList.Ids[i].Cursor >= 0 && srcList.Ids[i].Cursor < parse.Tabs); } #endif switch (expr.OP) { #if ENABLE_UPDATE_DELETE_LIMIT && !OMIT_SUBQUERY // The special operator TK_ROW means use the rowid for the first column in the FROM clause. This is used by the LIMIT and ORDER BY // clause processing on UPDATE and DELETE statements. case TK.ROW: { SrcList srcList = nc.SrcList; Debug.Assert(srcList != null && srcList.Srcs == 1); SrcList.SrcListItem item = srcList.Ids[0]; expr.OP = TK.COLUMN; expr.Table = item.Table; expr.TableId = item.Cursor; expr.ColumnId = -1; expr.Aff = AFF.INTEGER; break; } #endif case TK.ID: // A lone identifier is the name of a column. { return LookupName(parse, null, null, expr.u.Token, nc, expr); } case TK.DOT: // A table name and column name: ID.ID Or a database, table and column: ID.ID.ID { string columnName; string tableName; string dbName; // if (srcList == nullptr) break; Expr right = expr.Right; if (right.OP == TK.ID) { dbName = null; tableName = expr.Left.u.Token; columnName = right.u.Token; } else { Debug.Assert(right.OP == TK.DOT); dbName = expr.Left.u.Token; tableName = right.Left.u.Token; columnName = right.Right.u.Token; } return LookupName(parse, dbName, tableName, columnName, nc, expr); } case TK.CONST_FUNC: case TK.FUNCTION: // Resolve function names { ExprList list = expr.x.List; // The argument list int n = (list != null ? list.Exprs : 0); // Number of arguments bool noSuchFunc = false; // True if no such function exists bool wrongNumArgs = false; // True if wrong number of arguments bool isAgg = false; // True if is an aggregate function TEXTENCODE encode = E.CTXENCODE(parse.Ctx); // The database encoding C.ASSERTCOVERAGE(expr.OP == TK.CONST_FUNC); Debug.Assert(!E.ExprHasProperty(expr, EP.xIsSelect)); string id = expr.u.Token; // The function name. int idLength = id.Length; // Number of characters in function name FuncDef def = Callback.FindFunction(parse.Ctx, id, idLength, n, encode, false); // Information about the function if (def == null) { def = Callback.FindFunction(parse.Ctx, id, idLength, -2, encode, false); if (def == null) noSuchFunc = true; else wrongNumArgs = true; } else isAgg = (def.Func == null); #if !OMIT_AUTHORIZATION if (def != null) { ARC auth = Auth.Check(parse, AUTH.FUNCTION, null, def.Name, null); // Authorization to use the function if (auth != ARC.OK) { if (auth == ARC.DENY) { parse.ErrorMsg("not authorized to use function: %s", def.Name); nc.Errs++; } expr.OP = TK.NULL; return WRC.Prune; } } #endif if (isAgg && (nc.NCFlags & NC.AllowAgg) == 0) { parse.ErrorMsg("misuse of aggregate function %.*s()", idLength, id); nc.Errs++; isAgg = false; } else if (noSuchFunc && !ctx.Init.Busy) { parse.ErrorMsg("no such function: %.*s", idLength, id); nc.Errs++; } else if (wrongNumArgs) { parse.ErrorMsg("wrong number of arguments to function %.*s()", idLength, id); nc.Errs++; } if (isAgg) nc.NCFlags &= ~NC.AllowAgg; walker.WalkExprList(list); if (isAgg) { NameContext nc2 = nc; expr.OP = TK.AGG_FUNCTION; expr.OP2 = 0; while (nc2 != null && !expr.FunctionUsesThisSrc(nc2.SrcList)) { expr.OP2++; nc2 = nc2.Next; } if (nc2 != null) nc2.NCFlags |= NC.HasAgg; nc.NCFlags |= NC.AllowAgg; } // FIX ME: Compute pExpr->affinity based on the expected return type of the function return WRC.Prune; } #if !OMIT_SUBQUERY case TK.SELECT: case TK.EXISTS: { C.ASSERTCOVERAGE(expr.OP == TK.EXISTS); goto case TK.IN; } #endif case TK.IN: { C.ASSERTCOVERAGE(expr.OP == TK.IN); if (E.ExprHasProperty(expr, EP.xIsSelect)) { int refs = nc.Refs; #if !OMIT_CHECK if ((nc.NCFlags & NC.IsCheck) != 0) parse.ErrorMsg("subqueries prohibited in CHECK constraints"); #endif walker.WalkSelect(expr.x.Select); Debug.Assert(nc.Refs >= refs); if (refs != nc.Refs) E.ExprSetProperty(expr, EP.VarSelect); } break; } #if !OMIT_CHECK case TK.VARIABLE: { if ((nc.NCFlags & NC.IsCheck) != 0) parse.ErrorMsg("parameters prohibited in CHECK constraints"); break; } #endif } return (parse.Errs != 0 || parse.Ctx.MallocFailed ? WRC.Abort : WRC.Continue); } static int ResolveAsName(Parse parse, ExprList list, Expr expr) { if (expr.OP == TK.ID) { string colName = expr.u.Token; for (int i = 0; i < list.Exprs; i++) { string asName = list.Ids[i].Name; if (asName != null && string.Equals(asName, colName, StringComparison.InvariantCultureIgnoreCase)) return i + 1; } } return 0; } static int ResolveOrderByTermToExprList(Parse parse, Select select, Expr expr) { int i = 0; Debug.Assert(!expr.IsInteger(ref i)); ExprList list = select.EList; // The columns of the result set // Resolve all names in the ORDER BY term expression NameContext nc = new NameContext(); // Name context for resolving pE nc.Parse = parse; nc.SrcList = select.Src; nc.EList = list; nc.NCFlags = NC.AllowAgg; nc.Errs = 0; Context ctx = parse.Ctx; // Database connection byte savedSuppErr = ctx.SuppressErr; // Saved value of db->suppressErr ctx.SuppressErr = 1; bool r = Walker.ResolveExprNames(nc, ref expr); ctx.SuppressErr = savedSuppErr; if (r) return 0; // Try to match the ORDER BY expression against an expression in the result set. Return an 1-based index of the matching result-set entry. for (i = 0; i < list.Exprs; i++) if (Expr.Compare(list.Ids[i].Expr, expr) < 2) return i + 1; // If no match, return 0. return 0; } static void ResolveOutOfRangeError(Parse parse, string typeName, int i, int max) { parse.ErrorMsg("%r %s BY term out of range - should be between 1 and %d", i, typeName, max); } static int ResolveCompoundOrderBy(Parse parse, Select select) { ExprList orderBy = select.OrderBy; if (orderBy == null) return 0; Context ctx = parse.Ctx; #if true || MAX_COLUMN if (orderBy.Exprs > ctx.Limits[(int)LIMIT.COLUMN]) { parse.ErrorMsg("too many terms in ORDER BY clause"); return 1; } #endif int i; for (i = 0; i < orderBy.Exprs; i++) orderBy.Ids[i].Done = false; select.Next = null; while (select.Prior != null) { select.Prior.Next = select; select = select.Prior; } bool moreToDo = true; while (select != null && moreToDo) { moreToDo = false; ExprList list = select.EList; Debug.Assert(list != null); ExprList.ExprListItem item; for (i = 0; i < orderBy.Exprs; i++) { item = orderBy.Ids[i]; Expr pDup; if (item.Done) continue; Expr expr = item.Expr; int colId = -1; if (expr.IsInteger(ref colId)) { if (colId <= 0 || colId > list.Exprs) { ResolveOutOfRangeError(parse, "ORDER", i + 1, list.Exprs); return 1; } } else { colId = ResolveAsName(parse, list, expr); if (colId == 0) { Expr dupExpr = Expr.Dup(ctx, expr, 0); if (!ctx.MallocFailed) { Debug.Assert(dupExpr != null); colId = ResolveOrderByTermToExprList(parse, select, dupExpr); } Expr.Delete(ctx, ref dupExpr); } } if (colId > 0) { // Convert the ORDER BY term into an integer column number iCol, taking care to preserve the COLLATE clause if it exists Expr newExpr = Expr.Expr_(ctx, TK.INTEGER, null); if (newExpr == null) return 1; newExpr.Flags |= EP.IntValue; newExpr.u.I = colId; if (item.Expr == expr) item.Expr = newExpr; else { Debug.Assert(item.Expr.OP == TK.COLLATE); Debug.Assert(item.Expr.Left == expr); item.Expr.Left = newExpr; } Expr.Delete(ctx, ref expr); item.OrderByCol = (ushort)colId; item.Done = true; } else moreToDo = true; } select = select.Next; } for (i = 0; i < orderBy.Exprs; i++) { if (!orderBy.Ids[i].Done) { parse.ErrorMsg("%r ORDER BY term does not match any column in the result set", i + 1); return 1; } } return 0; } public static bool ResolveOrderGroupBy(Parse parse, Select select, ExprList orderBy, string type) { Context ctx = parse.Ctx; if (orderBy == null || parse.Ctx.MallocFailed) return 0; #if !MAX_COLUMN if (orderBy.Exprs > ctx.Limits[(int)LIMIT.COLUMN]) { parse.ErrorMsg("too many terms in %s BY clause", type); return true; } #endif ExprList list = select.EList; Debug.Assert(list != null); // sqlite3SelectNew() guarantees this int i; ExprList.ExprListItem item; for (i = 0; i < orderBy.Exprs; i++) { item = orderBy.Ids[i]; if (item.OrderByCol != null) { if (item.OrderByCol > list.Exprs) { ResolveOutOfRangeError(parse, type, i + 1, list.Exprs); return true; } ResolveAlias(parse, list, item.OrderByCol - 1, item.Expr, type); } } return false; } static bool ResolveOrderGroupBy(NameContext nc, Select select, ExprList orderBy, string type) { if (orderBy == null) return false; int result = select.EList.Exprs; // Number of terms in the result set Parse parse = nc.Parse; // Parsing context int i; ExprList.ExprListItem item; // A term of the ORDER BY clause for (i = 0; i < orderBy.Exprs; i++) { item = orderBy.Ids[i]; Expr expr = item.Expr; int colId = ResolveAsName(parse, select.EList, expr); // Column number if (colId > 0) { // If an AS-name match is found, mark this ORDER BY column as being a copy of the iCol-th result-set column. The subsequent call to // sqlite3ResolveOrderGroupBy() will convert the expression to a copy of the iCol-th result-set expression. item.OrderByCol = (ushort)colId; continue; } if (expr.SkipCollate().IsInteger(ref colId)) { // The ORDER BY term is an integer constant. Again, set the column number so that sqlite3ResolveOrderGroupBy() will convert the // order-by term to a copy of the result-set expression if (colId < 1 || colId > 0xffff) { ResolveOutOfRangeError(parse, type, i + 1, result); return true; } item.OrderByCol = (ushort)colId; continue; } // Otherwise, treat the ORDER BY term as an ordinary expression item.OrderByCol = 0; if (Walker.ResolveExprNames(nc, ref expr)) return true; for (int j = 0; j < select.EList.Exprs; j++) if (Expr.Compare(expr, select.EList.Ids[j].Expr) == 0) item.OrderByCol = (ushort)(j + 1); } return Walker.ResolveOrderGroupBy(parse, select, orderBy, type); } static WRC ResolveSelectStep(Walker walker, Select p) { Debug.Assert(p != null); if ((p.SelFlags & SF.Resolved) != 0) return WRC.Prune; NameContext outerNC = walker.u.NC; // Context that contains this SELECT Parse parse = walker.Parse; // Parsing context Context ctx = parse.Ctx; // Database connection // Normally sqlite3SelectExpand() will be called first and will have already expanded this SELECT. However, if this is a subquery within // an expression, sqlite3ResolveExprNames() will be called without a prior call to sqlite3SelectExpand(). When that happens, let // sqlite3SelectPrep() do all of the processing for this SELECT. sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and // this routine in the correct order. if ((p.SelFlags & SF.Expanded) == 0) { p.Prep(parse, outerNC); return (parse.Errs != 0 || ctx.MallocFailed ? WRC.Abort : WRC.Prune); } bool isCompound = (p.Prior != null); // True if p is a compound select int compounds = 0; // Number of compound terms processed so far Select leftmost = p; // Left-most of SELECT of a compound int i; NameContext nc; // Name context of this SELECT while (p != null) { Debug.Assert((p.SelFlags & SF.Expanded) != 0); Debug.Assert((p.SelFlags & SF.Resolved) == 0); p.SelFlags |= SF.Resolved; // Resolve the expressions in the LIMIT and OFFSET clauses. These are not allowed to refer to any names, so pass an empty NameContext. nc = new NameContext(); //: _memset(&nc, 0, sizeof(nc)); nc.Parse = parse; if (Walker.ResolveExprNames(nc, ref p.Limit) || Walker.ResolveExprNames(nc, ref p.Offset)) return WRC.Abort; // Recursively resolve names in all subqueries SrcList.SrcListItem item; for (i = 0; i < p.Src.Srcs; i++) { item = p.Src.Ids[i]; if (item.Select != null) { NameContext nc2; // Used to iterate name contexts int refs = 0; // Refcount for pOuterNC and outer contexts string savedContext = parse.AuthContext; // Count the total number of references to pOuterNC and all of its parent contexts. After resolving references to expressions in // pItem->pSelect, check if this value has changed. If so, then SELECT statement pItem->pSelect must be correlated. Set the // pItem->isCorrelated flag if this is the case. for (nc2 = outerNC; nc2 != null; nc2 = nc2.Next) refs += nc2.Refs; if (item.Name != null) parse.AuthContext = item.Name; Walker.ResolveSelectNames(parse, item.Select, outerNC); parse.AuthContext = savedContext; if (parse.Errs != 0 || ctx.MallocFailed) return WRC.Abort; for (nc2 = outerNC; nc2 != null; nc2 = nc2.Next) refs -= nc2.Refs; Debug.Assert(!item.IsCorrelated && refs <= 0); item.IsCorrelated = (refs != 0); } } // Set up the local name-context to pass to sqlite3ResolveExprNames() to resolve the result-set expression list. nc.NCFlags = NC.AllowAgg; nc.SrcList = p.Src; nc.Next = outerNC; // Resolve names in the result set. ExprList list = p.EList; // Result set expression list Debug.Assert(list != null); for (i = 0; i < list.Exprs; i++) { Expr expr = list.Ids[i].Expr; if (Walker.ResolveExprNames(nc, ref expr)) return WRC.Abort; } // If there are no aggregate functions in the result-set, and no GROUP BY expression, do not allow aggregates in any of the other expressions. Debug.Assert((p.SelFlags & SF.Aggregate) == 0); ExprList groupBy = p.GroupBy; // The GROUP BY clause if (groupBy != null || (nc.NCFlags & NC.HasAgg) != 0) p.SelFlags |= SF.Aggregate; else nc.NCFlags &= ~NC.AllowAgg; // If a HAVING clause is present, then there must be a GROUP BY clause. if (p.Having != null && groupBy == null) { parse.ErrorMsg("a GROUP BY clause is required before HAVING"); return WRC.Abort; } // Add the expression list to the name-context before parsing the other expressions in the SELECT statement. This is so that // expressions in the WHERE clause (etc.) can refer to expressions by aliases in the result set. // // Minor point: If this is the case, then the expression will be re-evaluated for each reference to it. nc.EList = p.EList; if (Walker.ResolveExprNames(nc, ref p.Where) || Walker.ResolveExprNames(nc, ref p.Having)) return WRC.Abort; // The ORDER BY and GROUP BY clauses may not refer to terms in outer queries nc.Next = null; nc.NCFlags |= NC.AllowAgg; // Process the ORDER BY clause for singleton SELECT statements. The ORDER BY clause for compounds SELECT statements is handled // below, after all of the result-sets for all of the elements of the compound have been resolved. if (!isCompound && Walker.ResolveOrderGroupBy(nc, p, p.OrderBy, "ORDER")) return WRC.Abort; if (ctx.MallocFailed) return WRC.Abort; // Resolve the GROUP BY clause. At the same time, make sure the GROUP BY clause does not contain aggregate functions. if (groupBy != null) { if (Walker.ResolveOrderGroupBy(nc, p, groupBy, "GROUP") || ctx.MallocFailed) return WRC.Abort; ExprList.ExprListItem item2; for (i = 0; i < groupBy.Exprs; i++) { item2 = groupBy.Ids[i]; if (E.ExprHasProperty(item2.Expr, EP.Agg)) { parse.ErrorMsg("aggregate functions are not allowed in the GROUP BY clause"); return WRC.Abort; } } } // Advance to the next term of the compound p = p.Prior; compounds++; } // Resolve the ORDER BY on a compound SELECT after all terms of the compound have been resolved. return (isCompound && ResolveCompoundOrderBy(parse, leftmost) != 0 ? WRC.Abort : WRC.Prune); } public static bool ResolveExprNames(NameContext nc, ref Expr expr) { if (expr == null) return false; #if MAX_EXPR_DEPTH { Parse parse = nc.Parse; if (Expr.CheckHeight(parse, expr.Height + nc.Parse.Height) != 0) return true; parse.Height += expr.Height; } #endif bool savedHasAgg = ((nc.NCFlags & NC.HasAgg) != 0); nc.NCFlags &= ~NC.HasAgg; Walker w = new Walker(); w.ExprCallback = ResolveExprStep; w.SelectCallback = ResolveSelectStep; w.Parse = nc.Parse; w.u.NC = nc; w.WalkExpr(expr); #if MAX_EXPR_DEPTH nc.Parse.Height -= expr.Height; #endif if (nc.Errs > 0 || w.Parse.Errs > 0) E.ExprSetProperty(expr, EP.Error); if ((nc.NCFlags & NC.HasAgg) != 0) E.ExprSetProperty(expr, EP.Agg); else if (savedHasAgg) nc.NCFlags |= NC.HasAgg; return E.ExprHasProperty(expr, EP.Error); } public static void ResolveSelectNames(Parse parse, Select p, NameContext outerNC) { Debug.Assert(p != null); Walker w = new Walker(); w.ExprCallback = ResolveExprStep; w.SelectCallback = ResolveSelectStep; w.Parse = parse; w.u.NC = outerNC; w.WalkSelect(p); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gciv = Google.Cloud.Iam.V1; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.PubSub.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedPublisherServiceApiClientTest { [xunit::FactAttribute] public void CreateTopicRequestObject() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); Topic request = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.CreateTopic(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTopicRequestObjectAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); Topic request = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.CreateTopicAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.CreateTopicAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTopic() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); Topic request = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.CreateTopic(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTopicAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); Topic request = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.CreateTopicAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.CreateTopicAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTopicResourceNames() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); Topic request = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.CreateTopic(request.TopicName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTopicResourceNamesAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); Topic request = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.CreateTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.CreateTopicAsync(request.TopicName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.CreateTopicAsync(request.TopicName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTopicRequestObject() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); UpdateTopicRequest request = new UpdateTopicRequest { Topic = new Topic(), UpdateMask = new wkt::FieldMask(), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.UpdateTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.UpdateTopic(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTopicRequestObjectAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); UpdateTopicRequest request = new UpdateTopicRequest { Topic = new Topic(), UpdateMask = new wkt::FieldMask(), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.UpdateTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.UpdateTopicAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.UpdateTopicAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PublishRequestObject() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; PublishResponse expectedResponse = new PublishResponse { MessageIds = { "message_idsbfb136bc", }, }; mockGrpcClient.Setup(x => x.Publish(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); PublishResponse response = client.Publish(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PublishRequestObjectAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; PublishResponse expectedResponse = new PublishResponse { MessageIds = { "message_idsbfb136bc", }, }; mockGrpcClient.Setup(x => x.PublishAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PublishResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); PublishResponse responseCallSettings = await client.PublishAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PublishResponse responseCancellationToken = await client.PublishAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Publish() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; PublishResponse expectedResponse = new PublishResponse { MessageIds = { "message_idsbfb136bc", }, }; mockGrpcClient.Setup(x => x.Publish(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); PublishResponse response = client.Publish(request.Topic, request.Messages); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PublishAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; PublishResponse expectedResponse = new PublishResponse { MessageIds = { "message_idsbfb136bc", }, }; mockGrpcClient.Setup(x => x.PublishAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PublishResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); PublishResponse responseCallSettings = await client.PublishAsync(request.Topic, request.Messages, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PublishResponse responseCancellationToken = await client.PublishAsync(request.Topic, request.Messages, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PublishResourceNames() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; PublishResponse expectedResponse = new PublishResponse { MessageIds = { "message_idsbfb136bc", }, }; mockGrpcClient.Setup(x => x.Publish(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); PublishResponse response = client.Publish(request.TopicAsTopicName, request.Messages); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PublishResourceNamesAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); PublishRequest request = new PublishRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Messages = { new PubsubMessage(), }, }; PublishResponse expectedResponse = new PublishResponse { MessageIds = { "message_idsbfb136bc", }, }; mockGrpcClient.Setup(x => x.PublishAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PublishResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); PublishResponse responseCallSettings = await client.PublishAsync(request.TopicAsTopicName, request.Messages, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PublishResponse responseCancellationToken = await client.PublishAsync(request.TopicAsTopicName, request.Messages, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTopicRequestObject() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); GetTopicRequest request = new GetTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.GetTopic(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTopicRequestObjectAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); GetTopicRequest request = new GetTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.GetTopicAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.GetTopicAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTopic() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); GetTopicRequest request = new GetTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.GetTopic(request.Topic); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTopicAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); GetTopicRequest request = new GetTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.GetTopicAsync(request.Topic, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.GetTopicAsync(request.Topic, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTopicResourceNames() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); GetTopicRequest request = new GetTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic response = client.GetTopic(request.TopicAsTopicName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTopicResourceNamesAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); GetTopicRequest request = new GetTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; Topic expectedResponse = new Topic { TopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), Labels = { { "key8a0b6e3c", "value60c16320" }, }, MessageStoragePolicy = new MessageStoragePolicy(), KmsKeyName = "kms_key_name06bd122b", SchemaSettings = new SchemaSettings(), SatisfiesPzs = false, MessageRetentionDuration = new wkt::Duration(), }; mockGrpcClient.Setup(x => x.GetTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Topic>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); Topic responseCallSettings = await client.GetTopicAsync(request.TopicAsTopicName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Topic responseCancellationToken = await client.GetTopicAsync(request.TopicAsTopicName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTopicRequestObject() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DeleteTopicRequest request = new DeleteTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); client.DeleteTopic(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTopicRequestObjectAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DeleteTopicRequest request = new DeleteTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); await client.DeleteTopicAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTopicAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTopic() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DeleteTopicRequest request = new DeleteTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); client.DeleteTopic(request.Topic); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTopicAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DeleteTopicRequest request = new DeleteTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); await client.DeleteTopicAsync(request.Topic, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTopicAsync(request.Topic, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTopicResourceNames() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DeleteTopicRequest request = new DeleteTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTopic(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); client.DeleteTopic(request.TopicAsTopicName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTopicResourceNamesAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DeleteTopicRequest request = new DeleteTopicRequest { TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTopicAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); await client.DeleteTopicAsync(request.TopicAsTopicName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTopicAsync(request.TopicAsTopicName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DetachSubscriptionRequestObject() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DetachSubscriptionRequest request = new DetachSubscriptionRequest { SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"), }; DetachSubscriptionResponse expectedResponse = new DetachSubscriptionResponse { }; mockGrpcClient.Setup(x => x.DetachSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); DetachSubscriptionResponse response = client.DetachSubscription(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DetachSubscriptionRequestObjectAsync() { moq::Mock<Publisher.PublisherClient> mockGrpcClient = new moq::Mock<Publisher.PublisherClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateIAMPolicyClient()).Returns(new moq::Mock<gciv::IAMPolicy.IAMPolicyClient>().Object); DetachSubscriptionRequest request = new DetachSubscriptionRequest { SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"), }; DetachSubscriptionResponse expectedResponse = new DetachSubscriptionResponse { }; mockGrpcClient.Setup(x => x.DetachSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetachSubscriptionResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PublisherServiceApiClient client = new PublisherServiceApiClientImpl(mockGrpcClient.Object, null); DetachSubscriptionResponse responseCallSettings = await client.DetachSubscriptionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DetachSubscriptionResponse responseCancellationToken = await client.DetachSubscriptionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using UnityEngine; using UnityEngine.Rendering; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityPlatformer { /// <summary> /// Create a mesh for given Collider2D and apply it material. /// /// NOTE: MeshFilter and MeshRenderer are hidden /// </summary> [ExecuteInEditMode] [RequireComponent(typeof(Collider2D))] public class Collider2DRenderer : MonoBehaviour { /// <summary> /// Setter/Getter Mesh material (update MeshRenderer) /// </summary> public Material material { get { return _material; } set { _material = value; if (_mr == null) { _mr.sharedMaterial = _material; } } } /// <summary> /// Default material /// </summary> static protected Material _default_material; [SerializeField] /// <summary> /// Current material /// </summary> protected Material _material; /// <summary> /// MeshFilter reference /// </summary> protected MeshFilter _mf; /// <summary> /// MeshRenderer reference /// </summary> protected MeshRenderer _mr; /// <summary> /// Listen to validate event to keep the renderer sane with use input /// </summary> void OnValidate() { _mf = GetComponent<MeshFilter>(); _mr = GetComponent<MeshRenderer>(); if (_mf == null) { _mf = gameObject.AddComponent<MeshFilter>(); } if (_mr == null) { _mr = gameObject.AddComponent<MeshRenderer>(); } _mr.receiveShadows = false; _mr.shadowCastingMode = ShadowCastingMode.Off; _mr.reflectionProbeUsage = ReflectionProbeUsage.Off; _mr.sharedMaterial = material != null ? material : _default_material; _mf.hideFlags = HideFlags.HideInInspector; _mr.hideFlags = HideFlags.HideInInspector; } /// <summary> /// /// </summary> void Start() { #if UNITY_EDITOR if (_default_material == null) { // TODO fixit! //_default_material = Resources.Load("Transparent", typeof(Material)) as // Material; _default_material = AssetDatabase.LoadAssetAtPath<Material>( "Collider2DRenderer.mat"); //_default_material = new Material(Shader.Find("Transparent")); } #endif if (_default_material == null) { //Debug.LogWarning("cannot load Transparent material!"); } #if UNITY_EDITOR OnValidate(); #endif Update(); } /// <summary> /// Create the mesh /// </summary> void Update() { #if UNITY_EDITOR OnValidate(); #endif Mesh mesh = new Mesh(); PolygonCollider2D _polygon2d = gameObject.GetComponent<PolygonCollider2D>(); BoxCollider2D _box2d = gameObject.GetComponent<BoxCollider2D>(); CircleCollider2D _circle2d = gameObject.GetComponent<CircleCollider2D>(); EdgeCollider2D _edge2d = gameObject.GetComponent<EdgeCollider2D>(); if (_polygon2d) { // points are alredy rotated :) int pointCount = _polygon2d.GetTotalPointCount(); Vector2[] points = _polygon2d.points; Vector3[] vertices = new Vector3[pointCount]; for (int j = 0; j < pointCount; j++) { Vector2 actual = points[j]; vertices[j] = new Vector3(actual.x, actual.y, 0); } Triangulator tr = new Triangulator(points); int[] triangles = tr.Triangulate(); mesh.vertices = vertices; mesh.triangles = triangles; } if (_box2d) { mesh.vertices = GetBoxCorners(_box2d); int[] triangles = {0, 1, 2, 1, 3, 2}; mesh.triangles = triangles; } if (_circle2d) { float scale = 1f / 16f; Vector3[] vertices = new Vector3[16]; Vector2[] points = new Vector2[16]; for (int j = 0; j < 16; j++) { float x = (_circle2d.offset.x + Mathf.Cos(scale * j * 2 * Mathf.PI) * _circle2d.radius) * _circle2d.transform.localScale.x; float y = (_circle2d.offset.y + Mathf.Sin(scale * j * 2 * Mathf.PI) * _circle2d.radius) * _circle2d.transform.localScale.y; points[j] = new Vector2(x, y); vertices[j] = new Vector3(x, y, 0); } Triangulator tr = new Triangulator(points); int[] triangles = tr.Triangulate(); mesh.vertices = vertices; mesh.triangles = triangles; } if (_edge2d) { Debug.LogWarning("EdgeCollider2D is not supported"); } _mf.mesh = mesh; } // Assign the collider in the inspector or elsewhere in your code Vector3[] GetBoxCorners(BoxCollider2D box) { Transform bcTransform = box.transform; // The collider's local width and height, accounting for scale, divided by 2 Vector2 size = new Vector2(box.size.x * bcTransform.localScale.x * 0.5f, box.size.y * bcTransform.localScale.y * 0.5f); // Find the 4 corners of the BoxCollider2D in LOCAL space, if the // BoxCollider2D had never been rotated Quaternion rotationInverse = Quaternion.Inverse(transform.rotation); Vector3 corner1 = rotationInverse * new Vector2(-size.x + box.offset.x, -size.y + box.offset.y); Vector3 corner2 = rotationInverse * new Vector2(-size.x + box.offset.x, size.y + box.offset.y); Vector3 corner3 = rotationInverse * new Vector2(size.x + box.offset.x, -size.y + box.offset.y); Vector3 corner4 = rotationInverse * new Vector2(size.x + box.offset.x, size.y + box.offset.y); // Rotate those 4 corners around the centre of the collider to match its // transform.rotation corner1 = RotatePointAroundPivot(corner1, Vector3.zero, bcTransform.eulerAngles); corner2 = RotatePointAroundPivot(corner2, Vector3.zero, bcTransform.eulerAngles); corner3 = RotatePointAroundPivot(corner3, Vector3.zero, bcTransform.eulerAngles); corner4 = RotatePointAroundPivot(corner4, Vector3.zero, bcTransform.eulerAngles); Vector3[] ret = new Vector3[4]; ret[0] = corner1; ret[1] = corner2; ret[2] = corner3; ret[3] = corner4; return ret; } // Helper method courtesy of @aldonaletto // http://answers.unity3d.com/questions/532297/rotate-a-vector-around-a-certain-point.html Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) { Vector3 dir = point - pivot; // get point direction relative to pivot dir = Quaternion.Euler(angles) * dir; // rotate it point = dir + pivot; // calculate rotated point return point; // return it } void OnDisable() { OnValidate(); //_mf.enabled = false; _mr.enabled = false; } void OnEnable() { OnValidate(); //_mf.enabled = true; _mr.enabled = true; } } }
using System; using System.Reflection; using System.IO; using Newtonsoft.Json; using NUnit.Framework; using System.Collections.Generic; namespace OpenQA.Selenium.Environment { public class EnvironmentManager { private static EnvironmentManager instance; private Type driverType; private Browser browser; private IWebDriver driver; private UrlBuilder urlBuilder; private TestWebServer webServer; private DriverFactory driverFactory; private RemoteSeleniumServer remoteServer; private string remoteCapabilities; private EnvironmentManager() { string currentDirectory = this.CurrentDirectory; string defaultConfigFile = Path.Combine(currentDirectory, "appconfig.json"); string configFile = TestContext.Parameters.Get<string>("ConfigFile", defaultConfigFile).Replace('/', Path.DirectorySeparatorChar); string content = File.ReadAllText(configFile); TestEnvironment env = JsonConvert.DeserializeObject<TestEnvironment>(content); bool captureWebServerOutput = TestContext.Parameters.Get<bool>("CaptureWebServerOutput", env.CaptureWebServerOutput); bool hideWebServerCommandPrompt = TestContext.Parameters.Get<bool>("HideWebServerCommandPrompt", env.HideWebServerCommandPrompt); string activeDriverConfig = TestContext.Parameters.Get("ActiveDriverConfig", env.ActiveDriverConfig); string activeWebsiteConfig = TestContext.Parameters.Get("ActiveWebsiteConfig", env.ActiveWebsiteConfig); string driverServiceLocation = TestContext.Parameters.Get("DriverServiceLocation", env.DriverServiceLocation); DriverConfig driverConfig = env.DriverConfigs[activeDriverConfig]; WebsiteConfig websiteConfig = env.WebSiteConfigs[activeWebsiteConfig]; this.driverFactory = new DriverFactory(driverServiceLocation); this.driverFactory.DriverStarting += OnDriverStarting; Assembly driverAssembly = Assembly.Load(driverConfig.AssemblyName); driverType = driverAssembly.GetType(driverConfig.DriverTypeName); browser = driverConfig.BrowserValue; remoteCapabilities = driverConfig.RemoteCapabilities; urlBuilder = new UrlBuilder(websiteConfig); // When run using the `bazel test` command, the following environment // variable will be set. If not set, we're running from a build system // outside Bazel, and need to locate the directory containing the jar. string projectRoot = System.Environment.GetEnvironmentVariable("TEST_SRCDIR"); if (string.IsNullOrEmpty(projectRoot)) { // Walk up the directory tree until we find ourselves in a directory // where the path to the Java web server can be determined. bool continueTraversal = true; DirectoryInfo info = new DirectoryInfo(currentDirectory); while (continueTraversal) { if (info == info.Root) { break; } foreach (var childDir in info.EnumerateDirectories()) { // Case 1: The current directory of this assembly is in the // same direct sub-tree as the Java targets (usually meaning // executing tests from the same build system as that which // builds the Java targets). // If we find a child directory named "java", then the web // server should be able to be found under there. if (string.Compare(childDir.Name, "java", StringComparison.OrdinalIgnoreCase) == 0) { continueTraversal = false; break; } // Case 2: The current directory of this assembly is a different // sub-tree as the Java targets (usually meaning executing tests // from a different build system as that which builds the Java // targets). // If we travel to a place in the tree where there is a child // directory named "bazel-bin", the web server should be found // in the "java" subdirectory of that directory. if (string.Compare(childDir.Name, "bazel-bin", StringComparison.OrdinalIgnoreCase) == 0) { string javaOutDirectory = Path.Combine(childDir.FullName, "java"); if (Directory.Exists(javaOutDirectory)) { info = childDir; continueTraversal = false; break; } } } if (continueTraversal) { info = info.Parent; } } projectRoot = info.FullName; } else { projectRoot += "/selenium"; } webServer = new TestWebServer(projectRoot, captureWebServerOutput, hideWebServerCommandPrompt); bool autoStartRemoteServer = false; if (browser == Browser.Remote) { autoStartRemoteServer = driverConfig.AutoStartRemoteServer; } remoteServer = new RemoteSeleniumServer(projectRoot, autoStartRemoteServer); } ~EnvironmentManager() { if (remoteServer != null) { remoteServer.Stop(); } if (webServer != null) { webServer.Stop(); } if (driver != null) { driver.Quit(); } } public event EventHandler<DriverStartingEventArgs> DriverStarting; public static EnvironmentManager Instance { get { if (instance == null) { instance = new EnvironmentManager(); } return instance; } } public Browser Browser { get { return browser; } } public string DriverServiceDirectory { get { return this.driverFactory.DriverServicePath; } } public string CurrentDirectory { get { string assemblyLocation = Path.GetDirectoryName(typeof(EnvironmentManager).Assembly.Location); string testDirectory = TestContext.CurrentContext.TestDirectory; if (assemblyLocation != testDirectory) { return assemblyLocation; } return testDirectory; } } public TestWebServer WebServer { get { return webServer; } } public RemoteSeleniumServer RemoteServer { get { return remoteServer; } } public string RemoteCapabilities { get { return remoteCapabilities; } } public UrlBuilder UrlBuilder { get { return urlBuilder; } } public IWebDriver GetCurrentDriver() { if (driver != null) { return driver; } else { return CreateFreshDriver(); } } public IWebDriver CreateDriverInstance() { return driverFactory.CreateDriver(driverType); } public IWebDriver CreateDriverInstance(DriverOptions options) { return driverFactory.CreateDriverWithOptions(driverType, options); } public IWebDriver CreateFreshDriver() { CloseCurrentDriver(); driver = CreateDriverInstance(); return driver; } public void CloseCurrentDriver() { if (driver != null) { driver.Quit(); } driver = null; } protected void OnDriverStarting(object sender, DriverStartingEventArgs e) { if (this.DriverStarting != null) { this.DriverStarting(sender, e); } } } }
// <copyright file="UserLUTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // 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> using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Factorization { using Numerics; /// <summary> /// LU factorization tests for a user matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class UserLUTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorLU = matrixI.LU(); // Check lower triangular part. var matrixL = factorLU.L; Assert.AreEqual(matrixI.RowCount, matrixL.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount); for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < matrixL.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, matrixL[i, j]); } } // Check upper triangular part. var matrixU = factorLU.U; Assert.AreEqual(matrixI.RowCount, matrixU.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount); for (var i = 0; i < matrixU.RowCount; i++) { for (var j = 0; j < matrixU.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, matrixU[i, j]); } } } /// <summary> /// LU factorization fails with a non-square matrix. /// </summary> [Test] public void LUFailsWithNonSquareMatrix() { var matrix = new UserDefinedMatrix(3, 1); Assert.That(() => matrix.LU(), Throws.ArgumentException); } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = UserDefinedMatrix.Identity(order); var lu = matrixI.LU(); Assert.AreEqual(Complex32.One, lu.Determinant); } /// <summary> /// Can factorize a random square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanFactorizeRandomMatrix(int order) { var matrixX = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var factorLU = matrixX.LU(); var matrixL = factorLU.L; var matrixU = factorLU.U; // Make sure the factors have the right dimensions. Assert.AreEqual(order, matrixL.RowCount); Assert.AreEqual(order, matrixL.ColumnCount); Assert.AreEqual(order, matrixU.RowCount); Assert.AreEqual(order, matrixU.ColumnCount); // Make sure the L factor is lower triangular. for (var i = 0; i < matrixL.RowCount; i++) { Assert.AreEqual(Complex32.One, matrixL[i, i]); for (var j = i + 1; j < matrixL.ColumnCount; j++) { Assert.AreEqual(Complex32.Zero, matrixL[i, j]); } } // Make sure the U factor is upper triangular. for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < i; j++) { Assert.AreEqual(Complex32.Zero, matrixU[i, j]); } } // Make sure the LU factor times it's transpose is the original matrix. var matrixXfromLU = matrixL * matrixU; var permutationInverse = factorLU.P.Inverse(); matrixXfromLU.PermuteRows(permutationInverse); for (var i = 0; i < matrixXfromLU.RowCount; i++) { for (var j = 0; j < matrixXfromLU.ColumnCount; j++) { Assert.AreEqual(matrixX[i, j].Real, matrixXfromLU[i, j].Real, 1e-3f); Assert.AreEqual(matrixX[i, j].Imaginary, matrixXfromLU[i, j].Imaginary, 1e-3f); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = new UserDefinedVector(Vector<Complex32>.Build.Random(order, 1).ToArray()); var resultx = factorLU.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-3f); Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-3f); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixX = factorLU.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1e-3f); Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1e-3f); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = new UserDefinedVector(Vector<Complex32>.Build.Random(order, 1).ToArray()); var vectorbCopy = vectorb.Clone(); var resultx = new UserDefinedVector(order); factorLU.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-3f); Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-3f); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix row number.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(order, order); factorLU.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1e-3f); Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1e-3f); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can inverse a matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanInverse(int order) { var matrixA = new UserDefinedMatrix(Matrix<Complex32>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixAInverse = factorLU.Inverse(); // The inverse dimension is equal A Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount); Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount); var matrixIdentity = matrixA * matrixAInverse; // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Check if multiplication of A and AI produced identity matrix. for (var i = 0; i < matrixIdentity.RowCount; i++) { Assert.AreEqual(matrixIdentity[i, i].Real, Complex32.One.Real, 1e-3f); Assert.AreEqual(matrixIdentity[i, i].Imaginary, Complex32.One.Imaginary, 1e-3f); } } } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V10.Common; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Resources; using Google.Ads.GoogleAds.V10.Services; using System; using System.Collections.Generic; using System.Linq; using static Google.Ads.GoogleAds.V10.Enums.ExtensionTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.AssetFieldTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// This example adds a hotel callout extension to a specific account, campaign within the /// account, and ad group within the campaign. /// </summary> public class AddHotelCallout : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddHotelCallout"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// The language code for the text. See supported languages at: /// https://developers.google.com/hotels/hotel-ads/api-reference/language-codes. /// </summary> [Option("languageCode", Required = true, HelpText = "The language code for the text. See supported languages at: " + "https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.")] public string LanguageCode { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The customer ID for which the call is made. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // The language code for the text. See supported languages at: // https://developers.google.com/hotels/hotel-ads/api-reference/language-codes. options.LanguageCode = "INSERT_LANGUAGE_CODE_HERE"; return 0; }); AddHotelCallout codeExample = new AddHotelCallout(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.LanguageCode); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This example adds a hotel callout extension to a specific account."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="languageCode">The language code for the text. See supported languages at: /// https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.</param> public void Run(GoogleAdsClient client, long customerId, string languageCode) { try { // Creates assets for the hotel callout extensions. List<string> assetResourceNames = AddExtensionAsset(client, customerId, languageCode); // Adds the extensions at the account level, so these will serve in all eligible // campaigns. LinkAssetToAccount(client, customerId, assetResourceNames); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates a new asset for the callout. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The client customer ID.</param> /// <param name="languageCode">The language code for the text.</param> /// <returns>The created extension feed item's resource name.</returns> private List<string> AddExtensionAsset(GoogleAdsClient client, in long customerId, string languageCode) { List<HotelCalloutAsset> hotelCalloutAssets = new List<HotelCalloutAsset>(); // Creates the callouts with text and specified language. hotelCalloutAssets.Add( new HotelCalloutAsset { Text = "Activities", LanguageCode = languageCode, }); hotelCalloutAssets.Add( new HotelCalloutAsset { Text = "Facilities", LanguageCode = languageCode, }); // Wraps the HotelCalloutAsset in an Asset and creates an AssetOperation to add the // Asset. List<AssetOperation> operations = new List<AssetOperation>(); foreach (HotelCalloutAsset asset in hotelCalloutAssets) { operations.Add(new AssetOperation { Create = new Asset { HotelCalloutAsset = asset, }, }); } // Issues the create request to create the assets. AssetServiceClient assetClient = client.GetService(Services.V10.AssetService); MutateAssetsResponse response = assetClient.MutateAssets(customerId.ToString(), operations); List<MutateAssetResult> results = response.Results.ToList(); List<string> resourceNames = new List<string>(); // Prints some information about the result. foreach (MutateAssetResult result in results) { resourceNames.Add(result.ResourceName); Console.WriteLine("Created hotel call out asset with resource name " + result.ResourceName); } return resourceNames; } /// <summary> /// Link asset to customer. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The client customer ID.</param> /// <param name="assetResourceNames">The asset resource names.</param> /// <returns>The created extension feed item's resource name.</returns> private void LinkAssetToAccount(GoogleAdsClient client, in long customerId, List<string> assetResourceNames) { // Creates a CustomerAsset link for each Asset resource name provided, then converts // this into a CustomerAssetOperation to create the Asset. List<CustomerAssetOperation> customerAssetOperations = new List<CustomerAssetOperation>(); foreach (string asset in assetResourceNames) { customerAssetOperations.Add( new CustomerAssetOperation { Create = new CustomerAsset { Asset = asset, FieldType = AssetFieldType.HotelCallout, }, }); } // Issues the create request to add the callout. CustomerAssetServiceClient customerAssetServiceClient = client.GetService(Services.V10.CustomerAssetService); MutateCustomerAssetsResponse response = customerAssetServiceClient.MutateCustomerAssets(customerId.ToString(), customerAssetOperations); foreach (MutateCustomerAssetResult result in response.Results) { Console.WriteLine("Added an account extension with resource name: " + result.ResourceName); } } } }
// // DapService.cs // // Authors: // Gabriel Burt <[email protected]> // Aaron Bockover <[email protected]> // Ruben Vermeersch <[email protected]> // // Copyright (C) 2007-2008 Novell, Inc. // // 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 Mono.Unix; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.Kernel; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Hardware; namespace Banshee.Dap { public class DapService : IExtensionService, IDelayedInitializeService, IDisposable { private Dictionary<string, DapSource> sources; private List<DeviceCommand> unhandled_device_commands; private List<TypeExtensionNode> supported_dap_types; private bool initialized; private object sync = new object (); public void Initialize () { } public void DelayedInitialize () { lock (sync) { if (initialized || ServiceManager.HardwareManager == null) return; sources = new Dictionary<string, DapSource> (); supported_dap_types = new List<TypeExtensionNode> (); AddinManager.AddExtensionNodeHandler ("/Banshee/Dap/DeviceClass", OnExtensionChanged); ServiceManager.HardwareManager.DeviceAdded += OnHardwareDeviceAdded; ServiceManager.HardwareManager.DeviceRemoved += OnHardwareDeviceRemoved; ServiceManager.HardwareManager.DeviceCommand += OnDeviceCommand; ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved; initialized = true; } } private void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { lock (sync) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add) { Log.DebugFormat ("Dap support extension loaded: {0}", node.Addin.Id); supported_dap_types.Add (node); // See if any existing devices are handled by this new DAP support foreach (IDevice device in ServiceManager.HardwareManager.GetAllDevices ()) { MapDevice (device); } } else if (args.Change == ExtensionChange.Remove) { supported_dap_types.Remove (node); Queue<DapSource> to_remove = new Queue<DapSource> (); foreach (DapSource source in sources.Values) { if (source.AddinId == node.Addin.Id) { to_remove.Enqueue (source); } } while (to_remove.Count > 0) { UnmapDevice (to_remove.Dequeue ().Device.Uuid); } } } } public void Dispose () { Scheduler.Unschedule (typeof(MapDeviceJob)); lock (sync) { if (!initialized) return; AddinManager.RemoveExtensionNodeHandler ("/Banshee/Dap/DeviceClass", OnExtensionChanged); ServiceManager.HardwareManager.DeviceAdded -= OnHardwareDeviceAdded; ServiceManager.HardwareManager.DeviceRemoved -= OnHardwareDeviceRemoved; ServiceManager.HardwareManager.DeviceCommand -= OnDeviceCommand; ServiceManager.SourceManager.SourceRemoved -= OnSourceRemoved; List<DapSource> dap_sources = new List<DapSource> (sources.Values); foreach (DapSource source in dap_sources) { UnmapDevice (source.Device.Uuid); } sources.Clear (); sources = null; supported_dap_types.Clear (); supported_dap_types = null; initialized = false; } } private DapSource FindDeviceSource (IDevice device) { foreach (TypeExtensionNode node in supported_dap_types) { try { DapSource source = (DapSource)node.CreateInstance (); source.DeviceInitialize (device); source.LoadDeviceContents (); source.AddinId = node.Addin.Id; return source; } catch (InvalidDeviceException) { } catch (InvalidCastException e) { Log.Exception ("Extension is not a DapSource as required", e); } catch (Exception e) { Log.Exception (e); } } return null; } private void MapDevice (IDevice device) { Scheduler.Schedule (new MapDeviceJob (this, device)); } private class MapDeviceJob : IJob { IDevice device; DapService service; public MapDeviceJob (DapService service, IDevice device) { this.device = device; this.service = service; } public string Uuid { get { return device.Uuid; } } public void Run () { DapSource source = null; lock (service.sync) { try { if (service.sources.ContainsKey (device.Uuid)) { return; } if (device is ICdromDevice || device is IDiscVolume) { return; } if (device is IVolume && (device as IVolume).ShouldIgnore) { return; } if (device.MediaCapabilities == null && !(device is IBlockDevice) && !(device is IVolume)) { return; } source = service.FindDeviceSource (device); if (source != null) { Log.DebugFormat ("Found DAP support ({0}) for device {1}", source.GetType ().FullName, source.Name); service.sources.Add (device.Uuid, source); } } catch (Exception e) { Log.Exception (e); } } if (source != null) { ThreadAssist.ProxyToMain (delegate { ServiceManager.SourceManager.AddSource (source); source.NotifyUser (); // If there are any queued device commands, see if they are to be // handled by this new DAP (e.g. --device-activate=file:///media/disk) try { if (service.unhandled_device_commands != null) { foreach (DeviceCommand command in service.unhandled_device_commands) { if (source.CanHandleDeviceCommand (command)) { service.HandleDeviceCommand (source, command.Action); service.unhandled_device_commands.Remove (command); if (service.unhandled_device_commands.Count == 0) { service.unhandled_device_commands = null; } break; } } } } catch (Exception e) { Log.Exception (e); } }); } } } internal void UnmapDevice (string uuid) { DapSource source = null; lock (sync) { if (sources.ContainsKey (uuid)) { Log.DebugFormat ("Unmapping DAP source ({0})", uuid); source = sources[uuid]; sources.Remove (uuid); } } if (source != null) { try { source.Dispose (); ThreadAssist.ProxyToMain (delegate { ServiceManager.SourceManager.RemoveSource (source); }); } catch (Exception e) { Log.Exception (e); } } } private void OnSourceRemoved (SourceEventArgs args) { DapSource dap_source = args.Source as DapSource; if (dap_source != null) { UnmapDevice (dap_source.Device.Uuid); } } private void OnHardwareDeviceAdded (object o, DeviceAddedArgs args) { MapDevice (args.Device); } private void OnHardwareDeviceRemoved (object o, DeviceRemovedArgs args) { UnmapDevice (args.DeviceUuid); } #region DeviceCommand Handling private void HandleDeviceCommand (DapSource source, DeviceCommandAction action) { if ((action & DeviceCommandAction.Activate) != 0) { ServiceManager.SourceManager.SetActiveSource (source); } } private void OnDeviceCommand (object o, DeviceCommand command) { lock (this) { // Check to see if we have an already mapped disc volume that should // handle this incoming command; if not, queue it for later devices foreach (DapSource source in sources.Values) { if (source.CanHandleDeviceCommand (command)) { HandleDeviceCommand (source, command.Action); return; } } if (unhandled_device_commands == null) { unhandled_device_commands = new List<DeviceCommand> (); } unhandled_device_commands.Add (command); } } #endregion string IService.ServiceName { get { return "DapService"; } } } }
using System; using System.Collections; using Foundation.Tasks; using UnityEngine; using UnityEngine.UI; namespace Foundation.Example { /// <summary> /// Example of how to use the UnityTask library /// </summary> [AddComponentMenu("Foundation/Examples/TaskTests")] public class TaskTests : MonoBehaviour { public Text Output; protected int Counter = 0; void Assert(Func<bool> compare, int c) { if (!compare.Invoke()) throw new Exception(string.Format("Test {0} Failed",c)); } public IEnumerator Start() { Output.text = string.Empty; Counter = 0; Application.logMessageReceived += Application_logMessageReceived; yield return 1; UnityTask.Run(() => { Counter++; Debug.Log("1 Run"); }); yield return new WaitForSeconds(1); Assert(() => Counter == 1,1); UnityTask.Run(Test2, "2 Run With Param"); yield return new WaitForSeconds(1); Assert(() => Counter == 2,2); UnityTask.RunCoroutine(Test3); yield return new WaitForSeconds(1); Assert(() => Counter == 3,3); var t4 =UnityTask.RunCoroutine(Test4()).ContinueWith(t => { Counter++; Debug.Log("5 Coroutine with Continue"); }); yield return StartCoroutine(t4.WaitRoutine()); Assert(() => Counter == 5,5); yield return new WaitForSeconds(1); var t5 =UnityTask.RunCoroutine(Test5).ContinueWith(t => { Counter++; Debug.Log("5 Continued"); }); yield return StartCoroutine(t5.WaitRoutine()); Assert(() => Counter == 7,7); yield return new WaitForSeconds(1); var t6 = UnityTask.Run(() => { return "6 Run with Result And Continue"; }).ContinueWith(t => { Counter++; Debug.Log(t.Result); }); yield return StartCoroutine(t6.WaitRoutine()); Assert(() => Counter == 8,8); yield return new WaitForSeconds(1); var t7 = UnityTask.Run<string, string>(Test7, "7 Run with Param and Result And Continue").ContinueWith(t => { Counter++; Debug.Log(t.Result); }); yield return StartCoroutine(t7.WaitRoutine()); yield return new WaitForSeconds(1); Assert(() => Counter == 10, 10); var t1 = UnityTask.RunCoroutine<string>(Test8); yield return StartCoroutine(t1.WaitRoutine()); Debug.Log(t1.Result); Assert(() => Counter == 11, 11); yield return new WaitForSeconds(1); var t2 = UnityTask.RunCoroutine<string>(Test9).ContinueWith(t => { Counter++; Debug.Log(t.Result); }); yield return StartCoroutine(t2.WaitRoutine()); Assert(() => Counter == 13, 13); var t12 = UnityTask.Run(() => { return "1"; }).ConvertTo<int>(task => { Debug.Log("10 ConvertTo Extension"); Counter++; return int.Parse(task.Result); }); Assert(() => t12.Result == 1, 14); Assert(() => Counter == 14, 14); Debug.Log("Success"); } void Application_logMessageReceived(string condition, string stackTrace, LogType type) { if (Output) { Output.text += (Environment.NewLine + condition); } } void Test2(string param) { Debug.Log(param); Counter++; } IEnumerator Test3() { yield return 1; Counter++; Debug.Log("3 Coroutine"); } IEnumerator Test5(UnityTask UnityTask) { yield return 1; Counter++; Debug.Log("5 Coroutine with UnityTask"); } IEnumerator Test4() { yield return 1; Debug.Log("4 Coroutine"); Counter++; } IEnumerator Wait() { yield return new WaitForSeconds(1); } string Test7(string param) { Counter++; return param; } IEnumerator Test8(UnityTask<string> UnityTask) { yield return 1; Counter++; UnityTask.Result = "8 Coroutine With Result"; } IEnumerator Test9(UnityTask<string> UnityTask) { yield return 1; UnityTask.Result = ("9 Coroutine with UnityTask State Complete"); Counter++; } void MainTest() { UnityTask.RunOnMain(() => { Debug.Log("Sleeping..."); UnityTask.Delay(2000); Debug.Log("Slept"); }); } void Background() { UnityTask.Run(() => { Debug.Log("Sleeping..."); UnityTask.Delay(2000); Debug.Log("Slept"); }); } void Routine() { UnityTask.RunCoroutine(RoutineFunction()); } IEnumerator RoutineFunction() { Debug.Log("Sleeping..."); yield return new WaitForSeconds(2); Debug.Log("Slept"); } void BackgroundToMain() { UnityTask.Run(() => { Debug.Log("Thread A Running"); var task = UnityTask.RunOnMain(() => { Debug.Log("Sleeping..."); UnityTask.Delay(2000); Debug.Log("Slept"); }); while (task.IsRunning) { Debug.Log("."); UnityTask.Delay(100); } Debug.Log("Thread A Done"); }); } void BackgroundToRotine() { UnityTask.Run(() => { Debug.Log("Thread A Running"); var task = UnityTask.RunCoroutine(RoutineFunction()); while (task.IsRunning) { Debug.Log("."); UnityTask.Delay(500); } Debug.Log("Thread A Done"); }); } void BackgroundToBackground() { UnityTask.Run(() => { Debug.Log("1 Sleeping..."); UnityTask.Run(() => { Debug.Log("2 Sleeping..."); UnityTask.Delay(2000); Debug.Log("2 Slept"); }); UnityTask.Delay(2000); Debug.Log("1 Slept"); }); } void BackgroundToBackgroundException() { var task1 = UnityTask.Run(() => { Debug.Log("1 Go"); var task2 = UnityTask.Run(() => { UnityTask.Delay(100); Debug.Log("2 Go"); throw new Exception("2 Fail"); }); task2.Wait(); if (task2.IsFaulted) throw task2.Exception; }); task1.Wait(); Debug.Log(task1.Status + " " + task1.Exception.Message); } void BackgroundException() { var task1 = UnityTask.Run(() => { throw new Exception("Hello World"); }); task1.Wait(); Debug.Log(task1.Status + " " + task1.Exception.Message); } void CoroutineUnityTaskState() { UnityTask.RunCoroutine<string>(CoroutineUnityTaskStateAsync).ContinueWith(o => Debug.Log(o.Result)); } IEnumerator CoroutineUnityTaskStateAsync(UnityTask<string> UnityTask) { yield return 1; UnityTask.Result = "Hello World"; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace GLib.Options { [ TypeConverter(typeof(ExpandableObjectConverter)) ] [ToolboxItem(true)] public partial class OptionsPanel : UserControl { protected OptionsForm _OptionsForm; private String _Path; private String _DisplayName; private bool _OptionsUpdated; [Browsable(true)] [Description("This event is fired when the panel options are changed")] public event EventHandler OptionsChanged; #region Properties /// <summary> /// Gets the options form. /// </summary> /// <value>The options form.</value> [Browsable(false)] public OptionsForm OptionsForm { get { return _OptionsForm; } } [Category("Options Form")] [Description("The path of the OptionsPanel (determines the location in the Category TreeView in the parent OptionsForm form)")] public String CategoryPath { get { return _Path; } set { _Path = value; } } [Category("Options Form")] [Description("The name displayed for this panel in the Category TreeView in the parent OptionsForm form")] public String DisplayName { get { return _DisplayName; } set { _DisplayName = value; } } /// <summary> /// Gets or sets a value indicating whether application must restart. /// </summary> /// <value> /// <c>true</c> if application must restart to apply options otherwise, <c>false</c>. /// </value> [Browsable(false)] public bool ApplicationMustRestart { get { if (OptionsForm != null) { return OptionsForm.ApplicationMustRestart; } else { return false; } } set { if (OptionsForm != null) { OptionsForm.ApplicationMustRestart = value; } } } /// <summary> /// Gets or sets a value indicating whether [options changed]. /// </summary> /// <value><c>true</c> if [options changed]; otherwise, <c>false</c>.</value> [Browsable(false)] public bool OptionsUpdated { get { return _OptionsUpdated; } set { _OptionsUpdated = value; if (_OptionsUpdated) { OnOptionsChanged(); } } } #endregion public OptionsPanel() { InitializeComponent(); } virtual public void PanelAdded(OptionsForm optf) { _OptionsForm = optf; InitPanelForControl(this); _OptionsForm.OptionsSaving += new EventHandler(OptionsSaving); _OptionsForm.OptionsSaved += new EventHandler(OptionsSaved); _OptionsForm.ResetForm += new EventHandler(ResetForm); } protected void SetOption(String OptionName, Object value) { _OptionsForm.AppSettings[OptionName] = value; OptionsUpdated = true; } protected void OnOptionsChanged() { if (OptionsChanged != null) { OptionsChanged(this, EventArgs.Empty); } } protected void OptionsSaving(object sender, EventArgs e) { } protected void OptionsSaved(object sender, EventArgs e) { ReloadValues(this); } protected virtual void ResetForm(object sender, EventArgs e) { ReloadValues(this); } private void ReloadValues(Control ctrl) { for (int i = 0; i < ctrl.Controls.Count; i++) { Control ctrl2 = ctrl.Controls[i]; for (int l = 0; l < ctrl2.DataBindings.Count; l++) { Binding bind = ctrl2.DataBindings[l]; bind.ReadValue(); } ReloadValues(ctrl2); } } private void InitPanelForControl(Control ctrl) { for (int i = 0; i < ctrl.Controls.Count; i++) { Control ctrl2 = ctrl.Controls[i]; for (int l = 0; l < ctrl2.DataBindings.Count; l++) { Binding bind = ctrl2.DataBindings[l]; String prop = bind.BindingMemberInfo.BindingMember; try { Object value = _OptionsForm.AppSettings[prop]; if (value != null) { bind.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged; bind.ControlUpdateMode = ControlUpdateMode.Never; System.Configuration.SettingsProperty sett = new System.Configuration.SettingsProperty(prop); sett.DefaultValue = value; _OptionsForm.Settings.Add(sett); } } catch { } } InitPanelForControl(ctrl2); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The core assembly for the DotSpatial 6.0 distribution. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is DotSpatial.dll // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/12/2009 12:02:12 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// TabColorDialog /// </summary> public class TabColorDialog : Form { #region Events /// <summary> /// Occurs whenever the apply changes button is clicked, or else when the ok button is clicked. /// </summary> public event EventHandler ChangesApplied; #endregion private Button btnApply; private Button btnCancel; private Button cmdOk; private Panel panel1; private TabColorControl tabColorControl1; #region Private Variables /// <summary> /// Required designer variable. /// </summary> private IContainer components = null; #endregion #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> private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(TabColorDialog)); this.panel1 = new Panel(); this.btnApply = new Button(); this.btnCancel = new Button(); this.cmdOk = new Button(); this.tabColorControl1 = new TabColorControl(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.AccessibleDescription = null; this.panel1.AccessibleName = null; resources.ApplyResources(this.panel1, "panel1"); this.panel1.BackgroundImage = null; this.panel1.Controls.Add(this.btnApply); this.panel1.Controls.Add(this.btnCancel); this.panel1.Controls.Add(this.cmdOk); this.panel1.Font = null; this.panel1.Name = "panel1"; // // btnApply // this.btnApply.AccessibleDescription = null; this.btnApply.AccessibleName = null; resources.ApplyResources(this.btnApply, "btnApply"); this.btnApply.BackgroundImage = null; this.btnApply.Font = null; this.btnApply.Name = "btnApply"; this.btnApply.UseVisualStyleBackColor = true; this.btnApply.Click += new EventHandler(this.btnApply_Click); // // btnCancel // this.btnCancel.AccessibleDescription = null; this.btnCancel.AccessibleName = null; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.BackgroundImage = null; //this.btnCancel.DialogResult = DialogResult.Cancel; this.btnCancel.Font = null; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new EventHandler(this.btnCancel_Click); // // cmdOk // this.cmdOk.AccessibleDescription = null; this.cmdOk.AccessibleName = null; resources.ApplyResources(this.cmdOk, "cmdOk"); this.cmdOk.BackgroundImage = null; //this.cmdOk.DialogResult = DialogResult.OK; this.cmdOk.Font = null; this.cmdOk.Name = "cmdOk"; this.cmdOk.UseVisualStyleBackColor = true; this.cmdOk.Click += new EventHandler(this.cmdOk_Click); // // tabColorControl1 // this.tabColorControl1.AccessibleDescription = null; this.tabColorControl1.AccessibleName = null; resources.ApplyResources(this.tabColorControl1, "tabColorControl1"); this.tabColorControl1.BackgroundImage = null; this.tabColorControl1.EndColor = Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.tabColorControl1.Font = null; this.tabColorControl1.HueShift = 0; this.tabColorControl1.Name = "tabColorControl1"; this.tabColorControl1.StartColor = Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.tabColorControl1.UseRangeChecked = true; // // TabColorDialog // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.BackgroundImage = null; this.Controls.Add(this.tabColorControl1); this.Controls.Add(this.panel1); this.Font = null; this.Icon = null; this.Name = "TabColorDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Constructors /// <summary> /// Creates a new instance of CollectionPropertyGrid /// </summary> public TabColorDialog() { InitializeComponent(); } #endregion #region Methods #endregion #region Properties /// <summary> /// Gets or sets the start color for this control /// </summary> public Color StartColor { get { return tabColorControl1.StartColor; } set { tabColorControl1.StartColor = value; } } /// <summary> /// Gets or sets the end color for this control. /// </summary> public Color EndColor { get { return tabColorControl1.EndColor; } set { tabColorControl1.EndColor = value; } } #endregion #region Events #endregion #region Event Handlers private void btnApply_Click(object sender, EventArgs e) { OnApplyChanges(); } private void btnCancel_Click(object sender, EventArgs e) { Close(); } private void cmdOk_Click(object sender, EventArgs e) { OnApplyChanges(); Close(); } #endregion #region Protected Methods /// <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); } /// <summary> /// Fires the ChangesApplied event /// </summary> protected virtual void OnApplyChanges() { if (ChangesApplied != null) ChangesApplied(this, EventArgs.Empty); } #endregion } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.Commands.Internal.Format { internal sealed class ComplexViewGenerator : ViewGenerator { internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); this.inputParameters = parameters; } internal override FormatStartData GenerateStartData(PSObject so) { FormatStartData startFormat = base.GenerateStartData(so); startFormat.shapeInfo = new ComplexViewHeaderInfo(); return startFormat; } internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLimit) { FormatEntryData fed = new FormatEntryData(); if (this.dataBaseInfo.view != null) fed.formatEntryInfo = GenerateComplexViewEntryFromDataBaseInfo(so, enumerationLimit); else fed.formatEntryInfo = GenerateComplexViewEntryFromProperties(so, enumerationLimit); return fed; } private ComplexViewEntry GenerateComplexViewEntryFromProperties(PSObject so, int enumerationLimit) { ComplexViewObjectBrowser browser = new ComplexViewObjectBrowser(this.ErrorManager, this.expressionFactory, enumerationLimit); return browser.GenerateView(so, this.inputParameters); } private ComplexViewEntry GenerateComplexViewEntryFromDataBaseInfo(PSObject so, int enumerationLimit) { // execute on the format directive ComplexViewEntry cve = new ComplexViewEntry(); // NOTE: we set a max depth to protect ourselves from infinite loops const int maxTreeDepth = 50; ComplexControlGenerator controlGenerator = new ComplexControlGenerator(this.dataBaseInfo.db, this.dataBaseInfo.view.loadingInfo, this.expressionFactory, this.dataBaseInfo.view.formatControlDefinitionHolder.controlDefinitionList, this.ErrorManager, enumerationLimit, this.errorContext); controlGenerator.GenerateFormatEntries(maxTreeDepth, this.dataBaseInfo.view.mainControl, so, cve.formatValueList); return cve; } } /// <summary> /// class to process a complex control directive and generate /// the corresponding formatting tokens /// </summary> internal sealed class ComplexControlGenerator { internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, MshExpressionFactory expressionFactory, List<ControlDefinition> controlDefinitionList, FormatErrorManager resultErrorManager, int enumerationLimit, TerminatingErrorContext errorContext) { _db = dataBase; _loadingInfo = loadingInfo; _expressionFactory = expressionFactory; _controlDefinitionList = controlDefinitionList; _errorManager = resultErrorManager; _enumerationLimit = enumerationLimit; _errorContext = errorContext; } internal void GenerateFormatEntries(int maxTreeDepth, ControlBase control, PSObject so, List<FormatValue> formatValueList) { if (control == null) { throw PSTraceSource.NewArgumentNullException("control"); } ExecuteFormatControl(new TraversalInfo(0, maxTreeDepth), control, so, formatValueList); } private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, PSObject so, List<FormatValue> formatValueList) { // we are looking for a complex control to execute ComplexControlBody complexBody = null; // we might have a reference ControlReference controlReference = control as ControlReference; if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody)) { // retrieve the reference complexBody = DisplayDataQuery.ResolveControlReference( _db, _controlDefinitionList, controlReference) as ComplexControlBody; } else { // try as an in line control complexBody = control as ComplexControlBody; } // finally, execute the control body if (complexBody != null) { // we have an inline control, just execute it ExecuteFormatControlBody(level, so, complexBody, formatValueList); return true; } return false; } private void ExecuteFormatControlBody(TraversalInfo level, PSObject so, ComplexControlBody complexBody, List<FormatValue> formatValueList) { ComplexControlEntryDefinition activeControlEntryDefinition = GetActiveComplexControlEntryDefinition(complexBody, so); ExecuteFormatTokenList(level, so, activeControlEntryDefinition.itemDefinition.formatTokenList, formatValueList); } private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(ComplexControlBody complexBody, PSObject so) { // see if we have an override that matches var typeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(_expressionFactory, _db, typeNames); foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { return x; } } if (match.BestMatch != null) { return match.BestMatch as ComplexControlEntryDefinition; } else { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { match = new TypeMatch(_expressionFactory, _db, typesWithoutPrefix); foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { return x; } } if (match.BestMatch != null) { return match.BestMatch as ComplexControlEntryDefinition; } } // we do not have any override, use default return complexBody.defaultEntry; } } private void ExecuteFormatTokenList(TraversalInfo level, PSObject so, List<FormatToken> formatTokenList, List<FormatValue> formatValueList) { if (so == null) { throw PSTraceSource.NewArgumentNullException("so"); } // guard against infinite loop if (level.Level == level.MaxDepth) { return; } FormatEntry fe = new FormatEntry(); formatValueList.Add(fe); #region foreach loop foreach (FormatToken t in formatTokenList) { TextToken tt = t as TextToken; if (tt != null) { FormatTextField ftf = new FormatTextField(); ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); fe.formatValueList.Add(ftf); continue; } var newline = t as NewLineToken; if (newline != null) { for (int i = 0; i < newline.count; i++) { fe.formatValueList.Add(new FormatNewLine()); } continue; } FrameToken ft = t as FrameToken; if (ft != null) { // instantiate a new entry and attach a frame info object FormatEntry feFrame = new FormatEntry(); feFrame.frameInfo = new FrameInfo(); // add the frame info feFrame.frameInfo.firstLine = ft.frameInfoDefinition.firstLine; feFrame.frameInfo.leftIndentation = ft.frameInfoDefinition.leftIndentation; feFrame.frameInfo.rightIndentation = ft.frameInfoDefinition.rightIndentation; // execute the list inside the frame ExecuteFormatTokenList(level, so, ft.itemDefinition.formatTokenList, feFrame.formatValueList); // add the frame computation results to the current format entry fe.formatValueList.Add(feFrame); continue; } #region CompoundPropertyToken CompoundPropertyToken cpt = t as CompoundPropertyToken; if (cpt != null) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { // token not active, skip it continue; } // get the property from the object object val = null; // if no expression was specified, just use the // object itself if (cpt.expression == null || string.IsNullOrEmpty(cpt.expression.expressionValue)) { val = so; } else { MshExpression ex = _expressionFactory.CreateFromExpressionToken(cpt.expression, _loadingInfo); List<MshExpressionResult> resultList = ex.GetValues(so); if (resultList.Count > 0) { val = resultList[0].Result; if (resultList[0].Exception != null) { _errorManager.LogMshExpressionFailedResult(resultList[0], so); } } } // if the token is has a formatting string, it's a leaf node, // do the formatting and we will be done if (cpt.control == null || cpt.control is FieldControlBody) { // Since it is a leaf node we just consider it an empty string and go // on with formatting if (val == null) { val = ""; } FieldFormattingDirective fieldFormattingDirective = null; StringFormatError formatErrorObject = null; if (cpt.control != null) { fieldFormattingDirective = ((FieldControlBody)cpt.control).fieldFormattingDirective; if (fieldFormattingDirective != null && _errorManager.DisplayFormatErrorString) { formatErrorObject = new StringFormatError(); } } IEnumerable e = PSObjectHelper.GetEnumerable(val); FormatPropertyField fpf = new FormatPropertyField(); if (cpt.enumerateCollection && e != null) { foreach (object x in e) { if (x == null) { // nothing to process continue; } fpf = new FormatPropertyField(); fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, x, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } } else { fpf = new FormatPropertyField(); fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, val, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } if (formatErrorObject != null && formatErrorObject.exception != null) { _errorManager.LogStringFormatError(formatErrorObject); fpf.propertyValue = _errorManager.FormatErrorString; } } else { // An empty result that is not a leaf node should not be expanded if (val == null) { continue; } IEnumerable e = PSObjectHelper.GetEnumerable(val); if (cpt.enumerateCollection && e != null) { foreach (object x in e) { if (x == null) { // nothing to process continue; } // proceed with the recursion ExecuteFormatControl(level.NextLevel, cpt.control, PSObject.AsPSObject(x), fe.formatValueList); } } else { // proceed with the recursion ExecuteFormatControl(level.NextLevel, cpt.control, PSObjectHelper.AsPSObject(val), fe.formatValueList); } } } #endregion CompoundPropertyToken } #endregion foreach loop } private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken) { if (conditionToken == null) return true; MshExpression ex = _expressionFactory.CreateFromExpressionToken(conditionToken, _loadingInfo); MshExpressionResult expressionResult; bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult); if (expressionResult != null && expressionResult.Exception != null) { _errorManager.LogMshExpressionFailedResult(expressionResult, so); } return retVal; } private TypeInfoDataBase _db; private DatabaseLoadingInfo _loadingInfo; private MshExpressionFactory _expressionFactory; private List<ControlDefinition> _controlDefinitionList; private FormatErrorManager _errorManager; private TerminatingErrorContext _errorContext; private int _enumerationLimit; } internal class TraversalInfo { internal TraversalInfo(int level, int maxDepth) { _level = level; _maxDepth = maxDepth; } internal int Level { get { return _level; } } internal int MaxDepth { get { return _maxDepth; } } internal TraversalInfo NextLevel { get { return new TraversalInfo(_level + 1, _maxDepth); } } private int _level; private int _maxDepth; } /// <summary> /// class to generate a complex view from properties /// </summary> internal sealed class ComplexViewObjectBrowser { internal ComplexViewObjectBrowser(FormatErrorManager resultErrorManager, MshExpressionFactory mshExpressionFactory, int enumerationLimit) { _errorManager = resultErrorManager; _expressionFactory = mshExpressionFactory; _enumerationLimit = enumerationLimit; } /// <summary> /// given an object, generate a tree-like view /// of the object /// </summary> /// <param name="so">object to process</param> /// <param name="inputParameters">parameters from the command line</param> /// <returns>complex view entry to send to the output command</returns> internal ComplexViewEntry GenerateView(PSObject so, FormattingCommandLineParameters inputParameters) { _complexSpecificParameters = (ComplexSpecificParameters)inputParameters.shapeParameters; int maxDepth = _complexSpecificParameters.maxDepth; TraversalInfo level = new TraversalInfo(0, maxDepth); List<MshParameter> mshParameterList = null; if (inputParameters != null) mshParameterList = inputParameters.mshParameterList; // create a top level entry as root of the tree ComplexViewEntry cve = new ComplexViewEntry(); var typeNames = so.InternalTypeNames; if (TreatAsScalarType(typeNames)) { FormatEntry fe = new FormatEntry(); cve.formatValueList.Add(fe); DisplayRawObject(so, fe.formatValueList); } else { // check if the top level object is an enumeration IEnumerable e = PSObjectHelper.GetEnumerable(so); if (e != null) { // let's start the traversal with an enumeration FormatEntry fe = new FormatEntry(); cve.formatValueList.Add(fe); DisplayEnumeration(e, level, fe.formatValueList); } else { // let's start the traversal with a traversal on properties DisplayObject(so, level, mshParameterList, cve.formatValueList); } } return cve; } private void DisplayRawObject(PSObject so, List<FormatValue> formatValueList) { FormatPropertyField fpf = new FormatPropertyField(); StringFormatError formatErrorObject = null; if (_errorManager.DisplayFormatErrorString) { // we send a format error object down to the formatting calls // only if we want to show the formatting error strings formatErrorObject = new StringFormatError(); } fpf.propertyValue = PSObjectHelper.SmartToString(so, _expressionFactory, _enumerationLimit, formatErrorObject); if (formatErrorObject != null && formatErrorObject.exception != null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayFormatErrorString) { fpf.propertyValue = _errorManager.FormatErrorString; } } formatValueList.Add(fpf); formatValueList.Add(new FormatNewLine()); } /// <summary> /// recursive call to display an object /// </summary> /// <param name="so">object to display</param> /// <param name="currentLevel">current level in the traversal</param> /// <param name="parameterList"> list of parameters from the command line</param> /// <param name="formatValueList">list of format tokens to add to</param> private void DisplayObject(PSObject so, TraversalInfo currentLevel, List<MshParameter> parameterList, List<FormatValue> formatValueList) { // resolve the names of the properties List<MshResolvedExpressionParameterAssociation> activeAssociationList = AssociationManager.SetupActiveProperties(parameterList, so, _expressionFactory); // create a format entry FormatEntry fe = new FormatEntry(); formatValueList.Add(fe); // add the display name of the object string objectDisplayName = GetObjectDisplayName(so); if (objectDisplayName != null) objectDisplayName = "class " + objectDisplayName; AddPrologue(fe.formatValueList, "{", objectDisplayName); ProcessActiveAssociationList(so, currentLevel, activeAssociationList, AddIndentationLevel(fe.formatValueList)); AddEpilogue(fe.formatValueList, "}"); } private void ProcessActiveAssociationList(PSObject so, TraversalInfo currentLevel, List<MshResolvedExpressionParameterAssociation> activeAssociationList, List<FormatValue> formatValueList) { foreach (MshResolvedExpressionParameterAssociation a in activeAssociationList) { FormatTextField ftf = new FormatTextField(); ftf.text = a.ResolvedExpression.ToString() + " = "; formatValueList.Add(ftf); // compute the value of the entry List<MshExpressionResult> resList = a.ResolvedExpression.GetValues(so); object val = null; if (resList.Count >= 1) { MshExpressionResult result = resList[0]; if (result.Exception != null) { _errorManager.LogMshExpressionFailedResult(result, so); if (_errorManager.DisplayErrorStrings) { val = _errorManager.ErrorString; } else { val = ""; } } else { val = result.Result; } } // extract the optional max depth TraversalInfo level = currentLevel; if (a.OriginatingParameter != null) { object maxDepthKey = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.DepthEntryKey); if (maxDepthKey != AutomationNull.Value) { int parameterMaxDept = (int)maxDepthKey; level = new TraversalInfo(currentLevel.Level, parameterMaxDept); } } IEnumerable e = null; if (val != null || (level.Level >= level.MaxDepth)) e = PSObjectHelper.GetEnumerable(val); if (e != null) { formatValueList.Add(new FormatNewLine()); DisplayEnumeration(e, level.NextLevel, AddIndentationLevel(formatValueList)); } else if (val == null || TreatAsLeafNode(val, level)) { DisplayLeaf(val, formatValueList); } else { formatValueList.Add(new FormatNewLine()); // we need to go one more level down DisplayObject(PSObject.AsPSObject(val), level.NextLevel, null, AddIndentationLevel(formatValueList)); } } // for each } /// <summary> /// recursive call to display an object /// </summary> /// <param name="e">enumeration to display</param> /// <param name="level">current level in the traversal</param> /// <param name="formatValueList">list of format tokens to add to</param> private void DisplayEnumeration(IEnumerable e, TraversalInfo level, List<FormatValue> formatValueList) { AddPrologue(formatValueList, "[", null); DisplayEnumerationInner(e, level, AddIndentationLevel(formatValueList)); AddEpilogue(formatValueList, "]"); formatValueList.Add(new FormatNewLine()); } private void DisplayEnumerationInner(IEnumerable e, TraversalInfo level, List<FormatValue> formatValueList) { int enumCount = 0; foreach (object x in e) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (_enumerationLimit >= 0) { if (_enumerationLimit == enumCount) { DisplayLeaf(PSObjectHelper.ellipses, formatValueList); break; } enumCount++; } if (TreatAsLeafNode(x, level)) { DisplayLeaf(x, formatValueList); } else { // check if the top level object is an enumeration IEnumerable e1 = PSObjectHelper.GetEnumerable(x); if (e1 != null) { formatValueList.Add(new FormatNewLine()); DisplayEnumeration(e1, level.NextLevel, AddIndentationLevel(formatValueList)); } else { DisplayObject(PSObjectHelper.AsPSObject(x), level.NextLevel, null, formatValueList); } } } } /// <summary> /// display a leaf value /// </summary> /// <param name="val">object to display</param> /// <param name="formatValueList">list of format tokens to add to</param> private void DisplayLeaf(object val, List<FormatValue> formatValueList) { FormatPropertyField fpf = new FormatPropertyField(); fpf.propertyValue = PSObjectHelper.FormatField(null, PSObjectHelper.AsPSObject(val), _enumerationLimit, null, _expressionFactory); formatValueList.Add(fpf); formatValueList.Add(new FormatNewLine()); } /// <summary> /// determine if we have to stop the expansion /// </summary> /// <param name="val">object to verify</param> /// <param name="level">current level of recursion</param> /// <returns></returns> private static bool TreatAsLeafNode(object val, TraversalInfo level) { if (level.Level >= level.MaxDepth || val == null) return true; return TreatAsScalarType(PSObject.GetTypeNames(val)); } /// <summary> /// treat as scalar check /// </summary> /// <param name="typeNames">name of the type to check</param> /// <returns>true if it has to be treated as a scalar</returns> private static bool TreatAsScalarType(Collection<string> typeNames) { return DefaultScalarTypes.IsTypeInList(typeNames); } private string GetObjectDisplayName(PSObject so) { if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.none) return null; var typeNames = so.InternalTypeNames; if (typeNames.Count == 0) { return "PSObject"; } if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.shortName) { // get the last token in the full name string[] arr = typeNames[0].Split(Utils.Separators.Dot); if (arr.Length > 0) return arr[arr.Length - 1]; } return typeNames[0]; } private static void AddPrologue(List<FormatValue> formatValueList, string openTag, string label) { if (label != null) { FormatTextField ftfLabel = new FormatTextField(); ftfLabel.text = label; formatValueList.Add(ftfLabel); formatValueList.Add(new FormatNewLine()); } FormatTextField ftf = new FormatTextField(); ftf.text = openTag; formatValueList.Add(ftf); formatValueList.Add(new FormatNewLine()); } private static void AddEpilogue(List<FormatValue> formatValueList, string closeTag) { FormatTextField ftf = new FormatTextField(); ftf.text = closeTag; formatValueList.Add(ftf); formatValueList.Add(new FormatNewLine()); } private List<FormatValue> AddIndentationLevel(List<FormatValue> formatValueList) { FormatEntry feFrame = new FormatEntry(); feFrame.frameInfo = new FrameInfo(); // add the frame info feFrame.frameInfo.firstLine = 0; feFrame.frameInfo.leftIndentation = _indentationStep; feFrame.frameInfo.rightIndentation = 0; formatValueList.Add(feFrame); return feFrame.formatValueList; } private ComplexSpecificParameters _complexSpecificParameters; /// <summary> /// identation added to each level in the recursion /// </summary> private int _indentationStep = 2; private FormatErrorManager _errorManager; private MshExpressionFactory _expressionFactory; private int _enumerationLimit; } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using ASC.Common.Logging; using ASC.MessagingSystem.DbSender; namespace ASC.MessagingSystem { public static class MessageService { private static readonly ILog log = LogManager.GetLogger("ASC.Messaging"); private static readonly IMessageSender sender; static MessageService() { if (ConfigurationManagerExtension.AppSettings["messaging.enabled"] != "true") { return; } sender = new DbMessageSender(); } #region HttpRequest public static void Send(HttpRequest request, MessageAction action) { SendRequestMessage(request, null, action, null); } public static void Send(HttpRequest request, MessageAction action, string d1) { SendRequestMessage(request, null, action, null, d1); } public static void Send(HttpRequest request, MessageAction action, string d1, string d2) { SendRequestMessage(request, null, action, null, d1, d2); } public static void Send(HttpRequest request, MessageAction action, string d1, string d2, string d3) { SendRequestMessage(request, null, action, null, d1, d2, d3); } public static void Send(HttpRequest request, MessageAction action, string d1, string d2, string d3, string d4) { SendRequestMessage(request, null, action, null, d1, d2, d3, d4); } public static void Send(HttpRequest request, MessageAction action, IEnumerable<string> d1, string d2) { SendRequestMessage(request, null, action, null, string.Join(", ", d1), d2); } public static void Send(HttpRequest request, MessageAction action, string d1, IEnumerable<string> d2) { SendRequestMessage(request, null, action, null, d1, string.Join(", ", d2)); } public static void Send(HttpRequest request, MessageAction action, string d1, string d2, IEnumerable<string> d3) { SendRequestMessage(request, null, action, null, d1, d2, string.Join(", ", d3)); } public static void Send(HttpRequest request, MessageAction action, IEnumerable<string> d1) { SendRequestMessage(request, null, action, null, string.Join(", ", d1)); } public static void Send(HttpRequest request, string loginName, MessageAction action) { SendRequestMessage(request, loginName, action, null); } public static void Send(HttpRequest request, string loginName, MessageAction action, string d1) { SendRequestMessage(request, loginName, action, null, d1); } #endregion #region HttpRequest & Target public static void Send(HttpRequest request, MessageAction action, MessageTarget target) { SendRequestMessage(request, null, action, target); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1) { SendRequestMessage(request, null, action, target, d1); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1, string d2) { SendRequestMessage(request, null, action, target, d1, d2); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1, string d2, string d3) { SendRequestMessage(request, null, action, target, d1, d2, d3); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1, string d2, string d3, string d4) { SendRequestMessage(request, null, action, target, d1, d2, d3, d4); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, IEnumerable<string> d1, string d2) { SendRequestMessage(request, null, action, target, string.Join(", ", d1), d2); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1, IEnumerable<string> d2) { SendRequestMessage(request, null, action, target, d1, string.Join(", ", d2)); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, string d1, string d2, IEnumerable<string> d3) { SendRequestMessage(request, null, action, target, d1, d2, string.Join(", ", d3)); } public static void Send(HttpRequest request, MessageAction action, MessageTarget target, IEnumerable<string> d1) { SendRequestMessage(request, null, action, target, string.Join(", ", d1)); } public static void Send(HttpRequest request, string loginName, MessageAction action, MessageTarget target) { SendRequestMessage(request, loginName, action, target); } public static void Send(HttpRequest request, string loginName, MessageAction action, MessageTarget target, string d1) { SendRequestMessage(request, loginName, action, target, d1); } #endregion private static void SendRequestMessage(HttpRequest request, string loginName, MessageAction action, MessageTarget target, params string[] description) { if (sender == null) return; if (request == null) { log.Debug(string.Format("Empty Http Request for \"{0}\" type of event", action)); return; } var message = MessageFactory.Create(request, loginName, action, target, description); if (!MessagePolicy.Check(message)) return; sender.Send(message); } #region HttpHeaders public static void Send(MessageUserData userData, Dictionary<string, string> httpHeaders, MessageAction action) { SendHeadersMessage(userData, httpHeaders, action, null); } public static void Send(Dictionary<string, string> httpHeaders, MessageAction action) { SendHeadersMessage(null, httpHeaders, action, null); } public static void Send(Dictionary<string, string> httpHeaders, MessageAction action, string d1) { SendHeadersMessage(null, httpHeaders, action, null, d1); } public static void Send(Dictionary<string, string> httpHeaders, MessageAction action, IEnumerable<string> d1) { SendHeadersMessage(null, httpHeaders, action, null, d1 != null ? d1.ToArray() : null); } public static void Send(MessageUserData userData, Dictionary<string, string> httpHeaders, MessageAction action, MessageTarget target) { SendHeadersMessage(userData, httpHeaders, action, target); } #endregion #region HttpHeaders & Target public static void Send(Dictionary<string, string> httpHeaders, MessageAction action, MessageTarget target) { SendHeadersMessage(null, httpHeaders, action, target); } public static void Send(Dictionary<string, string> httpHeaders, MessageAction action, MessageTarget target, string d1) { SendHeadersMessage(null, httpHeaders, action, target, d1); } public static void Send(Dictionary<string, string> httpHeaders, MessageAction action, MessageTarget target, IEnumerable<string> d1) { SendHeadersMessage(null, httpHeaders, action, target, d1 != null ? d1.ToArray() : null); } #endregion private static void SendHeadersMessage(MessageUserData userData, Dictionary<string, string> httpHeaders, MessageAction action, MessageTarget target, params string[] description) { if (sender == null) return; var message = MessageFactory.Create(userData, httpHeaders, action, target, description); if (!MessagePolicy.Check(message)) return; sender.Send(message); } #region Initiator public static void Send(HttpRequest request, MessageInitiator initiator, MessageAction action, params string[] description) { SendInitiatorMessage(request, initiator.ToString(), action, null, description); } public static void Send(MessageInitiator initiator, MessageAction action, params string[] description) { SendInitiatorMessage(null, initiator.ToString(), action, null, description); } #endregion #region Initiator & Target public static void Send(HttpRequest request, MessageInitiator initiator, MessageAction action, MessageTarget target, params string[] description) { SendInitiatorMessage(request, initiator.ToString(), action, target, description); } public static void Send(MessageInitiator initiator, MessageAction action, MessageTarget target, params string[] description) { SendInitiatorMessage(null, initiator.ToString(), action, target, description); } #endregion private static void SendInitiatorMessage(HttpRequest request, string initiator, MessageAction action, MessageTarget target, params string[] description) { if (sender == null) return; var message = MessageFactory.Create(request, initiator, action, target, description); if (!MessagePolicy.Check(message)) return; sender.Send(message); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reflection; using Avalonia.Collections; using Avalonia.Controls; using Avalonia.Controls.Metadata; using Avalonia.Markup.Xaml.MarkupExtensions; using Avalonia.Styling; using Avalonia.VisualTree; namespace Avalonia.Diagnostics.ViewModels { internal class ControlDetailsViewModel : ViewModelBase, IDisposable { private readonly IAvaloniaObject _avaloniaObject; private IDictionary<object, List<PropertyViewModel>>? _propertyIndex; private PropertyViewModel? _selectedProperty; private DataGridCollectionView? _propertiesView; private bool _snapshotStyles; private bool _showInactiveStyles; private string? _styleStatus; private object? _selectedEntity; private readonly Stack<(string Name,object Entry)> _selectedEntitiesStack = new(); private string? _selectedEntityName; private string? _selectedEntityType; private bool _showImplementedInterfaces; public ControlDetailsViewModel(TreePageViewModel treePage, IAvaloniaObject avaloniaObject) { _avaloniaObject = avaloniaObject; TreePage = treePage; Layout = avaloniaObject is IVisual ? new ControlLayoutViewModel((IVisual)avaloniaObject) : default; NavigateToProperty(_avaloniaObject, (_avaloniaObject as IControl)?.Name ?? _avaloniaObject.ToString()); AppliedStyles = new ObservableCollection<StyleViewModel>(); PseudoClasses = new ObservableCollection<PseudoClassViewModel>(); if (avaloniaObject is StyledElement styledElement) { styledElement.Classes.CollectionChanged += OnClassesChanged; var pseudoClassAttributes = styledElement.GetType().GetCustomAttributes<PseudoClassesAttribute>(true); foreach (var classAttribute in pseudoClassAttributes) { foreach (var className in classAttribute.PseudoClasses) { PseudoClasses.Add(new PseudoClassViewModel(className, styledElement)); } } var styleDiagnostics = styledElement.GetStyleDiagnostics(); foreach (var appliedStyle in styleDiagnostics.AppliedStyles) { var styleSource = appliedStyle.Source; var setters = new List<SetterViewModel>(); if (styleSource is Style style) { foreach (var setter in style.Setters) { if (setter is Setter regularSetter && regularSetter.Property != null) { var setterValue = regularSetter.Value; var resourceInfo = GetResourceInfo(setterValue); SetterViewModel setterVm; if (resourceInfo.HasValue) { var resourceKey = resourceInfo.Value.resourceKey; var resourceValue = styledElement.FindResource(resourceKey); setterVm = new ResourceSetterViewModel(regularSetter.Property, resourceKey, resourceValue, resourceInfo.Value.isDynamic); } else { setterVm = new SetterViewModel(regularSetter.Property, setterValue); } setters.Add(setterVm); } } AppliedStyles.Add(new StyleViewModel(appliedStyle, style.Selector?.ToString() ?? "No selector", setters)); } } UpdateStyles(); } } private (object resourceKey, bool isDynamic)? GetResourceInfo(object? value) { if (value is StaticResourceExtension staticResource) { return (staticResource.ResourceKey, false); } else if (value is DynamicResourceExtension dynamicResource && dynamicResource.ResourceKey != null) { return (dynamicResource.ResourceKey, true); } return null; } public TreePageViewModel TreePage { get; } public DataGridCollectionView? PropertiesView { get => _propertiesView; private set => RaiseAndSetIfChanged(ref _propertiesView, value); } public ObservableCollection<StyleViewModel> AppliedStyles { get; } public ObservableCollection<PseudoClassViewModel> PseudoClasses { get; } public object? SelectedEntity { get => _selectedEntity; set { RaiseAndSetIfChanged(ref _selectedEntity, value); } } public string? SelectedEntityName { get => _selectedEntityName; set { RaiseAndSetIfChanged(ref _selectedEntityName, value); } } public string? SelectedEntityType { get => _selectedEntityType; set { RaiseAndSetIfChanged(ref _selectedEntityType, value); } } public PropertyViewModel? SelectedProperty { get => _selectedProperty; set => RaiseAndSetIfChanged(ref _selectedProperty, value); } public bool SnapshotStyles { get => _snapshotStyles; set => RaiseAndSetIfChanged(ref _snapshotStyles, value); } public bool ShowInactiveStyles { get => _showInactiveStyles; set => RaiseAndSetIfChanged(ref _showInactiveStyles, value); } public string? StyleStatus { get => _styleStatus; set => RaiseAndSetIfChanged(ref _styleStatus, value); } public ControlLayoutViewModel? Layout { get; } protected override void OnPropertyChanged(PropertyChangedEventArgs e) { base.OnPropertyChanged(e); if (e.PropertyName == nameof(SnapshotStyles)) { if (!SnapshotStyles) { UpdateStyles(); } } } public void UpdateStyleFilters() { foreach (var style in AppliedStyles) { var hasVisibleSetter = false; foreach (var setter in style.Setters) { setter.IsVisible = TreePage.SettersFilter.Filter(setter.Name); hasVisibleSetter |= setter.IsVisible; } style.IsVisible = hasVisibleSetter; } } public void Dispose() { if (_avaloniaObject is INotifyPropertyChanged inpc) { inpc.PropertyChanged -= ControlPropertyChanged; } if (_avaloniaObject is AvaloniaObject ao) { ao.PropertyChanged -= ControlPropertyChanged; } if (_avaloniaObject is StyledElement se) { se.Classes.CollectionChanged -= OnClassesChanged; } } private IEnumerable<PropertyViewModel> GetAvaloniaProperties(object o) { if (o is AvaloniaObject ao) { return AvaloniaPropertyRegistry.Instance.GetRegistered(ao) .Union(AvaloniaPropertyRegistry.Instance.GetRegisteredAttached(ao.GetType())) .Select(x => new AvaloniaPropertyViewModel(ao, x)); } else { return Enumerable.Empty<AvaloniaPropertyViewModel>(); } } private IEnumerable<PropertyViewModel> GetClrProperties(object o, bool showImplementedInterfaces) { foreach (var p in GetClrProperties(o, o.GetType())) { yield return p; } if (showImplementedInterfaces) { foreach (var i in o.GetType().GetInterfaces()) { foreach (var p in GetClrProperties(o, i)) { yield return p; } } } } private IEnumerable<PropertyViewModel> GetClrProperties(object o, Type t) { return t.GetProperties() .Where(x => x.GetIndexParameters().Length == 0) .Select(x => new ClrPropertyViewModel(o, x)); } private void ControlPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { if (_propertyIndex is { } && _propertyIndex.TryGetValue(e.Property, out var properties)) { foreach (var property in properties) { property.Update(); } } Layout?.ControlPropertyChanged(sender, e); } private void ControlPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName != null && _propertyIndex is { } && _propertyIndex.TryGetValue(e.PropertyName, out var properties)) { foreach (var property in properties) { property.Update(); } } if (!SnapshotStyles) { UpdateStyles(); } } private void OnClassesChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (!SnapshotStyles) { UpdateStyles(); } } private void UpdateStyles() { int activeCount = 0; foreach (var style in AppliedStyles) { style.Update(); if (style.IsActive) { activeCount++; } } var propertyBuckets = new Dictionary<AvaloniaProperty, List<SetterViewModel>>(); foreach (var style in AppliedStyles) { if (!style.IsActive) { continue; } foreach (var setter in style.Setters) { if (propertyBuckets.TryGetValue(setter.Property, out var setters)) { foreach (var otherSetter in setters) { otherSetter.IsActive = false; } setter.IsActive = true; setters.Add(setter); } else { setter.IsActive = true; setters = new List<SetterViewModel> { setter }; propertyBuckets.Add(setter.Property, setters); } } } foreach (var pseudoClass in PseudoClasses) { pseudoClass.Update(); } StyleStatus = $"Styles ({activeCount}/{AppliedStyles.Count} active)"; } private bool FilterProperty(object arg) { return !(arg is PropertyViewModel property) || TreePage.PropertiesFilter.Filter(property.Name); } private class PropertyComparer : IComparer<PropertyViewModel> { public static PropertyComparer Instance { get; } = new PropertyComparer(); public int Compare(PropertyViewModel? x, PropertyViewModel? y) { var groupX = GroupIndex(x?.Group); var groupY = GroupIndex(y?.Group); if (groupX != groupY) { return groupX - groupY; } else { return string.CompareOrdinal(x?.Name, y?.Name); } } private int GroupIndex(string? group) { switch (group) { case "Properties": return 0; case "Attached Properties": return 1; case "CLR Properties": return 2; default: return 3; } } } public void ApplySelectedProperty() { var selectedProperty = SelectedProperty; var selectedEntity = SelectedEntity; var selectedEntityName = SelectedEntityName; if (selectedEntity == null || selectedProperty == null || selectedProperty.PropertyType == typeof(string) || selectedProperty.PropertyType.IsValueType ) return; object? property; if (selectedProperty.Key is AvaloniaProperty avaloniaProperty) { property = (_selectedEntity as IControl)?.GetValue(avaloniaProperty); } else { property = selectedEntity.GetType().GetProperties() .FirstOrDefault(pi => pi.Name == selectedProperty.Name && pi.DeclaringType == selectedProperty.DeclaringType && pi.PropertyType.Name == selectedProperty.PropertyType.Name) ?.GetValue(selectedEntity); } if (property == null) return; _selectedEntitiesStack.Push((Name:selectedEntityName!,Entry:selectedEntity)); NavigateToProperty(property, selectedProperty.Name); } public void ApplyParentProperty() { if (_selectedEntitiesStack.Any()) { var property = _selectedEntitiesStack.Pop(); NavigateToProperty(property.Entry, property.Name); } } protected void NavigateToProperty(object o, string? entityName) { var oldSelectedEntity = SelectedEntity; if (oldSelectedEntity is IAvaloniaObject ao1) { ao1.PropertyChanged -= ControlPropertyChanged; } else if (oldSelectedEntity is INotifyPropertyChanged inpc1) { inpc1.PropertyChanged -= ControlPropertyChanged; } SelectedEntity = o; SelectedEntityName = entityName; SelectedEntityType = o.ToString(); var properties = GetAvaloniaProperties(o) .Concat(GetClrProperties(o, _showImplementedInterfaces)) .OrderBy(x => x, PropertyComparer.Instance) .ThenBy(x => x.Name) .ToList(); _propertyIndex = properties.GroupBy(x => x.Key).ToDictionary(x => x.Key, x => x.ToList()); var view = new DataGridCollectionView(properties); view.GroupDescriptions.Add(new DataGridPathGroupDescription(nameof(AvaloniaPropertyViewModel.Group))); view.Filter = FilterProperty; PropertiesView = view; if (o is IAvaloniaObject ao2) { ao2.PropertyChanged += ControlPropertyChanged; } else if (o is INotifyPropertyChanged inpc2) { inpc2.PropertyChanged += ControlPropertyChanged; } } internal void UpdatePropertiesView(bool showImplementedInterfaces) { _showImplementedInterfaces = showImplementedInterfaces; SelectedProperty = null; NavigateToProperty(_avaloniaObject, (_avaloniaObject as IControl)?.Name ?? _avaloniaObject.ToString()); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Threading; using Apache.Ignite.Core.Portable; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Base class for all task-related tests. /// </summary> public abstract class AbstractTaskTest { /** */ protected const string Grid1Name = "grid1"; /** */ protected const string Grid2Name = "grid2"; /** */ protected const string Grid3Name = "grid3"; /** */ protected const string Cache1Name = "cache1"; /** Whether this is a test with forked JVMs. */ private readonly bool _fork; /** First node. */ [NonSerialized] protected IIgnite Grid1; /** Second node. */ [NonSerialized] private IIgnite _grid2; /** Third node. */ [NonSerialized] private IIgnite _grid3; /** Second process. */ [NonSerialized] private IgniteProcess _proc2; /** Third process. */ [NonSerialized] private IgniteProcess _proc3; /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected AbstractTaskTest(bool fork) { _fork = fork; } /// <summary> /// Initialization routine. /// </summary> [TestFixtureSetUp] public void InitClient() { TestUtils.KillProcesses(); if (_fork) { Grid1 = Ignition.Start(Configuration("config\\compute\\compute-standalone.xml")); _proc2 = Fork("config\\compute\\compute-standalone.xml"); while (true) { if (!_proc2.Alive) throw new Exception("Process 2 died unexpectedly: " + _proc2.Join()); if (Grid1.Cluster.Nodes().Count < 2) Thread.Sleep(100); else break; } _proc3 = Fork("config\\compute\\compute-standalone.xml"); while (true) { if (!_proc3.Alive) throw new Exception("Process 3 died unexpectedly: " + _proc3.Join()); if (Grid1.Cluster.Nodes().Count < 3) Thread.Sleep(100); else break; } } else { Grid1 = Ignition.Start(Configuration("config\\compute\\compute-grid1.xml")); _grid2 = Ignition.Start(Configuration("config\\compute\\compute-grid2.xml")); _grid3 = Ignition.Start(Configuration("config\\compute\\compute-grid3.xml")); } } [SetUp] public void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } [TestFixtureTearDown] public void StopClient() { if (Grid1 != null) Ignition.Stop(Grid1.Name, true); if (_fork) { if (_proc2 != null) { _proc2.Kill(); _proc2.Join(); } if (_proc3 != null) { _proc3.Kill(); _proc3.Join(); } } else { if (_grid2 != null) Ignition.Stop(_grid2.Name, true); if (_grid3 != null) Ignition.Stop(_grid3.Name, true); } } /// <summary> /// Configuration for node. /// </summary> /// <param name="path">Path to Java XML configuration.</param> /// <returns>Node configuration.</returns> protected IgniteConfiguration Configuration(string path) { IgniteConfiguration cfg = new IgniteConfiguration(); if (!_fork) { PortableConfiguration portCfg = new PortableConfiguration(); ICollection<PortableTypeConfiguration> portTypeCfgs = new List<PortableTypeConfiguration>(); PortableTypeConfigurations(portTypeCfgs); portCfg.TypeConfigurations = portTypeCfgs; cfg.PortableConfiguration = portCfg; } cfg.JvmClasspath = TestUtils.CreateTestClasspath(); cfg.JvmOptions = TestUtils.TestJavaOptions(); cfg.SpringConfigUrl = path; return cfg; } /// <summary> /// Create forked process with the following Spring config. /// </summary> /// <param name="path">Path to Java XML configuration.</param> /// <returns>Forked process.</returns> private static IgniteProcess Fork(string path) { return new IgniteProcess( "-springConfigUrl=" + path, "-J-ea", "-J-Xcheck:jni", "-J-Xms512m", "-J-Xmx512m", "-J-DIGNITE_QUIET=false" //"-J-Xnoagent", "-J-Djava.compiler=NONE", "-J-Xdebug", "-J-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5006" ); } /// <summary> /// Define portable types. /// </summary> /// <param name="portTypeCfgs">Portable type configurations.</param> protected virtual void PortableTypeConfigurations(ICollection<PortableTypeConfiguration> portTypeCfgs) { // No-op. } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Text; using FileHelpers.Events; using FileHelpers.Options; //using Container=FileHelpers.Container; namespace FileHelpers { /// <summary>Abstract Base class for the engines of the library: /// <see cref="FileHelperEngine"/> and /// <see cref="FileHelperAsyncEngine"/></summary> [EditorBrowsable(EditorBrowsableState.Never)] public abstract class EngineBase { internal const int DefaultReadBufferSize = 100*1024; internal const int DefaultWriteBufferSize = 100*1024; [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal IRecordInfo RecordInfo { get; private set; } //private readonly IRecordInfo mRecordInfo; #region " Constructor " /// <summary> /// Create an engine on record type, with default encoding /// </summary> /// <param name="recordType">Class to base engine on</param> internal EngineBase(Type recordType) : this(recordType, Encoding.Default) {} /// <summary> /// Create and engine on type with specified encoding /// </summary> /// <param name="recordType">Class to base engine on</param> /// <param name="encoding">encoding of the file</param> internal EngineBase(Type recordType, Encoding encoding) { if (recordType == null) throw new BadUsageException(Messages.Errors.NullRecordClass.Text); if (recordType.IsValueType) { throw new BadUsageException(Messages.Errors.StructRecordClass .RecordType(recordType.Name) .Text); } mRecordType = recordType; RecordInfo = FileHelpers.RecordInfo.Resolve(recordType); // Container.Resolve<IRecordInfo>(recordType); mEncoding = encoding; CreateRecordOptions(); } /// <summary> /// Create an engine on the record info provided /// </summary> /// <param name="ri">Record information</param> internal EngineBase(RecordInfo ri) { mRecordType = ri.RecordType; RecordInfo = ri; CreateRecordOptions(); } #endregion #region " LineNumber " [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal int mLineNumber; [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal int mTotalRecords; /// <include file='FileHelperEngine.docs.xml' path='doc/LineNum/*'/> public int LineNumber { get { return mLineNumber; } } #endregion #region " TotalRecords " /// <include file='FileHelperEngine.docs.xml' path='doc/TotalRecords/*'/> public int TotalRecords { get { return mTotalRecords; } } #endregion /// <summary> /// Builds a line with the name of the fields, for a delimited files it /// uses the same delimiter, for a fixed length field it writes the /// fields names separated with tabs /// </summary> /// <returns>field names structured for the heading of the file</returns> public string GetFileHeader() { var delimiter = "\t"; if (RecordInfo.IsDelimited) delimiter = ((DelimitedRecordOptions) Options).Delimiter; var res = new StringBuilder(); for (int i = 0; i < RecordInfo.Fields.Length; i++) { if (i > 0) res.Append(delimiter); var field = RecordInfo.Fields[i]; res.Append(field.FieldFriendlyName); } return res.ToString(); } #region " RecordType " [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Type mRecordType; /// <include file='FileHelperEngine.docs.xml' path='doc/RecordType/*'/> public Type RecordType { get { return mRecordType; } } #endregion #region " HeaderText " [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal string mHeaderText = String.Empty; /// <summary>The Read Header in the last Read operation. If any.</summary> public string HeaderText { get { return mHeaderText; } set { mHeaderText = value; } } #endregion #region " FooterText" /// <summary>The Read Footer in the last Read operation. If any.</summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] protected string mFooterText = String.Empty; /// <summary>The Read Footer in the last Read operation. If any.</summary> public string FooterText { get { return mFooterText; } set { mFooterText = value; } } #endregion #region " Encoding " /// <summary> /// The encoding to Read and Write the streams. /// Default is the system's current ANSI code page. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] protected Encoding mEncoding = Encoding.Default; /// <summary> /// The encoding to Read and Write the streams. /// Default is the system's current ANSI code page. /// </summary> /// <value>Default is the system's current ANSI code page.</value> public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } } #endregion #region " ErrorManager" /// <summary>This is a common class that manage the errors of the library.</summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] protected ErrorManager mErrorManager = new ErrorManager(); /// <summary>This is a common class that manages the errors of the library.</summary> /// <remarks> /// You can find complete information about the errors encountered while processing. /// For example, you can get the errors, their number and save them to a file, etc. /// </remarks> /// <seealso cref="FileHelpers.ErrorManager"/> public ErrorManager ErrorManager { get { return mErrorManager; } } /// <summary> /// Indicates the behavior of the engine when it finds an error. /// {Shortcut for <seealso cref="FileHelpers.ErrorManager.ErrorMode"/>) /// </summary> public ErrorMode ErrorMode { get { return mErrorManager.ErrorMode; } set { mErrorManager.ErrorMode = value; } } #endregion #region " ResetFields " /// <summary> /// Reset back to the beginning /// </summary> internal void ResetFields() { mLineNumber = 0; mErrorManager.ClearErrors(); mTotalRecords = 0; } #endregion /// <summary>Event handler called to notify progress.</summary> public event EventHandler<ProgressEventArgs> Progress; /// <summary> /// Determine whether a progress call is needed /// </summary> protected bool MustNotifyProgress { get { return Progress != null; } } /// <summary> /// Raises the Progress Event /// </summary> /// <param name="e">The Event Args</param> protected void OnProgress(ProgressEventArgs e) { if (Progress == null) return; Progress(this, e); } private void CreateRecordOptions() { Options = CreateRecordOptionsCore(RecordInfo); } internal static RecordOptions CreateRecordOptionsCore(IRecordInfo info) { RecordOptions options; if (info.IsDelimited) options = new DelimitedRecordOptions(info); else options = new FixedRecordOptions(info); for (int index = 0; index < options.Fields.Count; index++) { var field = options.Fields[index]; field.Parent = options; field.ParentIndex = index; } return options; } /// <summary> /// Allows you to change some record layout options at runtime /// </summary> public RecordOptions Options { get; private set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.IO.MemoryMappedFiles; using Microsoft.Win32.SafeHandles; using Xunit; using System.Runtime.InteropServices; [Collection("CreateViewAccessor")] public class CreateViewAccessor : MMFTestBase { private static readonly String s_fileNameForLargeCapacity = "CreateViewAccessor_MMF_ForLargeCapacity.txt"; [Fact] public static void CreateViewAccessorTestCases() { bool bResult = false; CreateViewAccessor test = new CreateViewAccessor(); try { bResult = test.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine("FAiL! Error Err_9999zzz! Uncaught Exception in main(), exc_main==" + exc_main.ToString()); } Assert.True(bResult, "One or more test cases failed."); } public bool runTest() { try { //////////////////////////////////////////////////////////////////////// // CreateViewAccessor() //////////////////////////////////////////////////////////////////////// long defaultCapacity = SystemInfoHelpers.GetPageSize(); MemoryMappedFileAccess defaultAccess = MemoryMappedFileAccess.ReadWrite; String fileContents = String.Empty; // Verify default values using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname101", 100)) { VerifyCreateViewAccessor("Loc101", mmf, defaultCapacity, defaultAccess, fileContents); } // default length is full MMF using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname102", defaultCapacity * 2)) { VerifyCreateViewAccessor("Loc102", mmf, defaultCapacity * 2, defaultAccess, fileContents); } // if MMF is read-only, default access throws using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname103", 100, MemoryMappedFileAccess.Read)) { VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc103", mmf); } //////////////////////////////////////////////////////////////////////// // CreateViewAccessor(long, long) //////////////////////////////////////////////////////////////////////// using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname200", defaultCapacity * 2)) { // 0 VerifyCreateViewAccessor("Loc201", mmf, 0, 0, defaultCapacity * 2, defaultAccess, fileContents); // >0 VerifyCreateViewAccessor("Loc202", mmf, 100, 0, defaultCapacity * 2 - 100, defaultAccess, fileContents); // >pagesize VerifyCreateViewAccessor("Loc203", mmf, defaultCapacity + 100, 0, defaultCapacity - 100, defaultAccess, fileContents); // <0 VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc204", mmf, -1, 0); // =MMF capacity VerifyCreateViewAccessor("Loc205", mmf, defaultCapacity * 2, 0, 0, defaultAccess, fileContents); // >MMF capacity VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc206", mmf, defaultCapacity * 2 + 1, 0); } // size using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname410", defaultCapacity * 2)) { // 0 VerifyCreateViewAccessor("Loc211", mmf, 1000, 0, defaultCapacity * 2 - 1000, defaultAccess, fileContents); // >0, <pagesize VerifyCreateViewAccessor("Loc212", mmf, 100, 1000, 1000, defaultAccess, fileContents); // =pagesize VerifyCreateViewAccessor("Loc213", mmf, 100, defaultCapacity, defaultCapacity, defaultAccess, fileContents); // >pagesize VerifyCreateViewAccessor("Loc214", mmf, 100, defaultCapacity + 1000, defaultCapacity + 1000, defaultAccess, fileContents); // <0 VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc215", mmf, 0, -1); VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc216", mmf, 0, -2); VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc217", mmf, 0, Int64.MinValue); // offset+size = MMF capacity VerifyCreateViewAccessor("Loc218", mmf, 0, defaultCapacity * 2, defaultCapacity * 2, defaultAccess, fileContents); VerifyCreateViewAccessor("Loc219", mmf, defaultCapacity, defaultCapacity, defaultCapacity, defaultAccess, fileContents); VerifyCreateViewAccessor("Loc220", mmf, defaultCapacity * 2 - 1, 1, 1, defaultAccess, fileContents); // offset+size > MMF capacity VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc221", mmf, 0, defaultCapacity * 2 + 1); VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc222", mmf, 1, defaultCapacity * 2); VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc223", mmf, defaultCapacity, defaultCapacity + 1); VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc224", mmf, defaultCapacity * 2, 1); // Int64.MaxValue - cannot exceed local address space if (IntPtr.Size == 4) VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc225", mmf, 0, Int64.MaxValue); else // 64-bit machine VerifyCreateViewAccessorException<IOException>("Loc225b", mmf, 0, Int64.MaxValue); // valid but too large } //////////////////////////////////////////////////////////////////////// // CreateViewAccessor(long, long, MemoryMappedFileAccess) //////////////////////////////////////////////////////////////////////// // [] offset using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname400", defaultCapacity * 2)) { // 0 VerifyCreateViewAccessor("Loc401", mmf, 0, 0, defaultAccess, defaultCapacity * 2, defaultAccess, fileContents); // >0 VerifyCreateViewAccessor("Loc402", mmf, 100, 0, defaultAccess, defaultCapacity * 2 - 100, defaultAccess, fileContents); // >pagesize VerifyCreateViewAccessor("Loc403", mmf, defaultCapacity + 100, 0, defaultAccess, defaultCapacity - 100, defaultAccess, fileContents); // <0 VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc404", mmf, -1, 0, defaultAccess); // =MMF capacity VerifyCreateViewAccessor("Loc405", mmf, defaultCapacity * 2, 0, defaultAccess, 0, defaultAccess, fileContents); // >MMF capacity VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc406", mmf, defaultCapacity * 2 + 1, 0, defaultAccess); } // size using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname410", defaultCapacity * 2)) { // 0 VerifyCreateViewAccessor("Loc411", mmf, 1000, 0, defaultAccess, defaultCapacity * 2 - 1000, defaultAccess, fileContents); // >0, <pagesize VerifyCreateViewAccessor("Loc412", mmf, 100, 1000, defaultAccess, 1000, defaultAccess, fileContents); // =pagesize VerifyCreateViewAccessor("Loc413", mmf, 100, defaultCapacity, defaultAccess, defaultCapacity, defaultAccess, fileContents); // >pagesize VerifyCreateViewAccessor("Loc414", mmf, 100, defaultCapacity + 1000, defaultAccess, defaultCapacity + 1000, defaultAccess, fileContents); // <0 VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc415", mmf, 0, -1, defaultAccess); VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc416", mmf, 0, -2, defaultAccess); VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc417", mmf, 0, Int64.MinValue, defaultAccess); // offset+size = MMF capacity VerifyCreateViewAccessor("Loc418", mmf, 0, defaultCapacity * 2, defaultAccess, defaultCapacity * 2, defaultAccess, fileContents); VerifyCreateViewAccessor("Loc419", mmf, defaultCapacity, defaultCapacity, defaultAccess, defaultCapacity, defaultAccess, fileContents); VerifyCreateViewAccessor("Loc420", mmf, defaultCapacity * 2 - 1, 1, defaultAccess, 1, defaultAccess, fileContents); // offset+size > MMF capacity VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc421", mmf, 0, defaultCapacity * 2 + 1, defaultAccess); VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc422", mmf, 1, defaultCapacity * 2, defaultAccess); VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc423", mmf, defaultCapacity, defaultCapacity + 1, defaultAccess); VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc424", mmf, defaultCapacity * 2, 1, defaultAccess); // Int64.MaxValue - cannot exceed local address space if (IntPtr.Size == 4) VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc425", mmf, 0, Int64.MaxValue, defaultAccess); else // 64-bit machine VerifyCreateViewAccessorException<IOException>("Loc425b", mmf, 0, Int64.MaxValue, defaultAccess); // valid but too large } // [] access MemoryMappedFileAccess[] accessList; // existing file is ReadWriteExecute using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname431", 1000, MemoryMappedFileAccess.ReadWriteExecute)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessor("Loc431_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents); } } // existing file is ReadExecute using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname432", 1000, MemoryMappedFileAccess.ReadExecute)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessor("Loc432_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents); } accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc432_" + access, mmf, 0, 0, access); } } // existing file is CopyOnWrite using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname433", 1000, MemoryMappedFileAccess.CopyOnWrite)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessor("Loc433_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents); } accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc433_" + access, mmf, 0, 0, access); } } // existing file is ReadWrite using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname434", 1000, MemoryMappedFileAccess.ReadWrite)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessor("Loc434_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents); } accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc434_" + access, mmf, 0, 0, access); } } // existing file is Read using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname435", 1000, MemoryMappedFileAccess.Read)) { accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessor("Loc435_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents); } accessList = new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Write, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute, }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessorException<UnauthorizedAccessException>("Loc435_" + access, mmf, 0, 0, access); } } // invalid enum value using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVA_mapname436", 1000, MemoryMappedFileAccess.ReadWrite)) { accessList = new MemoryMappedFileAccess[] { (MemoryMappedFileAccess)(-1), (MemoryMappedFileAccess)(6), }; foreach (MemoryMappedFileAccess access in accessList) { VerifyCreateViewAccessorException<ArgumentOutOfRangeException>("Loc436_" + ((int)access), mmf, 0, 0, access); } } // File-backed MemoryMappedFile size should not be constrained to size of system's logical address space TestLargeCapacity(); /// END TEST CASES if (iCountErrors == 0) { return true; } else { Console.WriteLine("FAiL! iCountErrors==" + iCountErrors); return false; } } catch (Exception ex) { Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex); return false; } } private void TestLargeCapacity() { try { // Prepare the test file using (FileStream fs = File.Open(s_fileNameForLargeCapacity, FileMode.CreateNew)) { } // 2^31-1, 2^31, 2^31+1, 2^32-1, 2^32, 2^32+1 Int64[] capacities = { 2147483647, 2147483648, 2147483649, 4294967295, 4294967296, 4294967297 }; foreach (Int64 capacity in capacities) { RunTestLargeCapacity(capacity); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("Unexpected exception in TestLargeCapacity: {0}", ex.ToString()); } finally { if (File.Exists(s_fileNameForLargeCapacity)) { File.Delete(s_fileNameForLargeCapacity); } } } private void RunTestLargeCapacity(Int64 capacity) { iCountTestcases++; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(s_fileNameForLargeCapacity, FileMode.Open, "CVA_RunTestLargeCapacity", capacity)) { try { // mapping all; this should fail for 32-bit using (MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor(0, capacity, MemoryMappedFileAccess.ReadWrite)) { if (IntPtr.Size == 4) { iCountErrors++; Console.WriteLine("Err440! Not throwing expected ArgumentOutOfRangeException for capacity " + capacity); } } } catch (ArgumentOutOfRangeException aore) { if (IntPtr.Size != 4) { iCountErrors++; Console.WriteLine("Err441! Shouldn't get ArgumentOutOfRangeException on 64-bit: {0}", aore.ToString()); } else if (capacity < UInt32.MaxValue) { iCountErrors++; Console.WriteLine("Err442! Expected IOExc but got ArgOutOfRangeExc"); } else { // Got expected ArgumentOutOfRangeException } } catch (IOException ioex) { if (IntPtr.Size != 4) { iCountErrors++; Console.WriteLine("Err443! Shouldn't get IOException on 64-bit: {0}", ioex.ToString()); } else if (capacity > UInt32.MaxValue) { Console.WriteLine("Err444! Expected ArgOutOfRangeExc but got IOExc: {0}", ioex.ToString()); } else { // Got expected IOException } } } } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err445! Got unexpected exception: {0}", ex.ToString()); } } /// START HELPER FUNCTIONS public void VerifyCreateViewAccessor(String strLoc, MemoryMappedFile mmf, long expectedCapacity, MemoryMappedFileAccess expectedAccess, String expectedContents) { iCountTestcases++; try { using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor()) { Eval(expectedCapacity, view.Capacity, "ERROR, {0}: Wrong capacity", strLoc); VerifyAccess(strLoc, view, expectedAccess); VerifyContents(strLoc, view, expectedContents); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreateViewAccessorException<EXCTYPE>(String strLoc, MemoryMappedFile mmf) where EXCTYPE : Exception { iCountTestcases++; try { using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor()) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreateViewAccessor(String strLoc, MemoryMappedFile mmf, long offset, long size, long expectedCapacity, MemoryMappedFileAccess expectedAccess, String expectedContents) { iCountTestcases++; try { using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(offset, size)) { Eval(expectedCapacity, view.Capacity, "ERROR, {0}: Wrong capacity", strLoc); VerifyAccess(strLoc, view, expectedAccess); VerifyContents(strLoc, view, expectedContents); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreateViewAccessorException<EXCTYPE>(String strLoc, MemoryMappedFile mmf, long offset, long size) where EXCTYPE : Exception { iCountTestcases++; try { using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(offset, size)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreateViewAccessor(String strLoc, MemoryMappedFile mmf, long offset, long size, MemoryMappedFileAccess access, long expectedCapacity, MemoryMappedFileAccess expectedAccess, String expectedContents) { iCountTestcases++; try { using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(offset, size, access)) { Eval(expectedCapacity, view.Capacity, "ERROR, {0}: Wrong capacity", strLoc); VerifyAccess(strLoc, view, expectedAccess); VerifyContents(strLoc, view, expectedContents); } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyCreateViewAccessorException<EXCTYPE>(String strLoc, MemoryMappedFile mmf, long offset, long size, MemoryMappedFileAccess access) where EXCTYPE : Exception { iCountTestcases++; try { using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(offset, size, access)) { iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } void VerifyAccess(String strLoc, MemoryMappedViewAccessor view, MemoryMappedFileAccess expectedAccess) { try { bool expectedRead = ((expectedAccess == MemoryMappedFileAccess.Read) || (expectedAccess == MemoryMappedFileAccess.CopyOnWrite) || (expectedAccess == MemoryMappedFileAccess.ReadWrite) || (expectedAccess == MemoryMappedFileAccess.ReadExecute) || (expectedAccess == MemoryMappedFileAccess.ReadWriteExecute)); bool expectedWrite = ((expectedAccess == MemoryMappedFileAccess.Write) || (expectedAccess == MemoryMappedFileAccess.CopyOnWrite) || (expectedAccess == MemoryMappedFileAccess.ReadWrite) || (expectedAccess == MemoryMappedFileAccess.ReadWriteExecute)); Eval(expectedRead, view.CanRead, "ERROR, {0}, CanRead was wrong", strLoc); Eval(expectedWrite, view.CanWrite, "ERROR, {0}, CanWrite was wrong", strLoc); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}, Unexpected exception, {1}", strLoc, ex); } } void VerifyContents(String strLoc, MemoryMappedViewAccessor view, String expectedContents) { } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Windows.Forms; using Gallio.Runtime.ConsoleSupport; using Gallio.Properties; using Gallio.Common.Collections; namespace Gallio.Runtime.ConsoleSupport { /// <summary> /// Parser for command line arguments. /// </summary> /// <remarks> /// <para> /// The parser specification is infered from the instance fields of the object /// specified as the destination of the parse. /// Valid argument types are: int, uint, string, bool, enums /// Also argument types of Array of the above types are also valid. /// </para> /// <para> /// Error checking options can be controlled by adding a CommandLineArgumentAttribute /// to the instance fields of the destination object. /// </para> /// <para> /// At most one field may be marked with the DefaultCommandLineArgumentAttribute /// indicating that arguments without a '-' or '/' prefix will be parsed as that argument. /// </para> /// <para> /// If not specified then the parser will infer default options for parsing each /// instance field. The default long name of the argument is the field name. The /// default short name is the first character of the long name. Long names and explicitly /// specified short names must be unique. Default short names will be used provided that /// the default short name does not conflict with a long name or an explicitly /// specified short name. /// </para> /// <para> /// Arguments which are array types are collection arguments. Collection /// arguments can be specified multiple times. /// </para> /// <para> /// Command line parsing code adapted from /// <a href="http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e"> /// Peter Halam</a>. /// </para> /// </remarks> public class CommandLineArgumentParser { private readonly Type argumentSpecification; private readonly ResponseFileReader responseFileReader; private List<Argument> arguments; private Dictionary<string, Argument> argumentMap; private Argument defaultArgument; private bool defaultArgumentConsumesUnrecognizedSwitches; /// <summary> /// Creates a new command line argument parser. /// </summary> /// <param name="argumentSpecification">The argument type containing fields decorated /// with <see cref="CommandLineArgumentAttribute" />.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="argumentSpecification"/> is null.</exception> public CommandLineArgumentParser(Type argumentSpecification) : this(argumentSpecification, File.ReadAllText) { } /// <summary> /// Creates a new command line argument parser. /// </summary> /// <param name="argumentSpecification">The argument type containing fields decorated /// with <see cref="CommandLineArgumentAttribute" /></param> /// <param name="responseFileReader">The delegate to use for reading response files instead of the default, /// or null to disable reading from response files.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="argumentSpecification"/> is null.</exception> public CommandLineArgumentParser(Type argumentSpecification, ResponseFileReader responseFileReader) { if (argumentSpecification == null) throw new ArgumentNullException(@"argumentSpecification"); this.argumentSpecification = argumentSpecification; this.responseFileReader = responseFileReader; PopulateArgumentMap(); } /// <summary> /// Parses an argument list. /// </summary> /// <param name="args">The arguments to parse.</param> /// <param name="destination">The destination of the parsed arguments.</param> /// <param name="reporter">The error reporter.</param> /// <returns>True if no parse errors were encountered.</returns> public bool Parse(string[] args, object destination, CommandLineErrorReporter reporter) { if (args == null || Array.IndexOf(args, null) >= 0) throw new ArgumentNullException(@"args"); if (destination == null) throw new ArgumentNullException(@"destination"); if (!argumentSpecification.IsInstanceOfType(destination)) throw new ArgumentException(Resources.CommandLineArgumentParser_ArgumentObjectIsOfIncorrectType, @"destination"); if (reporter == null) throw new ArgumentNullException(@"reporter"); var argumentValues = new MultiMap<Argument, object>(); try { bool hadError = ParseArgumentList(args, argumentValues, reporter); // Finished assigning values. foreach (Argument arg in arguments) hadError |= arg.AssignValue(destination, argumentValues, reporter); if (defaultArgument != null) hadError |= defaultArgument.AssignValue(destination, argumentValues, reporter); return !hadError; } catch (Exception ex) { reporter(string.Format(Resources.CommandLineArgumentParser_ExceptionWhileParsing, ex.Message)); return false; } } /// <summary> /// Prints a user friendly usage string describing the command line argument syntax. /// </summary> /// <param name="output">The command line output.</param> public void ShowUsage(CommandLineOutput output) { if (output == null) throw new ArgumentNullException(@"output"); foreach (Argument arg in arguments) { output.PrintArgumentHelp(@"/", arg.LongName, arg.ShortName, arg.Description, arg.ValueLabel, arg.ValueType); output.NewLine(); } if (SupportsResponseFiles) { output.PrintArgumentHelp(@"@", null, null, Resources.CommandLineArgumentParser_ResponseFileDescription, Resources.CommandLineArgumentParser_ResponseFileValueLabel, typeof (string)); output.NewLine(); } if (defaultArgument != null) { output.PrintArgumentHelp(null, null, null, defaultArgument.Description, defaultArgument.ValueLabel, defaultArgument.ValueType); output.NewLine(); } } /// <summary> /// Prints a user friendly usage string describing the command line argument syntax in a message box. /// </summary> /// <param name="caption">The message box caption.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="caption"/> is null.</exception> public void ShowUsageInMessageBox(string caption) { if (caption == null) throw new ArgumentNullException("caption"); StringWriter writer = new StringWriter(); writer.WriteLine("Available options:"); writer.WriteLine(); ShowUsage(new CommandLineOutput(writer, 60)); MessageBox.Show(writer.ToString(), caption); } private bool SupportsResponseFiles { get { return responseFileReader != null; } } private void PopulateArgumentMap() { arguments = new List<Argument>(); argumentMap = new Dictionary<string, Argument>(); foreach (FieldInfo field in argumentSpecification.GetFields()) { if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral) { CommandLineArgumentAttribute attribute = GetAttribute(field); var defaultAttribute = attribute as DefaultCommandLineArgumentAttribute; if (defaultAttribute != null) { if (defaultArgument != null) ThrowError(Resources.CommandLineArgumentParser_MoreThanOneDefaultCommandLineArgumentDefined); defaultArgument = new Argument(attribute, field); defaultArgumentConsumesUnrecognizedSwitches = defaultAttribute.ConsumeUnrecognizedSwitches; } else { arguments.Add(new Argument(attribute, field)); } } } // add explicit names to map foreach (Argument argument in arguments) { AddArgumentToMap(argument.LongName, argument); if (!string.IsNullOrEmpty(argument.ShortName)) AddArgumentToMap(argument.ShortName, argument); foreach (string synonym in argument.Synonyms) AddArgumentToMap(synonym, argument); } } private void AddArgumentToMap(string argumentName, Argument argument) { if (argumentMap.ContainsKey(argumentName)) ThrowError(Resources.CommandLineArgumentParser_DuplicateArgumentName, argumentName); argumentMap.Add(argumentName, argument); } private bool ParseArgumentList(IEnumerable<string> args, MultiMap<Argument, object> argumentValues, CommandLineErrorReporter reporter) { bool hadError = false; foreach (string argument in args) { if (argument.Length == 0) continue; switch (argument[0]) { case '-': case '/': int endIndex = argument.IndexOfAny(new char[] { ':', '+' }, 1); string option = argument.Substring(1, endIndex == -1 ? argument.Length - 1 : endIndex - 1); string optionArgument; if (option.Length + 1 == argument.Length) optionArgument = null; else if (argument.Length > 1 + option.Length && argument[1 + option.Length] == ':') optionArgument = argument.Substring(option.Length + 2); else optionArgument = argument.Substring(option.Length + 1); Argument arg; if (argumentMap.TryGetValue(option, out arg)) { hadError |= !arg.AddValue(optionArgument, argumentValues, reporter); } else if (defaultArgumentConsumesUnrecognizedSwitches) { hadError |= !defaultArgument.AddValue(argument, argumentValues, reporter); } else { ReportUnrecognizedArgument(reporter, argument); hadError = true; } break; case '@': if (SupportsResponseFiles) { string[] nestedArguments; hadError |= LexFileArguments(argument.Substring(1), reporter, out nestedArguments); if (nestedArguments != null) hadError |= ParseArgumentList(nestedArguments, argumentValues, reporter); } else if (defaultArgument != null) { hadError |= !defaultArgument.AddValue(argument, argumentValues, reporter); } else { ReportUnrecognizedArgument(reporter, argument); hadError = true; } break; default: if (defaultArgument != null) { hadError |= !defaultArgument.AddValue(argument, argumentValues, reporter); } else { ReportUnrecognizedArgument(reporter, argument); hadError = true; } break; } } return hadError; } private static void ReportUnrecognizedArgument(CommandLineErrorReporter reporter, string argument) { reporter(string.Format(Resources.CommandLineArgumentParser_UnrecognizedArgument, argument)); } private bool LexFileArguments(string fileName, CommandLineErrorReporter reporter, out string[] nestedArguments) { nestedArguments = null; string args = GetResponseFileContents(fileName, reporter); if (args == null) return true; bool hadError = false; List<string> argArray = new List<string>(); StringBuilder currentArg = new StringBuilder(); bool inQuotes = false; int index = 0; try { for (; ; ) { // skip whitespace while (char.IsWhiteSpace(args[index])) { index += 1; } // # - comment to end of line if (args[index] == '#') { index += 1; while (args[index] != '\n') { index += 1; } continue; } // do one argument do { if (args[index] == '\\') { int cSlashes = 1; index += 1; while (index == args.Length && args[index] == '\\') { cSlashes += 1; } if (index == args.Length || args[index] != '"') { currentArg.Append('\\', cSlashes); } else { currentArg.Append('\\', (cSlashes >> 1)); if (0 != (cSlashes & 1)) { currentArg.Append('"'); } else { inQuotes = !inQuotes; } } } else if (args[index] == '"') { inQuotes = !inQuotes; index += 1; } else { currentArg.Append(args[index]); index += 1; } } while (!char.IsWhiteSpace(args[index]) || inQuotes); argArray.Add(currentArg.ToString()); currentArg.Length = 0; } } catch (IndexOutOfRangeException) { // got EOF if (inQuotes) { reporter(string.Format(Resources.CommandLineArgumentParser_MismatchedQuotedInResponseFile, fileName)); hadError = true; } else if (currentArg.Length > 0) { // valid argument can be terminated by EOF argArray.Add(currentArg.ToString()); } } nestedArguments = argArray.ToArray(); return hadError; } private string GetResponseFileContents(string fileName, CommandLineErrorReporter reporter) { string args = null; try { args = responseFileReader(fileName); } catch (FileNotFoundException) { reporter(string.Format(Resources.CommandLineArgumentParser_ResponseFileDoesNotExist, fileName)); } catch (Exception e) { reporter(string.Format(Resources.CommandLineArgumentParser_ErrorOpeningResponseFile, fileName, e.Message)); } return args; } private static CommandLineArgumentAttribute GetAttribute(ICustomAttributeProvider field) { object[] attributes = field.GetCustomAttributes(typeof(CommandLineArgumentAttribute), false); if (attributes.Length == 0) ThrowError(Resources.CommandLineArgumentParser_NoArgumentFields); return (CommandLineArgumentAttribute)attributes[0]; } private static void ThrowError(string message, params Object[] args) { throw new InvalidOperationException(String.Format(message, args)); } private sealed class Argument { private readonly FieldInfo field; private readonly string longName; private readonly string shortName; private readonly string valueLabel; private readonly CommandLineArgumentFlags flags; private readonly Type valueType; private readonly string description; private readonly string[] synonyms; private readonly bool isDefault; public Argument(CommandLineArgumentAttribute attribute, FieldInfo field) { this.field = field; longName = GetLongName(attribute, field); shortName = GetShortName(attribute, field); valueType = GetValueType(field); flags = GetFlags(attribute, field); if (attribute != null) { isDefault = attribute is DefaultCommandLineArgumentAttribute; description = attribute.Description; valueLabel = attribute.ValueLabel; synonyms = attribute.Synonyms; } else { synonyms = EmptyArray<string>.Instance; } if (IsCollection && !AllowMultiple) ThrowError(Resources.CommandLineArgumentParser_Argument_CollectionArgumentsMustAllowMultipleValues); if (string.IsNullOrEmpty(longName)) ThrowError(Resources.CommandLineArgumentParser_Argument_MissingLongName); if (Unique && ! IsCollection) ThrowError(Resources.CommandLineArgumentParser_Argument_InvalidUsageOfUniqueFlag); if (! IsValidElementType(valueType)) ThrowError(Resources.CommandLineArgumentParser_Argument_UnsupportedValueType); } public bool AssignValue(object destination, MultiMap<Argument, object> argumentValues, CommandLineErrorReporter reporter) { IList<object> values = argumentValues[this]; if (IsCollection) { Array array = Array.CreateInstance(valueType, values.Count); for (int i = 0; i < values.Count; i++) array.SetValue(values[i], i); field.SetValue(destination, array); } else if (values.Count != 0) { field.SetValue(destination, values[0]); } else if (IsRequired) { if (IsDefault) reporter(Resources.CommandLineArgumentParser_Argument_MissingRequiredDefaultArgument); else reporter(string.Format(Resources.CommandLineArgumentParser_Argument_MissingRequiredArgument, LongName)); return true; } return false; } public bool AddValue(string value, MultiMap<Argument, object> argumentValues, CommandLineErrorReporter reporter) { if (!AllowMultiple && argumentValues.ContainsKey(this)) { reporter(string.Format(Resources.CommandLineArgumentParser_Argument_DuplicateArgument, LongName)); return false; } object newValue; if (!ParseValue(ValueType, value, out newValue)) { reporter(string.Format(Resources.CommandLineArgumentParser_Argument_InvalidArgumentValue, LongName, value)); return false; } if (Unique && argumentValues.Contains(this, newValue)) { reporter(string.Format(Resources.CommandLineArgumentParser_Argument_DuplicateArgumentValueExpectedUnique, LongName, value)); return false; } argumentValues.Add(this, newValue); return true; } public Type ValueType { get { return valueType; } } private static bool ParseValue(Type type, string stringData, out object value) { // null is only valid for bool variables // empty string is never valid if ((stringData != null || type == typeof(bool)) && (stringData == null || stringData.Length > 0)) { try { if (type == typeof(string)) { value = stringData; return true; } else if (type == typeof(bool)) { if (stringData == null || stringData == @"+") { value = true; return true; } else if (stringData == @"-") { value = false; return true; } } else if (type == typeof(int)) { value = int.Parse(stringData); return true; } else if (type == typeof(uint)) { value = int.Parse(stringData); return true; } else { Debug.Assert(type.IsEnum); value = Enum.Parse(type, stringData, true); return true; } } catch { // catch parse errors } } value = null; return false; } public string LongName { get { return longName; } } public string ShortName { get { return shortName; } } public string[] Synonyms { get { return synonyms; } } public string ValueLabel { get { return valueLabel; } } public bool IsRequired { get { return 0 != (flags & CommandLineArgumentFlags.Required); } } public bool AllowMultiple { get { return 0 != (flags & CommandLineArgumentFlags.Multiple); } } public bool Unique { get { return 0 != (flags & CommandLineArgumentFlags.Unique); } } public Type Type { get { return field.FieldType; } } public bool IsCollection { get { return IsCollectionType(Type); } } public bool IsNullable { get { return IsNullableType(Type); } } public bool IsDefault { get { return isDefault; } } public string Description { get { return description; } } private static string GetLongName(CommandLineArgumentAttribute attribute, FieldInfo field) { return attribute == null || attribute.IsDefaultLongName ? field.Name : attribute.LongName; } private static string GetShortName(CommandLineArgumentAttribute attribute, FieldInfo field) { return attribute == null || attribute.IsDefaultShortName ? GetLongName(attribute, field).Substring(0, 1) : attribute.ShortName; } private static Type GetValueType(FieldInfo field) { if (IsCollectionType(field.FieldType)) return field.FieldType.GetElementType(); if (IsNullableType(field.FieldType)) return Nullable.GetUnderlyingType(field.FieldType); return field.FieldType; } private static CommandLineArgumentFlags GetFlags(CommandLineArgumentAttribute attribute, FieldInfo field) { if (attribute != null) return attribute.Flags; else if (IsCollectionType(field.FieldType)) return CommandLineArgumentFlags.MultipleUnique; else return CommandLineArgumentFlags.AtMostOnce; } private static bool IsCollectionType(Type type) { return type.IsArray; } private static bool IsNullableType(Type type) { return Nullable.GetUnderlyingType(type) != null; } private static bool IsValidElementType(Type type) { return type != null && ( type == typeof(int) || type == typeof(uint) || type == typeof(string) || type == typeof(bool) || type.IsEnum); } } } }
//------------------------------------------------------------------------------ // <copyright file="ObjectListFieldCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * Object List Field Collection class. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class ObjectListFieldCollection : ArrayListCollectionBase, IObjectListFieldCollection, IStateManager { private ObjectList _owner; private bool _marked = false; private bool _fieldsSetDirty = false; // Used for primary field collection (the one modified by the user). internal ObjectListFieldCollection(ObjectList owner) : base(new ArrayList()) { _owner = owner; } // Used for autogenerated field collections. internal ObjectListFieldCollection(ObjectList owner, ArrayList fields) : base(fields) { _owner = owner; foreach (ObjectListField field in fields) { field.SetOwner(owner); } } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.GetAll"]/*' /> public ObjectListField[] GetAll() { int n = Count; ObjectListField[] allFields = new ObjectListField[n]; if (n > 0) { Items.CopyTo(0, allFields, 0, n); } return allFields; } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.SetAll"]/*' /> public void SetAll(ObjectListField[] value) { Items = new ArrayList(value); foreach(ObjectListField field in Items) { field.SetOwner(_owner); } if(_marked) { SetFieldsDirty(); } } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.this"]/*' /> public ObjectListField this[int index] { get { return (ObjectListField)Items[index]; } } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.Add"]/*' /> public void Add(ObjectListField field) { AddAt(-1, field); } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.AddAt"]/*' /> public void AddAt(int index, ObjectListField field) { if (index == -1) { Items.Add(field); } else { Items.Insert(index, field); } if (_marked) { if (!_fieldsSetDirty && index > -1) { SetFieldsDirty(); } else { ((IStateManager)field).TrackViewState(); field.SetDirty(); } } field.SetOwner(_owner); NotifyOwnerChange(); } private void SetFieldsDirty() { foreach (ObjectListField fld in Items) { ((IStateManager)fld).TrackViewState(); fld.SetDirty(); } _fieldsSetDirty = true; } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.Clear"]/*' /> public void Clear() { Items.Clear(); if (_marked) { // Each field will be marked dirty as it is added. _fieldsSetDirty = true; } NotifyOwnerChange(); } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.RemoveAt"]/*' /> public void RemoveAt(int index) { if ((index >= 0) && (index < Count)) { Items.RemoveAt(index); } if(_marked && !_fieldsSetDirty) { SetFieldsDirty(); } NotifyOwnerChange(); } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.Remove"]/*' /> public void Remove(ObjectListField field) { int index = IndexOf(field); if (index >= 0) { RemoveAt(index); } } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.IndexOf"]/*' /> public int IndexOf(ObjectListField field) { if (field != null) { return Items.IndexOf(field, 0, Count); } return -1; } /// <include file='doc\ObjectListFieldCollection.uex' path='docs/doc[@for="ObjectListFieldCollection.IndexOf1"]/*' /> public int IndexOf(String fieldIDOrName) { ArrayList fields = Items; int i = 0; foreach (ObjectListField field in fields) { String id = field.UniqueID; if (id != null && String.Compare(id, fieldIDOrName, StringComparison.OrdinalIgnoreCase) == 0) { return i; } i++; } return -1; } private void NotifyOwnerChange() { if (_owner != null) { _owner.OnFieldChanged(true); // fieldAddedOrRemoved = true } } ///////////////////////////////////////////////////////////////////////// // STATE MANAGEMENT ///////////////////////////////////////////////////////////////////////// /// <internalonly/> protected bool IsTrackingViewState { get { return _marked; } } /// <internalonly/> protected void TrackViewState() { _marked = true; foreach (IStateManager field in Items) { field.TrackViewState(); } } /// <internalonly/> protected void LoadViewState(Object savedState) { if (savedState != null) { Object[] stateArray = (Object[]) savedState; bool allFieldsSaved = (bool) stateArray[0]; if (allFieldsSaved) { // All fields are in view state. Any fields loaded until now are invalid. ClearFieldsViewState(); } Object[] fieldStates = (Object[])stateArray[1]; EnsureCount(fieldStates.Length); for (int i = 0; i < fieldStates.Length; i++) { ((IStateManager)Items[i]).LoadViewState(fieldStates[i]); } if (allFieldsSaved) { SetFieldsDirty(); } } } /// <internalonly/> protected Object SaveViewState() { int fieldsCount = Count; if (fieldsCount > 0) { Object[] fieldStates = new Object[fieldsCount]; bool haveState = _fieldsSetDirty; for (int i = 0; i < fieldsCount; i++) { fieldStates[i] = ((IStateManager)Items[i]).SaveViewState(); if (fieldStates[i] != null) { haveState = true; } } if (haveState) { return new Object[]{_fieldsSetDirty, fieldStates}; } } return null; } private void EnsureCount(int count) { int diff = Count - count; if (diff > 0) { Items.RemoveRange(count, diff); NotifyOwnerChange(); } else { // Set owner = null, to avoid multiple change notifications. // We'll call it just once later. ObjectList prevOwner = _owner; _owner = null; for (int i = diff; i < 0; i++) { ObjectListField field = new ObjectListField(); Add(field); field.SetOwner(prevOwner); } _owner = prevOwner; NotifyOwnerChange(); } } private void ClearFieldsViewState() { foreach (ObjectListField field in Items) { field.ClearViewState(); } } #region Implementation of IStateManager /// <internalonly/> bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } /// <internalonly/> void IStateManager.LoadViewState(object state) { LoadViewState(state); } /// <internalonly/> void IStateManager.TrackViewState() { TrackViewState(); } /// <internalonly/> object IStateManager.SaveViewState() { return SaveViewState(); } #endregion } }
namespace NRepository.Core.Command { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using NRepository.Core.Events; using NRepository.Core.Utilities; public abstract class BatchCommandRepositoryBase : ICommandRepository { private bool _disposed; private readonly List<IEntityStateWrapper> _BatchedStorageItems; public BatchCommandRepositoryBase() : this(new DefaultCommandEventsHandlers()) { } public BatchCommandRepositoryBase(ICommandEventHandlers eventHandlers) { Check.NotNull(eventHandlers, "eventHandlers"); EventHandlers = eventHandlers; _BatchedStorageItems = new List<IEntityStateWrapper>(); } [ExcludeFromCodeCoverage] ~BatchCommandRepositoryBase() { Dispose(false); } public object ObjectContext { get; protected set; } protected ICommandEventHandlers EventHandlers { get; set; } public IEnumerable<IEntityStateWrapper> BatchedItems { get { return _BatchedStorageItems; } } public virtual void Add<T>(T entity) where T : class { Check.NotNull(entity, "entity"); Add<T>(entity, new DefaultAddCommandInterceptor()); } public virtual void Add<T>(T entity, IAddCommandInterceptor addInterceptor) where T : class { Check.NotNull(entity, "entity"); Check.NotNull(addInterceptor, "addInterceptor"); _BatchedStorageItems.Add(new EntityStateWrapper { Entity = entity, State = State.Add, CommandInterceptor = addInterceptor }); EventHandlers.EntityAddedEventHandler.Handle(new EntityAddedEvent(this, entity)); } public virtual void Modify<T>(T entity) where T : class { Check.NotNull(entity, "entity"); Modify<T>(entity, new DefaultModifyCommandInterceptor()); } public virtual void Modify<T>(T entity, IModifyCommandInterceptor modifyInterceptor) where T : class { Check.NotNull(entity, "entity"); Check.NotNull(modifyInterceptor, "modifyInterceptor"); _BatchedStorageItems.Add(new EntityStateWrapper { Entity = entity, State = State.Modify, CommandInterceptor = modifyInterceptor }); EventHandlers.EntityModifiedEventHandler.Handle(new EntityModifiedEvent(this, entity)); } public virtual void Delete<T>(T entity) where T : class { Check.NotNull(entity, "entity"); Delete(entity, new DefaultDeleteCommandInterceptor()); } public virtual void Delete<T>(T entity, IDeleteCommandInterceptor removeInterceptor) where T : class { Check.NotNull(entity, "entity"); Check.NotNull(removeInterceptor, "removeInterceptor"); _BatchedStorageItems.Add(new EntityStateWrapper { Entity = entity, State = State.Delete, CommandInterceptor = removeInterceptor }); EventHandlers.EntityDeletedEventHandler.Handle(new EntityDeletedEvent(this, entity)); } public virtual int Save(ISaveCommandInterceptor savingStrategy) { Check.NotNull(savingStrategy, "savingStrategy"); var retVal = savingStrategy.Save(this, Save); return retVal; } public virtual int Save() { _BatchedStorageItems.ForEach(p => { switch (p.State) { case State.Add: AddEntityActioned(p.Entity, (IAddCommandInterceptor)p.CommandInterceptor); break; case State.Modify: ModifyEntityActioned(p.Entity, (IModifyCommandInterceptor)p.CommandInterceptor); break; case State.Delete: DeleteEntityActioned(p.Entity, (IDeleteCommandInterceptor)p.CommandInterceptor); break; default: throw new NotSupportedException(); } }); var retVal = _BatchedStorageItems.Count; _BatchedStorageItems.Clear(); EventHandlers.RepositorySavedEventHandler.Handle(new RepositorySavedEvent(this)); return retVal; } [ExcludeFromCodeCoverage] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [ExcludeFromCodeCoverage] protected virtual void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) { if (ObjectContext is IDisposable) { ((IDisposable)ObjectContext).Dispose(); } } } protected abstract void AddEntityActioned<T>(T entity, IAddCommandInterceptor addCommandInterceptor) where T : class; protected abstract void ModifyEntityActioned<T>(T entity, IModifyCommandInterceptor modifyCommandInterceptor) where T : class; protected abstract void DeleteEntityActioned<T>(T entity, IDeleteCommandInterceptor deleteCommandInterceptor) where T : class; public virtual async Task AddAsync<T>(T entity) where T : class { await Task.Run(() => Add(entity)); } public virtual async Task AddAsync<T>(T entity, IAddCommandInterceptor addInterceptor) where T : class { Check.NotNull(entity, "entity"); Check.NotNull(addInterceptor, "addInterceptor"); await Task.Run(() => Add(entity, addInterceptor)); } public virtual async Task ModifyAsync<T>(T entity) where T : class { Check.NotNull(entity, "entity"); await Task.Run(() => Modify(entity)); } public virtual async Task ModifyAsync<T>(T entity, IModifyCommandInterceptor modifyInterceptor) where T : class { Check.NotNull(entity, "entity"); Check.NotNull(modifyInterceptor, "modifyInterceptor"); await Task.Run(() => Modify(entity, modifyInterceptor)); } public virtual async Task DeleteAsync<T>(T entity) where T : class { Check.NotNull(entity, "entity"); await Task.Run(() => Delete(entity)); } public virtual async Task DeleteAsync<T>(T entity, IDeleteCommandInterceptor deleteStrategy) where T : class { Check.NotNull(deleteStrategy, "deleteStrategy"); await Task.Run(() => Delete(entity, deleteStrategy)); } public virtual async Task<int> SaveAsync() { return await SaveAsync(new DefaultSaveCommandInterceptor()); } public virtual async Task<int> SaveAsync(ISaveCommandInterceptor savingStrategy) { Check.NotNull(savingStrategy, "savingStrategy"); return await Task<int>.Run(() => Save(savingStrategy)); } public virtual void RaiseEvent<T>(T evnt) where T : class, IRepositoryCommandEvent { Check.NotNull(evnt, "evnt"); if (typeof(EntityAddedEvent).IsAssignableFrom(typeof(T))) { var addedEvent = evnt as EntityAddedEvent; EventHandlers.EntityAddedEventHandler.Handle(addedEvent); ; return; } if (typeof(EntityModifiedEvent).IsAssignableFrom(typeof(T))) { var modifiedEvent = evnt as EntityModifiedEvent; EventHandlers.EntityModifiedEventHandler.Handle(modifiedEvent); ; return; } if (typeof(EntityDeletedEvent).IsAssignableFrom(typeof(T))) { var deletedEvent = evnt as EntityDeletedEvent; EventHandlers.EntityDeletedEventHandler.Handle(deletedEvent); ; return; } if (typeof(RepositorySavedEvent).IsAssignableFrom(typeof(T))) { var addedEvent = evnt as RepositorySavedEvent; EventHandlers.RepositorySavedEventHandler.Handle(addedEvent); ; return; } throw new InvalidOperationException(string.Format("{0} is an unknown CommandEvent", typeof(T).FullName)); } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org 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.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Xna.Framework; namespace Cocos2D { #if !WINDOWS_PHONE && !XBOX && !NETFX_CORE [Serializable, StructLayout(LayoutKind.Sequential), TypeConverter(typeof (CCPointConverter))] #endif public struct CCPoint { public static readonly CCPoint Zero = new CCPoint(0, 0); public static readonly CCPoint AnchorMiddle = new CCPoint(0.5f, 0.5f); public static readonly CCPoint AnchorLowerLeft = new CCPoint(0f, 0f); public static readonly CCPoint AnchorUpperLeft = new CCPoint(0f, 1f); public static readonly CCPoint AnchorLowerRight = new CCPoint(1f, 0f); public static readonly CCPoint AnchorUpperRight = new CCPoint(1f, 1f); public static readonly CCPoint AnchorMiddleRight = new CCPoint(1f, .5f); public static readonly CCPoint AnchorMiddleLeft = new CCPoint(0f, .5f); public static readonly CCPoint AnchorMiddleTop = new CCPoint(.5f, 1f); public static readonly CCPoint AnchorMiddleBottom = new CCPoint(.5f, 0f); public float X; public float Y; public CCPoint(float x, float y) { X = x; Y = y; } public CCPoint(CCPoint pt) { X = pt.X; Y = pt.Y; } public CCPoint(Point pt) { X = pt.X; Y = pt.Y; } public CCPoint(Vector2 v) { X = v.X; Y = v.Y; } public static bool Equal(ref CCPoint point1, ref CCPoint point2) { return ((point1.X == point2.X) && (point1.Y == point2.Y)); } public CCPoint Offset(float dx, float dy) { CCPoint pt; pt.X = X + dx; pt.Y = Y + dy; return pt; } public CCPoint Reverse { get { return new CCPoint(-X, -Y); } } public override int GetHashCode() { return X.GetHashCode() + Y.GetHashCode(); } public override bool Equals(object obj) { return (Equals((CCPoint) obj)); } public bool Equals(CCPoint p) { return X == p.X && Y == p.Y; } public override string ToString() { return String.Format("CCPoint : (x={0}, y={1})", X, Y); } public float DistanceSQ(ref CCPoint v2) { return Sub(ref v2).LengthSQ; } public CCPoint Sub(ref CCPoint v2) { CCPoint pt; pt.X = X - v2.X; pt.Y = Y - v2.Y; return pt; } public float LengthSQ { get { return X * X + Y * Y; } } public float LengthSquare { get { return LengthSQ; } } /// <summary> /// Computes the length of this point as if it were a vector with XY components relative to the /// origin. This is computed each time this property is accessed, so cache the value that is /// returned. /// </summary> public float Length { get { return (float) Math.Sqrt(X * X + Y * Y); } } /// <summary> /// Inverts the direction or location of the Y component. /// </summary> public CCPoint InvertY { get { CCPoint pt; pt.X = X; pt.Y = -Y; return pt; } } /// <summary> /// Normalizes the components of this point (convert to mag 1), and returns the orignial /// magnitude of the vector defined by the XY components of this point. /// </summary> /// <returns></returns> public float Normalize() { var mag = (float) Math.Sqrt(X * X + Y * Y); if (mag < float.Epsilon) { return (0f); } float l = 1f / mag; X *= l; Y *= l; return (mag); } #region Static Methods /** Run a math operation function on each point component * absf, fllorf, ceilf, roundf * any function that has the signature: float func(float); * For example: let's try to take the floor of x,y * ccpCompOp(p,floorf); @since v0.99.1 */ public delegate float ComputationOperationDelegate(float a); public static CCPoint ComputationOperation(CCPoint p, ComputationOperationDelegate del) { CCPoint pt; pt.X = del(p.X); pt.Y = del(p.Y); return pt; } /** Linear Interpolation between two points a and b @returns alpha == 0 ? a alpha == 1 ? b otherwise a value between a..b @since v0.99.1 */ public static CCPoint Lerp(CCPoint a, CCPoint b, float alpha) { return (a * (1f - alpha) + b * alpha); } /** @returns if points have fuzzy equality which means equal with some degree of variance. @since v0.99.1 */ public static bool FuzzyEqual(CCPoint a, CCPoint b, float variance) { if (a.X - variance <= b.X && b.X <= a.X + variance) if (a.Y - variance <= b.Y && b.Y <= a.Y + variance) return true; return false; } /** Multiplies a nd b components, a.X*b.X, a.y*b.y @returns a component-wise multiplication @since v0.99.1 */ public static CCPoint MultiplyComponents(CCPoint a, CCPoint b) { CCPoint pt; pt.X = a.X * b.X; pt.Y = a.Y * b.Y; return pt; } /** @returns the signed angle in radians between two vector directions @since v0.99.1 */ public static float AngleSigned(CCPoint a, CCPoint b) { CCPoint a2 = Normalize(a); CCPoint b2 = Normalize(b); var angle = (float) Math.Atan2(a2.X * b2.Y - a2.Y * b2.X, DotProduct(a2, b2)); if (Math.Abs(angle) < float.Epsilon) { return 0.0f; } return angle; } /** Rotates a point counter clockwise by the angle around a pivot @param v is the point to rotate @param pivot is the pivot, naturally @param angle is the angle of rotation cw in radians @returns the rotated point @since v0.99.1 */ public static CCPoint RotateByAngle(CCPoint v, CCPoint pivot, float angle) { CCPoint r = v - pivot; float cosa = (float) Math.Cos(angle), sina = (float) Math.Sin(angle); float t = r.X; r.X = t * cosa - r.Y * sina + pivot.X; r.Y = t * sina + r.Y * cosa + pivot.Y; return r; } /** A general line-line intersection test @param p1 is the startpoint for the first line P1 = (p1 - p2) @param p2 is the endpoint for the first line P1 = (p1 - p2) @param p3 is the startpoint for the second line P2 = (p3 - p4) @param p4 is the endpoint for the second line P2 = (p3 - p4) @param s is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)) @param t is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)) @return bool indicating successful intersection of a line note that to truly test intersection for segments we have to make sure that s & t lie within [0..1] and for rays, make sure s & t > 0 the hit point is p3 + t * (p4 - p3); the hit point also is p1 + s * (p2 - p1); @since v0.99.1 */ public static bool LineIntersect(CCPoint A, CCPoint B, CCPoint C, CCPoint D, ref float S, ref float T) { // FAIL: Line undefined if ((A.X == B.X && A.Y == B.Y) || (C.X == D.X && C.Y == D.Y)) { return false; } float BAx = B.X - A.X; float BAy = B.Y - A.Y; float DCx = D.X - C.X; float DCy = D.Y - C.Y; float ACx = A.X - C.X; float ACy = A.Y - C.Y; float denom = DCy * BAx - DCx * BAy; S = DCx * ACy - DCy * ACx; T = BAx * ACy - BAy * ACx; if (denom == 0) { if (S == 0 || T == 0) { // Lines incident return true; } // Lines parallel and not incident return false; } S = S / denom; T = T / denom; // Point of intersection // CGPoint P; // P.X = A.X + *S * (B.X - A.X); // P.y = A.y + *S * (B.y - A.y); return true; } /* ccpSegmentIntersect returns YES if Segment A-B intersects with segment C-D @since v1.0.0 */ public static bool SegmentIntersect(CCPoint A, CCPoint B, CCPoint C, CCPoint D) { float S = 0, T = 0; if (LineIntersect(A, B, C, D, ref S, ref T) && (S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f)) { return true; } return false; } /* ccpIntersectPoint returns the intersection point of line A-B, C-D @since v1.0.0 */ public static CCPoint IntersectPoint(CCPoint A, CCPoint B, CCPoint C, CCPoint D) { float S = 0, T = 0; if (LineIntersect(A, B, C, D, ref S, ref T)) { // Point of intersection CCPoint P; P.X = A.X + S * (B.X - A.X); P.Y = A.Y + S * (B.Y - A.Y); return P; } return Zero; } /** Converts radians to a normalized vector. @return CCPoint @since v0.7.2 */ public static CCPoint ForAngle(float a) { CCPoint pt; pt.X = (float) Math.Cos(a); pt.Y = (float) Math.Sin(a); return pt; // return CreatePoint((float)Math.Cos(a), (float)Math.Sin(a)); } /** Converts a vector to radians. @return CGFloat @since v0.7.2 */ public static float ToAngle(CCPoint v) { return (float) Math.Atan2(v.Y, v.X); } /** Clamp a value between from and to. @since v0.99.1 */ public static float Clamp(float value, float min_inclusive, float max_inclusive) { if (min_inclusive > max_inclusive) { float ftmp = min_inclusive; min_inclusive = max_inclusive; max_inclusive = ftmp; } return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; } /** Clamp a point between from and to. @since v0.99.1 */ public static CCPoint Clamp(CCPoint p, CCPoint from, CCPoint to) { CCPoint pt; pt.X = Clamp(p.X, from.X, to.X); pt.Y = Clamp(p.Y, from.Y, to.Y); return pt; // return CreatePoint(Clamp(p.X, from.X, to.X), Clamp(p.Y, from.Y, to.Y)); } /** Quickly convert CCSize to a CCPoint @since v0.99.1 */ [Obsolete("Use explicit cast (CCPoint)size.")] public static CCPoint FromSize(CCSize s) { CCPoint pt; pt.X = s.Width; pt.Y = s.Height; return pt; } /** * Allow Cast CCSize to CCPoint */ public static explicit operator CCPoint(CCSize size) { CCPoint pt; pt.X = size.Width; pt.Y = size.Height; return pt; } public static CCPoint Perp(CCPoint p) { CCPoint pt; pt.X = -p.Y; pt.Y = p.X; return pt; } public static float Dot(CCPoint p1, CCPoint p2) { return p1.X * p2.X + p1.Y * p2.Y; } public static float Distance(CCPoint v1, CCPoint v2) { return (v1 - v2).Length; } public static CCPoint Normalize(CCPoint p) { float x = p.X; float y = p.Y; float l = 1f / (float) Math.Sqrt(x * x + y * y); CCPoint pt; pt.X = x * l; pt.Y = y * l; return pt; } public static CCPoint Midpoint(CCPoint p1, CCPoint p2) { CCPoint pt; pt.X = (p1.X + p2.X) / 2f; pt.Y = (p1.Y + p2.Y) / 2f; return pt; } public static float DotProduct(CCPoint v1, CCPoint v2) { return v1.X * v2.X + v1.Y * v2.Y; } /** Calculates cross product of two points. @return CGFloat @since v0.7.2 */ public static float CrossProduct(CCPoint v1, CCPoint v2) { return v1.X * v2.Y - v1.Y * v2.X; } /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 @return CCPoint @since v0.7.2 */ public static CCPoint PerpendicularCounterClockwise(CCPoint v) { CCPoint pt; pt.X = -v.Y; pt.Y = v.X; return pt; } /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 @return CCPoint @since v0.7.2 */ public static CCPoint PerpendicularClockwise(CCPoint v) { CCPoint pt; pt.X = v.Y; pt.Y = -v.X; return pt; } /** Calculates the projection of v1 over v2. @return CCPoint @since v0.7.2 */ public static CCPoint Project(CCPoint v1, CCPoint v2) { float dp1 = v1.X * v2.X + v1.Y * v2.Y; float dp2 = v2.LengthSQ; float f = dp1 / dp2; CCPoint pt; pt.X = v2.X * f; pt.Y = v2.Y * f; return pt; // return Multiply(v2, DotProduct(v1, v2) / DotProduct(v2, v2)); } /** Rotates two points. @return CCPoint @since v0.7.2 */ public static CCPoint Rotate(CCPoint v1, CCPoint v2) { CCPoint pt; pt.X = v1.X * v2.X - v1.Y * v2.Y; pt.Y = v1.X * v2.Y + v1.Y * v2.X; return pt; } /** Unrotates two points. @return CCPoint @since v0.7.2 */ public static CCPoint Unrotate(CCPoint v1, CCPoint v2) { CCPoint pt; pt.X = v1.X * v2.X + v1.Y * v2.Y; pt.Y = v1.Y * v2.X - v1.X * v2.Y; return pt; } #endregion #region Operator Overloads public static bool operator ==(CCPoint p1, CCPoint p2) { return p1.X == p2.X && p1.Y == p2.Y; } public static bool operator !=(CCPoint p1, CCPoint p2) { return p1.X != p2.X || p1.Y != p2.Y; } public static CCPoint operator -(CCPoint p1, CCPoint p2) { CCPoint pt; pt.X = p1.X - p2.X; pt.Y = p1.Y - p2.Y; return pt; } public static CCPoint operator -(CCPoint p1) { CCPoint pt; pt.X = -p1.X; pt.Y = -p1.Y; return pt; } public static CCPoint operator +(CCPoint p1, CCPoint p2) { CCPoint pt; pt.X = p1.X + p2.X; pt.Y = p1.Y + p2.Y; return pt; } public static CCPoint operator +(CCPoint p1) { CCPoint pt; pt.X = +p1.X; pt.Y = +p1.Y; return pt; } public static CCPoint operator *(CCPoint p, float value) { CCPoint pt; pt.X = p.X * value; pt.Y = p.Y * value; return pt; } public static CCPoint operator /(CCPoint p, float value) { CCPoint pt; pt.X = p.X / value; pt.Y = p.Y / value; return pt; } #endregion public static CCPoint Parse(string s) { #if !WINDOWS_PHONE && !XBOX && !NETFX_CORE return (CCPoint) TypeDescriptor.GetConverter(typeof (CCPoint)).ConvertFromString(s); #else return (CCPointConverter.CCPointFromString(s)); #endif } public static implicit operator Vector2(CCPoint point) { return new Vector2(point.X, point.Y); } public static implicit operator Vector3(CCPoint point) { return new Vector3(point.X, point.Y, 0); } } #if !WINDOWS_PHONE && !XBOX && !NETFX_CORE [Serializable, StructLayout(LayoutKind.Sequential), TypeConverter(typeof (CCSizeConverter))] #endif public struct CCSize { public static readonly CCSize Zero = new CCSize(0, 0); public float Width; public float Height; public CCSize(float width, float height) { Width = width; Height = height; } /// <summary> /// Returns the inversion of this size, which is the height and width swapped. /// </summary> public CCSize Inverted { get { return new CCSize(Height, Width); } } public static bool Equal(ref CCSize size1, ref CCSize size2) { return ((size1.Width == size2.Width) && (size1.Height == size2.Height)); } public override int GetHashCode() { return (Width.GetHashCode() + Height.GetHashCode()); } public bool Equals(CCSize s) { return Width == s.Width && Height == s.Height; } public override bool Equals(object obj) { return (Equals((CCSize) obj)); } public CCPoint Center { get { return new CCPoint(Width / 2f, Height / 2f); } } public override string ToString() { return String.Format("{0} x {1}", Width, Height); } public static bool operator ==(CCSize p1, CCSize p2) { return (p1.Equals(p2)); } public static bool operator !=(CCSize p1, CCSize p2) { return (!p1.Equals(p2)); } public static CCSize operator *(CCSize p, float f) { return (new CCSize(p.Width * f, p.Height * f)); } public static CCSize operator /(CCSize p, float f) { return (new CCSize(p.Width / f, p.Height / f)); } public static CCSize operator +(CCSize p, float f) { return (new CCSize(p.Width + f, p.Height + f)); } public static CCSize operator -(CCSize p, float f) { return (new CCSize(p.Width - f, p.Height - f)); } public static CCSize Parse(string s) { #if !WINDOWS_PHONE && !XBOX && !NETFX_CORE return (CCSize) TypeDescriptor.GetConverter(typeof (CCSize)).ConvertFromString(s); #else return (CCSizeConverter.CCSizeFromString(s)); #endif } /** * Allow Cast CCPoint to CCSize */ public static explicit operator CCSize(CCPoint point) { CCSize size; size.Width = point.X; size.Height = point.Y; return size; } } #if !WINDOWS_PHONE && !XBOX && !NETFX_CORE [Serializable, StructLayout(LayoutKind.Sequential), TypeConverter(typeof (CCRectConverter))] #endif public struct CCRect { public static readonly CCRect Zero = new CCRect(0, 0, 0, 0); public CCPoint Origin; public CCSize Size; /// <summary> /// Creates the rectangle at (x,y) -> (width,height) /// </summary> /// <param name="x">Lower Left corner X</param> /// <param name="y">Lower left corner Y</param> /// <param name="width">width of the rectangle</param> /// <param name="height">height of the rectangle</param> public CCRect(float x, float y, float width, float height) { // Only support that, the width and height > 0 Debug.Assert(width >= 0 && height >= 0); Origin.X = x; Origin.Y = y; Size.Width = width; Size.Height = height; } /// <summary> /// Returns the inversion of this rect's size, which is the height and width swapped, while the origin stays unchanged. /// </summary> public CCRect InvertedSize { get { return new CCRect(Origin.X, Origin.Y, Size.Height, Size.Width); } } // return the rightmost x-value of 'rect' public float MaxX { get { return Origin.X + Size.Width; } } // return the midpoint x-value of 'rect' public float MidX { get { return Origin.X + Size.Width / 2.0f; } } // return the leftmost x-value of 'rect' public float MinX { get { return Origin.X; } } // Return the topmost y-value of 'rect' public float MaxY { get { return Origin.Y + Size.Height; } } // Return the midpoint y-value of 'rect' public float MidY { get { return Origin.Y + Size.Height / 2.0f; } } // Return the bottommost y-value of 'rect' public float MinY { get { return Origin.Y; } } public CCPoint Center { get { CCPoint pt; pt.X = MidX; pt.Y = MidY; return pt; } } public CCPoint UpperRight { get { CCPoint pt; pt.X = MaxX; pt.Y = MaxY; return (pt); } } public CCPoint LowerLeft { get { CCPoint pt; pt.X = MinX; pt.Y = MinY; return (pt); } } public CCRect Intersection(CCRect rect) { if (!IntersectsRect(rect)) { return (Zero); } /* +-------------+ * | | * | +---+-----+ * +-----+---+ | | | * | | | | | | * | | | +---+-----+ * | | | | * | | | | * +-----+---+ | * | | * +-------------+ */ float minx = 0, miny = 0, maxx = 0, maxy = 0; // X if (rect.MinX < MinX) { minx = MinX; } else if (rect.MinX < MaxX) { minx = rect.MinX; } if (rect.MaxX < MaxX) { maxx = rect.MaxX; } else if (rect.MaxX > MaxX) { maxx = MaxX; } // Y if (rect.MinY < MinY) { miny = MinY; } else if (rect.MinY < MaxY) { miny = rect.MinY; } if (rect.MaxY < MaxY) { maxy = rect.MaxY; } else if (rect.MaxY > MaxY) { maxy = MaxY; } return new CCRect(minx, miny, maxx - minx, maxy - miny); } public bool IntersectsRect(CCRect rect) { return !(MaxX < rect.MinX || rect.MaxX < MinX || MaxY < rect.MinY || rect.MaxY < MinY); } public bool IntersectsRect(ref CCRect rect) { return !(MaxX < rect.MinX || rect.MaxX < MinX || MaxY < rect.MinY || rect.MaxY < MinY); } public bool ContainsPoint(CCPoint point) { return point.X >= MinX && point.X <= MaxX && point.Y >= MinY && point.Y <= MaxY; } public bool ContainsPoint(float x, float y) { return x >= MinX && x <= MaxX && y >= MinY && y <= MaxY; } public static bool Equal(ref CCRect rect1, ref CCRect rect2) { return rect1.Origin.Equals(rect2.Origin) && rect1.Size.Equals(rect2.Size); } public static bool ContainsPoint(ref CCRect rect, ref CCPoint point) { bool bRet = false; if (float.IsNaN(point.X)) { point.X = 0; } if (float.IsNaN(point.Y)) { point.Y = 0; } if (point.X >= rect.MinX && point.X <= rect.MaxX && point.Y >= rect.MinY && point.Y <= rect.MaxY) { bRet = true; } return bRet; } public static bool IntersetsRect(ref CCRect rectA, ref CCRect rectB) { return !(rectA.MaxX < rectB.MinX || rectB.MaxX < rectA.MinX || rectA.MaxY < rectB.MinY || rectB.MaxY < rectA.MinY); } public static bool operator ==(CCRect p1, CCRect p2) { return (p1.Equals(p2)); } public static bool operator !=(CCRect p1, CCRect p2) { return (!p1.Equals(p2)); } public override int GetHashCode() { return Origin.GetHashCode() + Size.GetHashCode(); } public override bool Equals(object obj) { return (Equals((CCRect) obj)); } public bool Equals(CCRect rect) { return Origin.Equals(rect.Origin) && Size.Equals(rect.Size); } public override string ToString() { return String.Format("CCRect : (x={0}, y={1}, width={2}, height={3})", Origin.X, Origin.Y, Size.Width, Size.Height); } public static CCRect Parse(string s) { #if !WINDOWS_PHONE && !XBOX && !NETFX_CORE return (CCRect) TypeDescriptor.GetConverter(typeof (CCRect)).ConvertFromString(s); #else return (CCRectConverter.CCRectFromString(s)); #endif } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Math.Splines; using BitmapFont = FlatRedBall.Graphics.BitmapFont; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; #if FRB_XNA || SILVERLIGHT using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; #endif namespace FrbDemoDuckHunt.Entities { public partial class Dog { public void WalkingSniffingThenDiving(Action finishedCallback) { var currentTime = 0.0; //Initial Y = WalkingStartY; X = WalkingStartX; Z = 0; VisibleInstance.Visible = true; XVelocity = WalkingSpeed; this.CurrentState = VariableState.Walking; currentTime += 1.8; //First Sniff this.Set("XVelocity").To(0f).After(currentTime); this.Set("CurrentState").To(VariableState.Sniffing).After(currentTime); currentTime += .9; //2nd Walk this.Set("XVelocity").To(WalkingSpeed).After(currentTime); this.Set("CurrentState").To(VariableState.Walking).After(currentTime); currentTime += 1.8; //2nd Sniff this.Set("XVelocity").To(0f).After(currentTime); this.Set("CurrentState").To(VariableState.Sniffing).After(currentTime); currentTime += .9; //Happy this.Set("CurrentState").To(VariableState.Happy).After(currentTime); currentTime += .4; //Jump this.Set("CurrentState").To(VariableState.Jumping).After(currentTime); this.Set("XVelocity").To(JumpingXSpeed).After(currentTime); this.Set("YVelocity").To(JumpingYSpeed).After(currentTime); this.Call(() => GlobalContent.DogBarkSoundEffect.Play()).After(currentTime); currentTime += .5; this.Set("YAcceleration").To(JumpingYDeceleration).After(currentTime); currentTime += .5; this.Set("Z").To(-2f).After(currentTime); currentTime += 1.8; //Stop this.Set("XVelocity").To(0f).After(currentTime); this.Set("YVelocity").To(0f).After(currentTime); this.Set("YAcceleration").To(0f).After(currentTime); this.VisibleInstance.Set("Visible").To(false).After(currentTime); //Callback this.Call(finishedCallback).After(currentTime); } public void ShortWalkingSniffingThenDiving(Action finishedCallback) { var currentTime = 0.0; //Initial Y = WalkingStartY; X = ShortWalkingLeft; Z = 0; VisibleInstance.Visible = true; XVelocity = WalkingSpeed; this.CurrentState = VariableState.Walking; currentTime += .6; //First Sniff this.Set("XVelocity").To(0f).After(currentTime); this.Set("CurrentState").To(VariableState.Sniffing).After(currentTime); currentTime += .9; //Happy this.Set("CurrentState").To(VariableState.Happy).After(currentTime); currentTime += .4; //Jump this.Set("CurrentState").To(VariableState.Jumping).After(currentTime); this.Set("XVelocity").To(JumpingXSpeed).After(currentTime); this.Set("YVelocity").To(JumpingYSpeed).After(currentTime); this.Call(() => GlobalContent.DogBarkSoundEffect.Play()).After(currentTime); currentTime += .5; this.Set("YAcceleration").To(JumpingYDeceleration).After(currentTime); currentTime += .5; this.Set("Z").To(-2f).After(currentTime); currentTime += 1.8; //Stop this.Set("XVelocity").To(0f).After(currentTime); this.Set("YVelocity").To(0f).After(currentTime); this.Set("YAcceleration").To(0f).After(currentTime); this.VisibleInstance.Set("Visible").To(false).After(currentTime); //Callback this.Call(finishedCallback).After(currentTime); } public void OneDuck(float position, Action finishedCallback) { var currentTime = 0.0; //Initial Y = DuckStartY; X = position > DuckMaxStartX ? DuckMaxStartX : position < DuckMinStartX ? DuckMinStartX : position; Z = -2; XVelocity = 0; YVelocity = DogDuckMoveSpeed; VisibleInstance.Visible = true; CurrentState = VariableState.OneDuck; //Stop At Top currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); //Start Down currentTime += .5; this.Set("YVelocity").To(-DogDuckMoveSpeed).After(currentTime); //Stop currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); this.VisibleInstance.Set("Visible").To(false).After(currentTime); //Callback this.Call(finishedCallback).After(currentTime); GlobalContent.DuckRelease.Play(); } public void TwoDucks(float position, Action finishedCallback) { var currentTime = 0.0; //Initial Y = DuckStartY; X = position > DuckMaxStartX ? DuckMaxStartX : position < DuckMinStartX ? DuckMinStartX : position; Z = -2; XVelocity = 0; YVelocity = DogDuckMoveSpeed; VisibleInstance.Visible = true; CurrentState = VariableState.TwoDucks; //Stop At Top currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); //Start Down currentTime += .5; this.Set("YVelocity").To(-DogDuckMoveSpeed).After(currentTime); //Stop currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); this.VisibleInstance.Set("Visible").To(false).After(currentTime); //Callback this.Call(finishedCallback).After(currentTime); GlobalContent.DuckRelease.Play(); } public void Laugh(Action finishedCallback) { var currentTime = 0.0; //Initial Y = DuckStartY; X = 0; Z = -2; XVelocity = 0; YVelocity = DogDuckMoveSpeed; VisibleInstance.Visible = true; CurrentState = VariableState.Laughing; //Stop At Top currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); //Start Down currentTime += .5; this.Set("YVelocity").To(-DogDuckMoveSpeed).After(currentTime); //Stop currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); this.VisibleInstance.Set("Visible").To(false).After(currentTime); //Callback this.Call(finishedCallback).After(currentTime); GlobalContent.DogLaughingSoundEffect.Play(); } public void EndGame(Action finishedCallback) { var currentTime = 0.0; //Initial Y = DuckStartY; X = 0; Z = -2; XVelocity = 0; YVelocity = DogDuckMoveSpeed; VisibleInstance.Visible = true; CurrentState = VariableState.Laughing; //Stop At Top currentTime += .5; this.Set("YVelocity").To(0f).After(currentTime); //Callback currentTime += 4; this.Call(finishedCallback).After(currentTime); } private void CustomInitialize() { } private void CustomActivity() { } private void CustomDestroy() { } private static void CustomLoadStaticContent(string contentManagerName) { } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// CommonAddress /// </summary> [DataContract] public partial class CommonAddress : IEquatable<CommonAddress> { /// <summary> /// Initializes a new instance of the <see cref="CommonAddress" /> class. /// </summary> /// <param name="ObjectId">ObjectId.</param> /// <param name="MainAddressLine">MainAddressLine.</param> /// <param name="AddressLastLine">AddressLastLine.</param> /// <param name="PlaceName">PlaceName.</param> /// <param name="AreaName1">AreaName1.</param> /// <param name="AreaName2">AreaName2.</param> /// <param name="AreaName3">AreaName3.</param> /// <param name="AreaName4">AreaName4.</param> /// <param name="PostCode">PostCode.</param> /// <param name="PostCodeExt">PostCodeExt.</param> /// <param name="Country">Country.</param> /// <param name="AddressNumber">AddressNumber.</param> /// <param name="StreetName">StreetName.</param> /// <param name="UnitType">UnitType.</param> /// <param name="UnitValue">UnitValue.</param> public CommonAddress(string ObjectId = null, string MainAddressLine = null, string AddressLastLine = null, string PlaceName = null, string AreaName1 = null, string AreaName2 = null, string AreaName3 = null, string AreaName4 = null, string PostCode = null, string PostCodeExt = null, string Country = null, string AddressNumber = null, string StreetName = null, string UnitType = null, string UnitValue = null) { this.ObjectId = ObjectId; this.MainAddressLine = MainAddressLine; this.AddressLastLine = AddressLastLine; this.PlaceName = PlaceName; this.AreaName1 = AreaName1; this.AreaName2 = AreaName2; this.AreaName3 = AreaName3; this.AreaName4 = AreaName4; this.PostCode = PostCode; this.PostCodeExt = PostCodeExt; this.Country = Country; this.AddressNumber = AddressNumber; this.StreetName = StreetName; this.UnitType = UnitType; this.UnitValue = UnitValue; } /// <summary> /// Gets or Sets ObjectId /// </summary> [DataMember(Name="objectId", EmitDefaultValue=false)] public string ObjectId { get; set; } /// <summary> /// Gets or Sets MainAddressLine /// </summary> [DataMember(Name="mainAddressLine", EmitDefaultValue=false)] public string MainAddressLine { get; set; } /// <summary> /// Gets or Sets AddressLastLine /// </summary> [DataMember(Name="addressLastLine", EmitDefaultValue=false)] public string AddressLastLine { get; set; } /// <summary> /// Gets or Sets PlaceName /// </summary> [DataMember(Name="placeName", EmitDefaultValue=false)] public string PlaceName { get; set; } /// <summary> /// Gets or Sets AreaName1 /// </summary> [DataMember(Name="areaName1", EmitDefaultValue=false)] public string AreaName1 { get; set; } /// <summary> /// Gets or Sets AreaName2 /// </summary> [DataMember(Name="areaName2", EmitDefaultValue=false)] public string AreaName2 { get; set; } /// <summary> /// Gets or Sets AreaName3 /// </summary> [DataMember(Name="areaName3", EmitDefaultValue=false)] public string AreaName3 { get; set; } /// <summary> /// Gets or Sets AreaName4 /// </summary> [DataMember(Name="areaName4", EmitDefaultValue=false)] public string AreaName4 { get; set; } /// <summary> /// Gets or Sets PostCode /// </summary> [DataMember(Name="postCode", EmitDefaultValue=false)] public string PostCode { get; set; } /// <summary> /// Gets or Sets PostCodeExt /// </summary> [DataMember(Name="postCodeExt", EmitDefaultValue=false)] public string PostCodeExt { get; set; } /// <summary> /// Gets or Sets Country /// </summary> [DataMember(Name="country", EmitDefaultValue=false)] public string Country { get; set; } /// <summary> /// Gets or Sets AddressNumber /// </summary> [DataMember(Name="addressNumber", EmitDefaultValue=false)] public string AddressNumber { get; set; } /// <summary> /// Gets or Sets StreetName /// </summary> [DataMember(Name="streetName", EmitDefaultValue=false)] public string StreetName { get; set; } /// <summary> /// Gets or Sets UnitType /// </summary> [DataMember(Name="unitType", EmitDefaultValue=false)] public string UnitType { get; set; } /// <summary> /// Gets or Sets UnitValue /// </summary> [DataMember(Name="unitValue", EmitDefaultValue=false)] public string UnitValue { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CommonAddress {\n"); sb.Append(" ObjectId: ").Append(ObjectId).Append("\n"); sb.Append(" MainAddressLine: ").Append(MainAddressLine).Append("\n"); sb.Append(" AddressLastLine: ").Append(AddressLastLine).Append("\n"); sb.Append(" PlaceName: ").Append(PlaceName).Append("\n"); sb.Append(" AreaName1: ").Append(AreaName1).Append("\n"); sb.Append(" AreaName2: ").Append(AreaName2).Append("\n"); sb.Append(" AreaName3: ").Append(AreaName3).Append("\n"); sb.Append(" AreaName4: ").Append(AreaName4).Append("\n"); sb.Append(" PostCode: ").Append(PostCode).Append("\n"); sb.Append(" PostCodeExt: ").Append(PostCodeExt).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" AddressNumber: ").Append(AddressNumber).Append("\n"); sb.Append(" StreetName: ").Append(StreetName).Append("\n"); sb.Append(" UnitType: ").Append(UnitType).Append("\n"); sb.Append(" UnitValue: ").Append(UnitValue).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CommonAddress); } /// <summary> /// Returns true if CommonAddress instances are equal /// </summary> /// <param name="other">Instance of CommonAddress to be compared</param> /// <returns>Boolean</returns> public bool Equals(CommonAddress other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ObjectId == other.ObjectId || this.ObjectId != null && this.ObjectId.Equals(other.ObjectId) ) && ( this.MainAddressLine == other.MainAddressLine || this.MainAddressLine != null && this.MainAddressLine.Equals(other.MainAddressLine) ) && ( this.AddressLastLine == other.AddressLastLine || this.AddressLastLine != null && this.AddressLastLine.Equals(other.AddressLastLine) ) && ( this.PlaceName == other.PlaceName || this.PlaceName != null && this.PlaceName.Equals(other.PlaceName) ) && ( this.AreaName1 == other.AreaName1 || this.AreaName1 != null && this.AreaName1.Equals(other.AreaName1) ) && ( this.AreaName2 == other.AreaName2 || this.AreaName2 != null && this.AreaName2.Equals(other.AreaName2) ) && ( this.AreaName3 == other.AreaName3 || this.AreaName3 != null && this.AreaName3.Equals(other.AreaName3) ) && ( this.AreaName4 == other.AreaName4 || this.AreaName4 != null && this.AreaName4.Equals(other.AreaName4) ) && ( this.PostCode == other.PostCode || this.PostCode != null && this.PostCode.Equals(other.PostCode) ) && ( this.PostCodeExt == other.PostCodeExt || this.PostCodeExt != null && this.PostCodeExt.Equals(other.PostCodeExt) ) && ( this.Country == other.Country || this.Country != null && this.Country.Equals(other.Country) ) && ( this.AddressNumber == other.AddressNumber || this.AddressNumber != null && this.AddressNumber.Equals(other.AddressNumber) ) && ( this.StreetName == other.StreetName || this.StreetName != null && this.StreetName.Equals(other.StreetName) ) && ( this.UnitType == other.UnitType || this.UnitType != null && this.UnitType.Equals(other.UnitType) ) && ( this.UnitValue == other.UnitValue || this.UnitValue != null && this.UnitValue.Equals(other.UnitValue) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ObjectId != null) hash = hash * 59 + this.ObjectId.GetHashCode(); if (this.MainAddressLine != null) hash = hash * 59 + this.MainAddressLine.GetHashCode(); if (this.AddressLastLine != null) hash = hash * 59 + this.AddressLastLine.GetHashCode(); if (this.PlaceName != null) hash = hash * 59 + this.PlaceName.GetHashCode(); if (this.AreaName1 != null) hash = hash * 59 + this.AreaName1.GetHashCode(); if (this.AreaName2 != null) hash = hash * 59 + this.AreaName2.GetHashCode(); if (this.AreaName3 != null) hash = hash * 59 + this.AreaName3.GetHashCode(); if (this.AreaName4 != null) hash = hash * 59 + this.AreaName4.GetHashCode(); if (this.PostCode != null) hash = hash * 59 + this.PostCode.GetHashCode(); if (this.PostCodeExt != null) hash = hash * 59 + this.PostCodeExt.GetHashCode(); if (this.Country != null) hash = hash * 59 + this.Country.GetHashCode(); if (this.AddressNumber != null) hash = hash * 59 + this.AddressNumber.GetHashCode(); if (this.StreetName != null) hash = hash * 59 + this.StreetName.GetHashCode(); if (this.UnitType != null) hash = hash * 59 + this.UnitType.GetHashCode(); if (this.UnitValue != null) hash = hash * 59 + this.UnitValue.GetHashCode(); return hash; } } } }
// SqlDataTimeTest.cs - NUnit Test Cases for [explain here] // // Authors: // Ville Palo ([email protected]) // Martin Willemoes Hansen // // (C) Ville Palo // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // 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 NUnit.Framework; using System; using System.Data.SqlTypes; using System.Threading; using System.Globalization; namespace MonoTests.System.Data.SqlTypes { [TestFixture] public class SqlBooleanTest : Assertion { private SqlBoolean SqlTrue; private SqlBoolean SqlFalse; [SetUp] public void GetReady() { Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US"); SqlTrue = new SqlBoolean(true); SqlFalse = new SqlBoolean(false); } [Test] public void Create () { SqlBoolean SqlTrue2 = new SqlBoolean(1); SqlBoolean SqlFalse2 = new SqlBoolean(0); Assert("Creation of SqlBoolean failed", SqlTrue.Value); Assert("Creation of SqlBoolean failed", SqlTrue2.Value); Assert("Creation of SqlBoolean failed", !SqlFalse.Value); Assert("Creation of SqlBoolean failed", !SqlFalse2.Value); } //// // PUBLIC STATIC METHODS // // And [Test] public void And() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); // One result value SqlBoolean sqlResult; // true && false sqlResult = SqlBoolean.And(SqlTrue, SqlFalse); Assert("And method does not work correctly (true && false)", !sqlResult.Value); sqlResult = SqlBoolean.And(SqlFalse, SqlTrue); Assert("And method does not work correctly (false && true)", !sqlResult.Value); // true && true sqlResult = SqlBoolean.And(SqlTrue, SqlTrue2); Assert("And method does not work correctly (true && true)", sqlResult.Value); sqlResult = SqlBoolean.And(SqlTrue, SqlTrue); Assert("And method does not work correctly (true && true2)", sqlResult.Value); // false && false sqlResult = SqlBoolean.And(SqlFalse, SqlFalse2); Assert("And method does not work correctly (false && false)", !sqlResult.Value); sqlResult = SqlBoolean.And(SqlFalse, SqlFalse); Assert("And method does not work correctly (false && false2)", !sqlResult.Value); } // NotEquals [Test] public void NotEquals() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; // true != false SqlResult = SqlBoolean.NotEquals(SqlTrue, SqlFalse); Assert("NotEquals method does not work correctly (true != false)", SqlResult.Value); SqlResult = SqlBoolean.NotEquals(SqlFalse, SqlTrue); Assert("NotEquals method does not work correctly (false != true)", SqlResult.Value); // true != true SqlResult = SqlBoolean.NotEquals(SqlTrue, SqlTrue); Assert("NotEquals method does not work correctly (true != true)", !SqlResult.Value); SqlResult = SqlBoolean.NotEquals(SqlTrue, SqlTrue2); Assert("NotEquals method does not work correctly (true != true2)", !SqlResult.Value); // false != false SqlResult = SqlBoolean.NotEquals(SqlFalse, SqlFalse); Assert("NotEquals method does not work correctly (false != false)", !SqlResult.Value); SqlResult = SqlBoolean.NotEquals(SqlTrue, SqlTrue2); Assert("NotEquals method does not work correctly (false != false2)", !SqlResult.Value); // If either instance of SqlBoolean is null, the Value of the SqlBoolean will be Null. SqlResult = SqlBoolean.NotEquals(SqlBoolean.Null, SqlFalse); Assert("NotEquals method does not work correctly (Null != false)", SqlResult.IsNull); SqlResult = SqlBoolean.NotEquals(SqlTrue, SqlBoolean.Null); Assert("NotEquals method does not work correctly (false != Null)", SqlResult.IsNull); } // OnesComplement [Test] public void OnesComplement() { SqlBoolean SqlFalse2 = SqlBoolean.OnesComplement(SqlTrue); Assert("OnesComplement method does not work correctly", !SqlFalse2.Value); SqlBoolean SqlTrue2 = SqlBoolean.OnesComplement(SqlFalse); Assert("OnesComplement method does not work correctly", SqlTrue2.Value); } // Or [Test] public void Or() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; // true || false SqlResult = SqlBoolean.Or(SqlTrue, SqlFalse); Assert("Or method does not work correctly (true || false)", SqlResult.Value); SqlResult = SqlBoolean.Or(SqlFalse, SqlTrue); Assert("Or method does not work correctly (false || true)", SqlResult.Value); // true || true SqlResult = SqlBoolean.Or(SqlTrue, SqlTrue); Assert("Or method does not work correctly (true || true)", SqlResult.Value); SqlResult = SqlBoolean.Or(SqlTrue, SqlTrue2); Assert("Or method does not work correctly (true || true2)", SqlResult.Value); // false || false SqlResult = SqlBoolean.Or(SqlFalse, SqlFalse); Assert("Or method does not work correctly (false || false)", !SqlResult.Value); SqlResult = SqlBoolean.Or(SqlFalse, SqlFalse2); Assert("Or method does not work correctly (false || false2)", !SqlResult.Value); } // Parse [Test] public void Parse() { String error = "Parse method does not work correctly "; Assert(error + "(\"True\")", SqlBoolean.Parse("True").Value); Assert(error + "(\" True\")", SqlBoolean.Parse(" True").Value); Assert(error + "(\"True \")", SqlBoolean.Parse("True ").Value); Assert(error + "(\"tRue\")", SqlBoolean.Parse("tRuE").Value); Assert(error + "(\"False\")", !SqlBoolean.Parse("False").Value); Assert(error + "(\" False\")", !SqlBoolean.Parse(" False").Value); Assert(error + "(\"False \")", !SqlBoolean.Parse("False ").Value); Assert(error + "(\"fAlSe\")", !SqlBoolean.Parse("fAlSe").Value); } // Xor [Test] public void Xor() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; // true ^ false SqlResult = SqlBoolean.Xor(SqlTrue, SqlFalse); Assert("Xor method does not work correctly (true ^ false)", SqlResult.Value); SqlResult = SqlBoolean.Xor(SqlFalse, SqlTrue); Assert("Xor method does not work correctly (false ^ true)", SqlResult.Value); // true ^ true SqlResult = SqlBoolean.Xor(SqlTrue, SqlTrue2); Assert("Xor method does not work correctly (true ^ true)", !SqlResult.Value); // false ^ false SqlResult = SqlBoolean.Xor(SqlFalse, SqlFalse2); Assert("Xor method does not work correctly (false ^ false)", !SqlResult.Value); } // static Equals [Test] public void StaticEquals() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); String error = "Static Equals method does not work correctly "; Assert(error + "(true == true)", SqlBoolean.Equals(SqlTrue, SqlTrue2).Value); Assert(error + "(false == false)", SqlBoolean.Equals(SqlFalse, SqlFalse2).Value); Assert(error + "(true == false)", !SqlBoolean.Equals(SqlTrue, SqlFalse).Value); Assert(error + "(false == true)", !SqlBoolean.Equals(SqlFalse, SqlTrue).Value); AssertEquals(error + "(null == false)", SqlBoolean.Null, SqlBoolean.Equals(SqlBoolean.Null, SqlFalse)); AssertEquals(error + "(true == null)", SqlBoolean.Null, SqlBoolean.Equals(SqlTrue, SqlBoolean.Null)); } // // END OF STATIC METHODS //// //// // PUBLIC METHODS // // CompareTo [Test] public void CompareTo() { String error = "CompareTo method does not work correctly"; Assert(error, (SqlTrue.CompareTo(SqlBoolean.Null) > 0)); Assert(error, (SqlTrue.CompareTo(SqlFalse) > 0)); Assert(error, (SqlFalse.CompareTo(SqlTrue) < 0)); Assert(error, (SqlFalse.CompareTo(SqlFalse) == 0)); } // Equals [Test] public void Equals() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); String error = "Equals method does not work correctly "; Assert(error + "(true == true)", SqlTrue.Equals(SqlTrue2)); Assert(error + "(false == false)", SqlFalse.Equals(SqlFalse2)); Assert(error + "(true == false)", !SqlTrue.Equals(SqlFalse)); Assert(error + "(false == true)", !SqlFalse.Equals(SqlTrue)); Assert(error + "(true == false)", !SqlTrue.Equals(null)); } [Test] public void GetHashCodeTest() { AssertEquals("GetHashCode method does not work correctly", 1, SqlTrue.GetHashCode()); AssertEquals("GetHashCode method does not work correctly", 0, SqlFalse.GetHashCode()); } // GetType [Test] public void GetTypeTest() { AssertEquals("GetType method does not work correctly", SqlTrue.GetType().ToString(), "System.Data.SqlTypes.SqlBoolean"); } // ToSqlByte [Test] public void ToSqlByte() { SqlByte SqlTestByte; String error = "ToSqlByte method does not work correctly "; SqlTestByte = SqlTrue.ToSqlByte(); AssertEquals(error, (byte)1,SqlTestByte.Value); SqlTestByte = SqlFalse.ToSqlByte(); AssertEquals(error, (byte)0, SqlTestByte.Value); } // ToSqlDecimal [Test] public void ToSqlDecimal() { SqlDecimal SqlTestDecimal; String error = "ToSqlDecimal method does not work correctly "; SqlTestDecimal = SqlTrue.ToSqlDecimal(); AssertEquals(error, (decimal)1, SqlTestDecimal.Value); SqlTestDecimal = SqlFalse.ToSqlDecimal(); AssertEquals(error, (decimal)0, SqlTestDecimal.Value); } // ToSqlDouble [Test] public void ToSqlDouble() { SqlDouble SqlTestDouble; String error = "ToSqlDouble method does not work correctly "; SqlTestDouble = SqlTrue.ToSqlDouble(); AssertEquals(error, (double)1, SqlTestDouble.Value); SqlTestDouble = SqlFalse.ToSqlDouble(); AssertEquals(error, (double)0, SqlTestDouble.Value); } // ToSqlInt16 [Test] public void ToSqlInt16() { SqlInt16 SqlTestInt16; String error = "ToSqlInt16 method does not work correctly "; SqlTestInt16 = SqlTrue.ToSqlInt16(); AssertEquals(error, (short)1, SqlTestInt16.Value); SqlTestInt16 = SqlFalse.ToSqlInt16(); AssertEquals(error, (short)0, SqlTestInt16.Value); } // ToSqlInt32 [Test] public void ToSqlInt32() { SqlInt32 SqlTestInt32; String error = "ToSqlInt32 method does not work correctly "; SqlTestInt32 = SqlTrue.ToSqlInt32(); AssertEquals(error, (int)1, SqlTestInt32.Value); SqlTestInt32 = SqlFalse.ToSqlInt32(); AssertEquals(error, (int)0, SqlTestInt32.Value); } // ToSqlInt64 [Test] public void ToSqlInt64() { SqlInt64 SqlTestInt64; String error = "ToSqlInt64 method does not work correctly "; SqlTestInt64 = SqlTrue.ToSqlInt64(); AssertEquals(error, (long)1, SqlTestInt64.Value); SqlTestInt64 = SqlFalse.ToSqlInt64(); AssertEquals(error, (long)0, SqlTestInt64.Value); } // ToSqlMoney [Test] public void ToSqlMoney() { SqlMoney SqlTestMoney; String error = "ToSqlMoney method does not work correctly "; SqlTestMoney = SqlTrue.ToSqlMoney(); AssertEquals(error, 1.0000M, SqlTestMoney.Value); SqlTestMoney = SqlFalse.ToSqlMoney(); AssertEquals(error, (decimal)0, SqlTestMoney.Value); } // ToSqlSingle [Test] public void ToSqlsingle() { SqlSingle SqlTestSingle; String error = "ToSqlSingle method does not work correctly "; SqlTestSingle = SqlTrue.ToSqlSingle(); AssertEquals(error, (float)1, SqlTestSingle.Value); SqlTestSingle = SqlFalse.ToSqlSingle(); AssertEquals(error, (float)0, SqlTestSingle.Value); } // ToSqlString [Test] public void ToSqlString() { SqlString SqlTestString; String error = "ToSqlString method does not work correctly "; SqlTestString = SqlTrue.ToSqlString(); AssertEquals(error, "True", SqlTestString.Value); SqlTestString = SqlFalse.ToSqlString(); AssertEquals(error, "False", SqlTestString.Value); } // ToString [Test] public void ToStringTest() { SqlString TestString; String error = "ToString method does not work correctly "; TestString = SqlTrue.ToString(); AssertEquals(error, "True", TestString.Value); TestString = SqlFalse.ToSqlString(); AssertEquals(error, "False", TestString.Value); } // END OF PUBLIC METHODS //// //// // OPERATORS // BitwixeAnd operator [Test] public void BitwiseAndOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; String error = "BitwiseAnd operator does not work correctly "; SqlResult = SqlTrue & SqlFalse; Assert(error + "(true & false)", !SqlResult.Value); SqlResult = SqlFalse & SqlTrue; Assert(error + "(false & true)", !SqlResult.Value); SqlResult = SqlTrue & SqlTrue2; Assert(error + "(true & true)", SqlResult.Value); SqlResult = SqlFalse & SqlFalse2; Assert(error + "(false & false)", !SqlResult.Value); } // BitwixeOr operator [Test] public void BitwiseOrOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; String error = "BitwiseOr operator does not work correctly "; SqlResult = SqlTrue | SqlFalse; Assert(error + "(true | false)", SqlResult.Value); SqlResult = SqlFalse | SqlTrue; Assert(error + "(false | true)", SqlResult.Value); SqlResult = SqlTrue | SqlTrue2; Assert(error + "(true | true)", SqlResult.Value); SqlResult = SqlFalse | SqlFalse2; Assert(error + "(false | false)", !SqlResult.Value); } // Equality operator [Test] public void EqualityOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; String error = "Equality operator does not work correctly "; SqlResult = SqlTrue == SqlFalse; Assert(error + "(true == false)", !SqlResult.Value); SqlResult = SqlFalse == SqlTrue; Assert(error + "(false == true)", !SqlResult.Value); SqlResult = SqlTrue == SqlTrue2; Assert(error + "(true == true)", SqlResult.Value); SqlResult = SqlFalse == SqlFalse2; Assert(error + "(false == false)", SqlResult.Value); SqlResult = SqlFalse == SqlBoolean.Null; Assert(error + "(false == Null)", SqlResult.IsNull); SqlResult = SqlBoolean.Null == SqlBoolean.Null; Assert(error + "(Null == true)", SqlResult.IsNull); } // ExlusiveOr operator [Test] public void ExlusiveOrOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; String error = "ExclusiveOr operator does not work correctly "; SqlResult = SqlTrue ^ SqlFalse; Assert(error + "(true ^ false)", SqlResult.Value); SqlResult = SqlFalse | SqlTrue; Assert(error + "(false ^ true)", SqlResult.Value); SqlResult = SqlTrue ^ SqlTrue2; Assert(error + "(true ^ true)", !SqlResult.Value); SqlResult = SqlFalse ^ SqlFalse2; Assert(error + "(false ^ false)", !SqlResult.Value); } // false operator [Test] public void FalseOperator() { String error = "false operator does not work correctly "; AssertEquals(error + "(true)", SqlBoolean.False, (!SqlTrue)); AssertEquals(error + "(false)", SqlBoolean.True, (!SqlFalse)); } // Inequality operator [Test] public void InequalityOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); String error = "Inequality operator does not work correctly" ; AssertEquals(error + "(true != true)", SqlBoolean.False, SqlTrue != SqlTrue); AssertEquals(error + "(true != true)", SqlBoolean.False, SqlTrue != SqlTrue2); AssertEquals(error + "(false != false)", SqlBoolean.False, SqlFalse != SqlFalse); AssertEquals(error + "(false != false)", SqlBoolean.False, SqlFalse != SqlFalse2); AssertEquals(error + "(true != false)", SqlBoolean.True, SqlTrue != SqlFalse); AssertEquals(error + "(false != true)", SqlBoolean.True, SqlFalse != SqlTrue); AssertEquals(error + "(null != true)", SqlBoolean.Null, SqlBoolean.Null != SqlTrue); AssertEquals(error + "(false != null)", SqlBoolean.Null, SqlFalse != SqlBoolean.Null); } // Logical Not operator [Test] public void LogicalNotOperator() { String error = "Logical Not operator does not work correctly" ; AssertEquals(error + "(true)", SqlBoolean.False, !SqlTrue); AssertEquals(error + "(false)", SqlBoolean.True, !SqlFalse); } // OnesComplement operator [Test] public void OnesComplementOperator() { String error = "Ones complement operator does not work correctly" ; SqlBoolean SqlResult; SqlResult = ~SqlTrue; Assert(error + "(true)", !SqlResult.Value); SqlResult = ~SqlFalse; Assert(error + "(false)", SqlResult.Value); } // true operator [Test] public void TrueOperator() { String error = "true operator does not work correctly "; AssertEquals(error + "(true)", SqlBoolean.True, (SqlTrue)); AssertEquals(error + "(false)", SqlBoolean.False, (SqlFalse)); } // SqlBoolean to Boolean [Test] public void SqlBooleanToBoolean() { String error = "SqlBooleanToBoolean operator does not work correctly "; Boolean TestBoolean = (Boolean)SqlTrue; Assert(error + "(true)", TestBoolean); TestBoolean = (Boolean)SqlFalse; Assert(error + "(false)", !TestBoolean); } // SqlByte to SqlBoolean [Test] public void SqlByteToSqlBoolean() { SqlByte SqlTestByte; SqlBoolean SqlTestBoolean; String error = "SqlByteToSqlBoolean operator does not work correctly "; SqlTestByte = new SqlByte(1); SqlTestBoolean = (SqlBoolean)SqlTestByte; Assert(error + "(true)", SqlTestBoolean.Value); SqlTestByte = new SqlByte(2); SqlTestBoolean = (SqlBoolean)SqlTestByte; Assert(error + "(true)", SqlTestBoolean.Value); SqlTestByte = new SqlByte(0); SqlTestBoolean = (SqlBoolean)SqlTestByte; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlDecimal to SqlBoolean [Test] public void SqlDecimalToSqlBoolean() { SqlDecimal SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlDecimalToSqlBoolean operator does not work correctly "; SqlTest = new SqlDecimal(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlDecimal(19); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlDecimal(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlDouble to SqlBoolean [Test] public void SqlDoubleToSqlBoolean() { SqlDouble SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlDoubleToSqlBoolean operator does not work correctly "; SqlTest = new SqlDouble(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlDouble(-19.8); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlDouble(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlIn16 to SqlBoolean [Test] public void SqlInt16ToSqlBoolean() { SqlInt16 SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlInt16ToSqlBoolean operator does not work correctly "; SqlTest = new SqlInt16(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlInt16(-143); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlInt16(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlInt32 to SqlBoolean [Test] public void SqlInt32ToSqlBoolean() { SqlInt32 SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlInt32ToSqlBoolean operator does not work correctly "; SqlTest = new SqlInt32(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlInt32(1430); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlInt32(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlInt64 to SqlBoolean [Test] public void SqlInt64ToSqlBoolean() { SqlInt64 SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlInt64ToSqlBoolean operator does not work correctly "; SqlTest = new SqlInt64(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlInt64(-14305); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlInt64(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlMoney to SqlBoolean [Test] public void SqlMoneyToSqlBoolean() { SqlMoney SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlMoneyToSqlBoolean operator does not work correctly "; SqlTest = new SqlMoney(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlMoney(1305); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlMoney(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlSingle to SqlBoolean [Test] public void SqlSingleToSqlBoolean() { SqlSingle SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlSingleToSqlBoolean operator does not work correctly "; SqlTest = new SqlSingle(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlSingle(1305); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlSingle(-305.3); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlSingle(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // SqlString to SqlBoolean [Test] public void SqlStringToSqlBoolean() { SqlString SqlTest; SqlBoolean SqlTestBoolean; String error = "SqlSingleToSqlBoolean operator does not work correctly "; SqlTest = new SqlString("true"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlString("TRUE"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlString("True"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = new SqlString("false"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); } // Boolean to SqlBoolean [Test] public void BooleanToSqlBoolean() { SqlBoolean SqlTestBoolean; bool btrue = true; bool bfalse = false; String error = "BooleanToSqlBoolean operator does not work correctly "; Boolean SqlTest = true; SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(true)", SqlTestBoolean.Value); SqlTestBoolean = (SqlBoolean)btrue; Assert(error + "(true)", SqlTestBoolean.Value); SqlTest = false; SqlTestBoolean = (SqlBoolean)SqlTest; Assert(error + "(false)", !SqlTestBoolean.Value); SqlTestBoolean = (SqlBoolean)bfalse; Assert(error + "(false)", !SqlTestBoolean.Value); } // END OF OPERATORS //// //// // PROPERTIES // ByteValue property [Test] public void ByteValueProperty() { String error = "ByteValue property does not work correctly "; AssertEquals(error + "(true)", (byte)1, SqlTrue.ByteValue); AssertEquals(error + "(false)", (byte)0, SqlFalse.ByteValue); } // IsFalse property [Test] public void IsFalseProperty() { String error = "IsFalse property does not work correctly "; Assert(error + "(true)", !SqlTrue.IsFalse); Assert(error + "(false)", SqlFalse.IsFalse); } // IsNull property [Test] public void IsNullProperty() { String error = "IsNull property does not work correctly "; Assert(error + "(true)", !SqlTrue.IsNull); Assert(error + "(false)", !SqlFalse.IsNull); Assert(error + "(Null)", SqlBoolean.Null.IsNull); } // IsTrue property [Test] public void IsTrueProperty() { String error = "IsTrue property does not work correctly "; Assert(error + "(true)", SqlTrue.IsTrue); Assert(error + "(false)", !SqlFalse.IsTrue); } // Value property [Test] public void ValueProperty() { String error = "Value property does not work correctly "; Assert(error + "(true)", SqlTrue.Value); Assert(error + "(false)", !SqlFalse.Value); } // END OF PROPERTIEs //// //// // FIELDS [Test] public void FalseField() { Assert("False field does not work correctly", !SqlBoolean.False.Value); } [Test] public void NullField() { Assert("Null field does not work correctly", SqlBoolean.Null.IsNull); } [Test] public void OneField() { AssertEquals("One field does not work correctly", (byte)1, SqlBoolean.One.ByteValue); } [Test] public void TrueField() { Assert("True field does not work correctly", SqlBoolean.True.Value); } [Test] public void ZeroField() { AssertEquals("Zero field does not work correctly", (byte)0, SqlBoolean.Zero.ByteValue); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Data; using System.Data.SqlServerCe; using System.IO; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// An Elmah <see cref="ErrorLog"/> implementation that uses SQL Server Compact 4 as its backing store. /// </summary> public class SqlCompactErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SqlCompactErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SqlCompactErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new Elmah.ApplicationException("Connection string is missing for the SQL Server Compact error log."); _connectionString = connectionString; InitializeDatabase(); if (config.Contains("applicationName") && !string.IsNullOrEmpty(config["applicationName"].ToString())) { ApplicationName = config["applicationName"].ToString(); } } /// <summary> /// Initializes a new instance of the <see cref="SqlCompactErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SqlCompactErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; InitializeDatabase(); } private static readonly object _lock = new object(); private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(dbFilePath)) return; using (SqlCeEngine engine = new SqlCeEngine(ConnectionString)) { engine.CreateDatabase(); } const string sql1 = @" CREATE TABLE ELMAH_Error ( [ErrorId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(), [Application] NVARCHAR(60) NOT NULL, [Host] NVARCHAR(50) NOT NULL, [Type] NVARCHAR(100) NOT NULL, [Source] NVARCHAR(60) NOT NULL, [Message] NVARCHAR(500) NOT NULL, [User] NVARCHAR(50) NOT NULL, [StatusCode] INT NOT NULL, [TimeUtc] DATETIME NOT NULL, [Sequence] INT IDENTITY (1, 1) NOT NULL, [AllXml] NTEXT NOT NULL )"; const string sql2 = @" CREATE NONCLUSTERED INDEX [IX_Error_App_Time_Seq] ON [ELMAH_Error] ( [Application] ASC, [TimeUtc] DESC, [Sequence] DESC )"; using (SqlCeConnection conn = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand cmd = new SqlCeCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = sql1; cmd.ExecuteNonQuery(); cmd.CommandText = sql2; cmd.ExecuteNonQuery(); } } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQL Server Compact 4 Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); const string query = @" INSERT INTO ELMAH_Error ( [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [StatusCode], [TimeUtc], [AllXml] ) VALUES ( @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml);"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand command = new SqlCeCommand(query, connection)) { SqlCeParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id; parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName; parameters.Add("@Host", SqlDbType.NVarChar, 30).Value = error.HostName; parameters.Add("@Type", SqlDbType.NVarChar, 100).Value = error.Type; parameters.Add("@Source", SqlDbType.NVarChar, 60).Value = error.Source; parameters.Add("@Message", SqlDbType.NVarChar, 500).Value = error.Message; parameters.Add("@User", SqlDbType.NVarChar, 50).Value = error.User; parameters.Add("@StatusCode", SqlDbType.Int).Value = error.StatusCode; parameters.Add("@TimeUtc", SqlDbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", SqlDbType.NText).Value = errorXml; command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); return id.ToString(); } } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> /// public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [StatusCode], [TimeUtc] FROM [ELMAH_Error] WHERE [Application] = @Application ORDER BY [TimeUtc] DESC, [Sequence] DESC OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY; "; const string getCount = @" SELECT COUNT(*) FROM [ELMAH_Error]"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { connection.Open(); using (SqlCeCommand command = new SqlCeCommand(sql, connection)) { SqlCeParameterCollection parameters = command.Parameters; parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex; parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize; parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName; using (SqlCeDataReader reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { string id = reader["ErrorId"].ToString(); Elmah.Error error = new Elmah.Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } } } using (SqlCeCommand command = new SqlCeCommand(getCount, connection)) { return (int)command.ExecuteScalar(); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand command = new SqlCeCommand(sql, connection)) { command.Parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = errorGuid; connection.Open(); string errorXml = (string)command.ExecuteScalar(); if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } } } #endif // !NET_1_1 && !NET_1_0
/************************************************************** * Program: Lorei * Class: * Description: * This class handles all of the logic required for lorei to * operate. The class is currently designed around a * Dictionary that is used to store and look up created * processes based on a file path to the launched exe. * This may or may not be the best solution but it works well. * drawbacks: 1) Can only have one instance of a program * open at a time. But since i haven't created a * way to identify more then one program instance * at a time this is a mute point. * The class primarily focuses on the creation and handling of * the grammar classes used to control different programs. The * grammar classes are what allow the speech api to understand * English. * This class also hosts the script engines that setup the * the grammars required for a * specific program this provides a large amount of flexibility * and change to programs without the need to recompile lorei. * This class acts as a interface providing some basic methods * that the scripting engines can expose in the script files. **************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Speech.Recognition; using System.Speech.Synthesis; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using log4net; using Lorei.CScode.Interfaces; namespace Lorei.CScode.ApiProviders { public class RecognizerApiProvider: ApiProvider { /** * API Provider for the Speech recognizer. Includes Grammar creation * * @param p_textToSpeechApi Allows Speech */ public RecognizerApiProvider(TextToSpeechApiProvider p_textToSpeechApi) { m_textToSpeechApi = p_textToSpeechApi; log4net.Config.XmlConfigurator.Configure(); log = LogManager.GetLogger(typeof(RecognizerApiProvider)); // Setup Engine SetupSpeechRecognitionEngine(); } /** * Changes Lorei's state to Listening. */ public void LoreiStartListening() { if (!m_Enabled) { LoadTrackedGrammars(); m_speechRecognizer.RecognizeAsync(RecognizeMode.Multiple); if (StateChanged != null) StateChanged(this, true); m_Enabled = true; log.Info("Lorei has started listening."); } } /** * Changes Lorei's state to not Listening. */ public void LoreiStopListening() { if (m_Enabled) { m_speechRecognizer.RecognizeAsyncCancel(); if (StateChanged != null) StateChanged(this, false); m_Enabled = false; log.Info("Lorei has stopped listening."); } } /** * Loads in Script Processor, so it can pass Speech events to them. * * @param p_scriptProcessor The current ScriptProcessor to load. */ public void LoadScriptProcessor(ScriptProcessor p_scriptProcessor) { m_scriptProcessors.Add(p_scriptProcessor); log.Info(p_scriptProcessor + " has been added to the list of Script Processors."); } //Methods for Registration Api public void RegisterLoreiGrammar(System.Speech.Recognition.Grammar p_grammarToLoad) { m_speechRecognizer.LoadGrammar(p_grammarToLoad); } public List<string> GetLoreiNames() { return m_Keywords; } public void AddLoreiName( System.String p_nameToAdd ) { // HACK:: Remove this later and replace with a flat text file that all scripts can read. if (m_Keywords.Contains(p_nameToAdd)) return; m_Keywords.Add(p_nameToAdd); } /************ Api Provider Interface ************/ public List<System.Reflection.MethodInfo> GetMethods() { List<System.Reflection.MethodInfo> methods = new List<System.Reflection.MethodInfo>(); // Setup the list methods.Add(this.GetType().GetMethod("RegisterLoreiGrammar")); methods.Add(this.GetType().GetMethod("GetLoreiNames")); methods.Add(this.GetType().GetMethod("AddLoreiName")); return methods; } /** * Event triggered when Lorei understand what is being said */ private void m_speechRecognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { // Interaction Message m_textToSpeechApi.SayMessage("Ok!"); // Parse Speech ParseSpeech(e); log.Info("Message: " + e.Result.Text); } /** * Event triggered if no command is understood */ private void m_speechRecognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e) { // If we knew any words if (e.Result.Words.Count > 0) { m_textToSpeechApi.SayMessage("What?"); } } /************ Helper Methods ************/ // Helper Methods For Speech Recognition Engine private void SetupSpeechRecognitionEngine() { // Setup Speech Engine m_speechRecognizer = new SpeechRecognitionEngine(); if (m_speechRecognizer == null) { m_textToSpeechApi.SayMessage("Speech Recognizer Creation Failed is Null"); log.Error("Speech Recognizer has failed to created."); } else { m_textToSpeechApi.SayMessage("Speech Recognizer Created"); // Bind to default audio device m_speechRecognizer.SetInputToDefaultAudioDevice(); // Setup Event Handlers SetupEventHandlers(); } } private void LoadTrackedGrammars() { foreach(Grammar g in m_GrammarsLoaded) { m_speechRecognizer.LoadGrammar(g); } } private void SetupEventHandlers() { m_speechRecognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(m_speechRecognizer_SpeechRecognized); m_speechRecognizer.SpeechRecognitionRejected += new EventHandler<SpeechRecognitionRejectedEventArgs>(m_speechRecognizer_SpeechRecognitionRejected); } // Helper Methods For Parsing Speech and script Api accessible functions private void ParseSpeech(SpeechRecognizedEventArgs e) { // Let the world know we parsed a command m_lastCommand = e.Result.Text; this.TextReceived(this, e); // Pass the buck // Let our scripting languages have the message. // TODO: Clean up this interface later foreach (ScriptProcessor x in m_scriptProcessors) { x.ParseSpeech(e); } } /************ Constants ************/ /************ Events ************/ public event ParseSpeech TextReceived; public event ProcesserSwitchChanged StateChanged; /************ Accessors ************/ public bool Active { set { if (value == true) LoreiStartListening(); else LoreiStopListening(); } get { return m_Enabled; } } public string LastCommand { get { return m_lastCommand; } } /************ Data ************/ private List<Grammar> m_GrammarsLoaded = new List<Grammar>(); // Speech Components private SpeechRecognitionEngine m_speechRecognizer; // Program Control Data private bool m_disabledByVoice = false; private bool m_Enabled = false; private string m_lastCommand; // Scripting Data private List<ScriptProcessor> m_scriptProcessors = new List<ScriptProcessor>(); private TextToSpeechApiProvider m_textToSpeechApi; // List of nicknames for Lorei private List<String> m_Keywords = new List<string>(); //Logging Data private static ILog log; } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using CSharpGuidelinesAnalyzer.Extensions; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace CSharpGuidelinesAnalyzer.Rules.MiscellaneousDesign { [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class EvaluateQueryBeforeReturnAnalyzer : DiagnosticAnalyzer { private const string Title = "Evaluate LINQ query before returning it"; private const string OperationMessageFormat = "{0} '{1}' returns the result of a call to '{2}', which uses deferred execution"; private const string QueryMessageFormat = "{0} '{1}' returns the result of a query, which uses deferred execution"; private const string QueryableMessageFormat = "{0} '{1}' returns an IQueryable, which uses deferred execution"; private const string Description = "Evaluate the result of a LINQ expression before returning it."; private const string QueryOperationName = "<*>Query"; private const string QueryableOperationName = "<*>Queryable"; public const string DiagnosticId = "AV1250"; [NotNull] private static readonly AnalyzerCategory Category = AnalyzerCategory.MiscellaneousDesign; [NotNull] private static readonly DiagnosticDescriptor OperationRule = new DiagnosticDescriptor(DiagnosticId, Title, OperationMessageFormat, Category.DisplayName, DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [NotNull] private static readonly DiagnosticDescriptor QueryRule = new DiagnosticDescriptor(DiagnosticId, Title, QueryMessageFormat, Category.DisplayName, DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [NotNull] private static readonly DiagnosticDescriptor QueryableRule = new DiagnosticDescriptor(DiagnosticId, Title, QueryableMessageFormat, Category.DisplayName, DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [ItemNotNull] private static readonly ImmutableArray<string> LinqOperatorsDeferred = ImmutableArray.Create("Aggregate", "All", "Any", "Cast", "Concat", "Contains", "DefaultIfEmpty", "Except", "GroupBy", "GroupJoin", "Intersect", "Join", "OfType", "OrderBy", "OrderByDescending", "Range", "Repeat", "Reverse", "Select", "SelectMany", "SequenceEqual", "Skip", "SkipWhile", "Take", "TakeWhile", "ThenBy", "ThenByDescending", "Union", "Where", "Zip"); [ItemNotNull] private static readonly ImmutableArray<string> LinqOperatorsImmediate = ImmutableArray.Create("Average", "Count", "Distinct", "ElementAt", "ElementAtOrDefault", "Empty", "First", "FirstOrDefault", "Last", "LastOrDefault", "LongCount", "Max", "Min", "Single", "SingleOrDefault", "Sum", "ToArray", "ToImmutableArray", "ToDictionary", "ToList", "ToLookup"); [ItemNotNull] private static readonly ImmutableArray<string> LinqOperatorsTransparent = ImmutableArray.Create("AsEnumerable", "AsQueryable"); [NotNull] private static readonly Action<CompilationStartAnalysisContext> RegisterCompilationStartAction = RegisterCompilationStart; [NotNull] private static readonly Action<OperationBlockAnalysisContext, SequenceTypeInfo> AnalyzeCodeBlockAction = (context, sequenceTypeInfo) => context.SkipInvalid(_ => AnalyzeCodeBlock(context, sequenceTypeInfo)); [ItemNotNull] public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(OperationRule, QueryRule, QueryableRule); public override void Initialize([NotNull] AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(RegisterCompilationStartAction); } private static void RegisterCompilationStart([NotNull] CompilationStartAnalysisContext startContext) { var sequenceTypeInfo = new SequenceTypeInfo(startContext.Compilation); startContext.RegisterOperationBlockAction(context => AnalyzeCodeBlockAction(context, sequenceTypeInfo)); } private static void AnalyzeCodeBlock(OperationBlockAnalysisContext context, [NotNull] SequenceTypeInfo sequenceTypeInfo) { if (context.OwningSymbol.DeclaredAccessibility != Accessibility.Public || !IsInMethodThatReturnsEnumerable(context.OwningSymbol, sequenceTypeInfo)) { return; } var collector = new ReturnStatementCollector(sequenceTypeInfo, context); collector.VisitBlocks(context.OperationBlocks); AnalyzeReturnStatements(collector.ReturnStatements, context); } private static bool IsInMethodThatReturnsEnumerable([NotNull] ISymbol owningSymbol, [NotNull] SequenceTypeInfo sequenceTypeInfo) { return owningSymbol is IMethodSymbol { ReturnsVoid: false } method && sequenceTypeInfo.IsEnumerable(method.ReturnType); } private static void AnalyzeReturnStatements([NotNull] [ItemNotNull] IList<IReturnOperation> returnStatements, OperationBlockAnalysisContext context) { if (returnStatements.Any()) { foreach (IReturnOperation returnStatement in returnStatements) { context.CancellationToken.ThrowIfCancellationRequested(); var analyzer = new ReturnValueAnalyzer(context); analyzer.Analyze(returnStatement); } } } private static void ReportDiagnosticAt([NotNull] IReturnOperation returnStatement, [NotNull] string operationName, OperationBlockAnalysisContext context) { Location location = returnStatement.TryGetLocationForKeyword(); if (location != null) { ISymbol containingMember = context.OwningSymbol.GetContainingMember(); string memberName = containingMember.ToDisplayString(SymbolDisplayFormat.CSharpShortErrorMessageFormat); (DiagnosticDescriptor rule, object[] messageArguments) = GetArgumentsForReport(operationName, containingMember, memberName); var diagnostic = Diagnostic.Create(rule, location, messageArguments); context.ReportDiagnostic(diagnostic); } } private static (DiagnosticDescriptor rule, object[] messageArguments) GetArgumentsForReport([NotNull] string operationName, [NotNull] ISymbol containingMember, [NotNull] string memberName) { switch (operationName) { case QueryOperationName: { return (QueryRule, new object[] { containingMember.GetKind(), memberName }); } case QueryableOperationName: { return (QueryableRule, new object[] { containingMember.GetKind(), memberName }); } default: { return (OperationRule, new object[] { containingMember.GetKind(), memberName, operationName }); } } } /// <summary> /// Scans for return statements, skipping over anonymous methods and local functions, whose compile-time type allows for deferred execution. /// </summary> private sealed class ReturnStatementCollector : ExplicitOperationWalker { [NotNull] private readonly SequenceTypeInfo sequenceTypeInfo; private readonly OperationBlockAnalysisContext context; private int scopeDepth; [NotNull] [ItemNotNull] public IList<IReturnOperation> ReturnStatements { get; } = new List<IReturnOperation>(); public ReturnStatementCollector([NotNull] SequenceTypeInfo sequenceTypeInfo, OperationBlockAnalysisContext context) { Guard.NotNull(sequenceTypeInfo, nameof(sequenceTypeInfo)); this.sequenceTypeInfo = sequenceTypeInfo; this.context = context; } public void VisitBlocks([ItemNotNull] ImmutableArray<IOperation> blocks) { foreach (IOperation block in blocks) { Visit(block); } } public override void VisitLocalFunction([NotNull] ILocalFunctionOperation operation) { scopeDepth++; base.VisitLocalFunction(operation); scopeDepth--; } public override void VisitAnonymousFunction([NotNull] IAnonymousFunctionOperation operation) { scopeDepth++; base.VisitAnonymousFunction(operation); scopeDepth--; } public override void VisitReturn([NotNull] IReturnOperation operation) { if (scopeDepth == 0 && operation.ReturnedValue != null && !ReturnsConstant(operation.ReturnedValue) && MethodSignatureTypeIsEnumerable(operation.ReturnedValue)) { ITypeSymbol returnValueType = operation.ReturnedValue.SkipTypeConversions().Type; if (sequenceTypeInfo.IsQueryable(returnValueType)) { ReportDiagnosticAt(operation, QueryableOperationName, context); } else if (sequenceTypeInfo.IsNonQueryableSequenceType(returnValueType)) { ReturnStatements.Add(operation); } // ReSharper disable once RedundantIfElseBlock else { // No action required. } } base.VisitReturn(operation); } private static bool ReturnsConstant([NotNull] IOperation returnValue) { return returnValue.ConstantValue.HasValue; } private bool MethodSignatureTypeIsEnumerable([NotNull] IOperation returnValue) { return sequenceTypeInfo.IsEnumerable(returnValue.Type); } } /// <summary> /// Analyzes the filtered set of return values in a method. /// </summary> private sealed class ReturnValueAnalyzer { private readonly OperationBlockAnalysisContext context; [NotNull] private readonly IDictionary<ILocalSymbol, EvaluationResult> variableEvaluationCache = new Dictionary<ILocalSymbol, EvaluationResult>(); public ReturnValueAnalyzer(OperationBlockAnalysisContext context) { this.context = context; } public void Analyze([NotNull] IReturnOperation returnStatement) { EvaluationResult result = AnalyzeExpression(returnStatement.ReturnedValue); if (result.IsConclusive && result.IsDeferred) { ReportDiagnosticAt(returnStatement, result.DeferredOperationName, context); } } [NotNull] private EvaluationResult AnalyzeExpression([NotNull] IOperation expression) { Guard.NotNull(expression, nameof(expression)); context.CancellationToken.ThrowIfCancellationRequested(); var walker = new ExpressionWalker(this); walker.Visit(expression); return walker.Result; } /// <summary> /// Runs flow analysis on the return value expression of a return statement. /// </summary> private sealed class ExpressionWalker : AbstractEvaluatingOperationWalker { [NotNull] private readonly ReturnValueAnalyzer owner; public ExpressionWalker([NotNull] ReturnValueAnalyzer owner) { Guard.NotNull(owner, nameof(owner)); this.owner = owner; } public override void VisitConversion([NotNull] IConversionOperation operation) { Visit(operation.Operand); } public override void VisitInvocation([NotNull] IInvocationOperation operation) { base.VisitInvocation(operation); if (operation.Instance == null) { if (IsExecutionDeferred(operation) || IsExecutionImmediate(operation) || IsExecutionTransparent(operation)) { return; } } Result.SetUnknown(); } private bool IsExecutionDeferred([NotNull] IInvocationOperation operation) { if (LinqOperatorsDeferred.Contains(operation.TargetMethod.Name)) { if (operation.TargetMethod.ContainingType.SpecialType != SpecialType.System_String) { Result.SetDeferred(operation.TargetMethod.Name); return true; } } return false; } private bool IsExecutionImmediate([NotNull] IInvocationOperation operation) { if (LinqOperatorsImmediate.Contains(operation.TargetMethod.Name)) { Result.SetImmediate(); return true; } return false; } private bool IsExecutionTransparent([NotNull] IInvocationOperation operation) { return LinqOperatorsTransparent.Contains(operation.TargetMethod.Name); } public override void VisitLocalReference([NotNull] ILocalReferenceOperation operation) { if (IsInvokingDelegateVariable(operation)) { return; } var assignmentWalker = new VariableAssignmentWalker(operation.Local, operation.Syntax.GetLocation(), owner); assignmentWalker.VisitBlockBody(); Result.CopyFrom(assignmentWalker.Result); } private static bool IsInvokingDelegateVariable([NotNull] ILocalReferenceOperation operation) { return operation.Parent is IInvocationOperation; } public override void VisitConditional([NotNull] IConditionalOperation operation) { EvaluationResult trueResult = owner.AnalyzeExpression(operation.WhenTrue); if (operation.WhenFalse == null || trueResult.IsDeferred) { Result.CopyFrom(trueResult); } else { EvaluationResult falseResult = owner.AnalyzeExpression(operation.WhenFalse); Result.CopyFrom(EvaluationResult.Unify(trueResult, falseResult)); } } public override void VisitCoalesce([NotNull] ICoalesceOperation operation) { EvaluationResult valueResult = owner.AnalyzeExpression(operation.Value); if (valueResult.IsDeferred) { Result.CopyFrom(valueResult); } else { EvaluationResult alternativeResult = owner.AnalyzeExpression(operation.WhenNull); Result.CopyFrom(EvaluationResult.Unify(valueResult, alternativeResult)); } } public override void VisitTranslatedQuery([NotNull] ITranslatedQueryOperation operation) { Result.CopyFrom(EvaluationResult.Query); } public override void VisitObjectCreation([NotNull] IObjectCreationOperation operation) { Result.SetImmediate(); } public override void VisitDynamicObjectCreation([NotNull] IDynamicObjectCreationOperation operation) { Result.SetImmediate(); } public override void VisitArrayCreation([NotNull] IArrayCreationOperation operation) { Result.SetImmediate(); } public override void VisitArrayElementReference([NotNull] IArrayElementReferenceOperation operation) { Result.SetUnknown(); } public override void VisitAnonymousObjectCreation([NotNull] IAnonymousObjectCreationOperation operation) { Result.SetUnknown(); } public override void VisitObjectOrCollectionInitializer([NotNull] IObjectOrCollectionInitializerOperation operation) { Result.SetImmediate(); } public override void VisitCollectionElementInitializer([NotNull] ICollectionElementInitializerOperation operation) { Result.SetImmediate(); } public override void VisitDefaultValue([NotNull] IDefaultValueOperation operation) { Result.SetImmediate(); } public override void VisitDynamicInvocation([NotNull] IDynamicInvocationOperation operation) { Result.SetUnknown(); } public override void VisitDynamicMemberReference([NotNull] IDynamicMemberReferenceOperation operation) { Result.SetUnknown(); } public override void VisitNameOf([NotNull] INameOfOperation operation) { Result.SetUnknown(); } public override void VisitLiteral([NotNull] ILiteralOperation operation) { Result.SetImmediate(); } public override void VisitThrow([NotNull] IThrowOperation operation) { Result.SetImmediate(); } } /// <summary> /// Evaluates all assignments to a specific variable in a code block, storing its intermediate states. /// </summary> private sealed class VariableAssignmentWalker : AbstractEvaluatingOperationWalker { [NotNull] private readonly ILocalSymbol currentLocal; [NotNull] private readonly Location maxLocation; [NotNull] private readonly ReturnValueAnalyzer owner; public VariableAssignmentWalker([NotNull] ILocalSymbol local, [NotNull] Location maxLocation, [NotNull] ReturnValueAnalyzer owner) { Guard.NotNull(local, nameof(local)); Guard.NotNull(maxLocation, nameof(maxLocation)); Guard.NotNull(owner, nameof(owner)); currentLocal = local; this.maxLocation = maxLocation; this.owner = owner; } public void VisitBlockBody() { if (owner.variableEvaluationCache.ContainsKey(currentLocal)) { EvaluationResult resultFromCache = owner.variableEvaluationCache[currentLocal]; Result.CopyFrom(resultFromCache); } else { foreach (IOperation operation in owner.context.OperationBlocks) { Visit(operation); } } } public override void VisitVariableDeclarator([NotNull] IVariableDeclaratorOperation operation) { base.VisitVariableDeclarator(operation); if (currentLocal.IsEqualTo(operation.Symbol) && EndsBeforeMaxLocation(operation)) { IVariableInitializerOperation initializer = operation.GetVariableInitializer(); if (initializer != null) { AnalyzeAssignmentValue(initializer.Value); } } } public override void VisitSimpleAssignment([NotNull] ISimpleAssignmentOperation operation) { base.VisitSimpleAssignment(operation); if (operation.Target is ILocalReferenceOperation targetLocal && currentLocal.IsEqualTo(targetLocal.Local) && EndsBeforeMaxLocation(operation)) { AnalyzeAssignmentValue(operation.Value); } } public override void VisitDeconstructionAssignment([NotNull] IDeconstructionAssignmentOperation operation) { base.VisitDeconstructionAssignment(operation); if (operation.Target is ITupleOperation tupleOperation && EndsBeforeMaxLocation(operation)) { foreach (IOperation element in tupleOperation.Elements) { if (element is ILocalReferenceOperation targetLocal && currentLocal.IsEqualTo(targetLocal.Local)) { UpdateResult(EvaluationResult.Unknown); } } } } private bool EndsBeforeMaxLocation([NotNull] IOperation operation) { return operation.Syntax.GetLocation().SourceSpan.End < maxLocation.SourceSpan.Start; } private void AnalyzeAssignmentValue([NotNull] IOperation assignedValue) { Guard.NotNull(assignedValue, nameof(assignedValue)); EvaluationResult result = owner.AnalyzeExpression(assignedValue); UpdateResult(result); } private void UpdateResult([NotNull] EvaluationResult result) { if (result.IsConclusive) { Result.CopyFrom(result); owner.variableEvaluationCache[currentLocal] = Result; } } } } private abstract class AbstractEvaluatingOperationWalker : OperationWalker { [NotNull] public EvaluationResult Result { get; } = new EvaluationResult(); } private sealed class EvaluationResult { [NotNull] public static readonly EvaluationResult Query = new EvaluationResult(EvaluationState.Deferred, QueryOperationName); [NotNull] public static readonly EvaluationResult Unknown = new EvaluationResult(EvaluationState.Unknown, null); private EvaluationState evaluationState; [CanBeNull] private string deferredOperationNameOrNull; [NotNull] public string DeferredOperationName { get { if (evaluationState != EvaluationState.Deferred) { throw new InvalidOperationException("Operation name is not available in non-deferred states."); } // ReSharper disable once AssignNullToNotNullAttribute return deferredOperationNameOrNull; } } public bool IsConclusive => evaluationState != EvaluationState.Initial; public bool IsDeferred => evaluationState == EvaluationState.Deferred; public EvaluationResult() { } private EvaluationResult(EvaluationState state, [CanBeNull] string deferredOperationNameOrNull) { evaluationState = state; this.deferredOperationNameOrNull = deferredOperationNameOrNull; } public void SetImmediate() { evaluationState = EvaluationState.Immediate; } public void SetUnknown() { evaluationState = EvaluationState.Unknown; } public void SetDeferred([NotNull] string operationName) { Guard.NotNullNorWhiteSpace(operationName, nameof(operationName)); evaluationState = EvaluationState.Deferred; deferredOperationNameOrNull = operationName; } public void CopyFrom([NotNull] EvaluationResult result) { Guard.NotNull(result, nameof(result)); evaluationState = result.evaluationState; deferredOperationNameOrNull = result.deferredOperationNameOrNull; } [NotNull] public static EvaluationResult Unify([NotNull] EvaluationResult first, [NotNull] EvaluationResult second) { Guard.NotNull(first, nameof(first)); Guard.NotNull(second, nameof(second)); if (first.IsConclusive && first.IsDeferred) { return first; } if (second.IsConclusive && second.IsDeferred) { return second; } return first.IsConclusive ? first : second; } public override string ToString() { return evaluationState.ToString(); } private enum EvaluationState { Initial, Unknown, Immediate, Deferred } } private sealed class SequenceTypeInfo { [ItemNotNull] private readonly ImmutableArray<INamedTypeSymbol> queryableTypes; [ItemNotNull] private readonly ImmutableArray<INamedTypeSymbol> otherSequenceTypes; public SequenceTypeInfo([NotNull] Compilation compilation) { Guard.NotNull(compilation, nameof(compilation)); queryableTypes = GetQueryableTypes(compilation); otherSequenceTypes = GetOtherSequenceTypes(compilation); } [ItemNotNull] private ImmutableArray<INamedTypeSymbol> GetQueryableTypes([NotNull] Compilation compilation) { ImmutableArray<INamedTypeSymbol>.Builder builder = ImmutableArray.CreateBuilder<INamedTypeSymbol>(4); AddTypeToBuilder(KnownTypes.SystemLinqIQueryableT(compilation), builder); AddTypeToBuilder(KnownTypes.SystemLinqIOrderedQueryableT(compilation), builder); AddTypeToBuilder(KnownTypes.SystemLinqIQueryable(compilation), builder); AddTypeToBuilder(KnownTypes.SystemLinqIOrderedQueryable(compilation), builder); return !builder.Any() ? ImmutableArray<INamedTypeSymbol>.Empty : builder.ToImmutable(); } [ItemNotNull] private ImmutableArray<INamedTypeSymbol> GetOtherSequenceTypes([NotNull] Compilation compilation) { ImmutableArray<INamedTypeSymbol>.Builder builder = ImmutableArray.CreateBuilder<INamedTypeSymbol>(3); AddTypeToBuilder(KnownTypes.SystemLinqIOrderedEnumerableT(compilation), builder); AddTypeToBuilder(KnownTypes.SystemLinqIGroupingTKeyTElement(compilation), builder); AddTypeToBuilder(KnownTypes.SystemLinqILookupTKeyTElement(compilation), builder); return !builder.Any() ? ImmutableArray<INamedTypeSymbol>.Empty : builder.ToImmutable(); } private void AddTypeToBuilder([CanBeNull] INamedTypeSymbol type, [NotNull] [ItemNotNull] ImmutableArray<INamedTypeSymbol>.Builder builder) { if (type != null) { builder.Add(type); } } public bool IsEnumerable([NotNull] ITypeSymbol type) { return type.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T || type.SpecialType == SpecialType.System_Collections_IEnumerable; } public bool IsQueryable([NotNull] ITypeSymbol type) { Guard.NotNull(type, nameof(type)); return queryableTypes.Contains(type.OriginalDefinition); } public bool IsNonQueryableSequenceType([NotNull] ITypeSymbol type) { Guard.NotNull(type, nameof(type)); return IsEnumerable(type) || otherSequenceTypes.Contains(type.OriginalDefinition); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Management.Automation; using System.Reflection; using System.Resources; namespace Microsoft.PowerShell.Commands.Internal.Format { internal sealed class DisplayResourceManagerCache { internal enum LoadingResult { NoError, AssemblyNotFound, ResourceNotFound, StringNotFound } internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath } internal string GetTextTokenString(TextToken tt) { if (tt.resource != null) { string resString = this.GetString(tt.resource); if (resString != null) return resString; } return tt.text; } internal void VerifyResource(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus) { GetStringHelper(resourceReference, out result, out bindingStatus); } private string GetString(StringResourceReference resourceReference) { LoadingResult result; AssemblyBindingStatus bindingStatus; return GetStringHelper(resourceReference, out result, out bindingStatus); } private string GetStringHelper(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus) { result = LoadingResult.AssemblyNotFound; bindingStatus = AssemblyBindingStatus.NotFound; AssemblyLoadResult loadResult = null; // try first to see if we have an assembly reference in the cache if (_resourceReferenceToAssemblyCache.Contains(resourceReference)) { loadResult = _resourceReferenceToAssemblyCache[resourceReference] as AssemblyLoadResult; bindingStatus = loadResult.status; } else { loadResult = new AssemblyLoadResult(); // we do not have an assembly, we try to load it bool foundInGac; loadResult.a = LoadAssemblyFromResourceReference(resourceReference, out foundInGac); if (loadResult.a == null) { loadResult.status = AssemblyBindingStatus.NotFound; } else { loadResult.status = foundInGac ? AssemblyBindingStatus.FoundInGac : AssemblyBindingStatus.FoundInPath; } // add to the cache even if null _resourceReferenceToAssemblyCache.Add(resourceReference, loadResult); } bindingStatus = loadResult.status; if (loadResult.a == null) { // we failed the assembly loading result = LoadingResult.AssemblyNotFound; return null; } else { resourceReference.assemblyLocation = loadResult.a.Location; } // load now the resource from the resource manager cache try { string val = ResourceManagerCache.GetResourceString(loadResult.a, resourceReference.baseName, resourceReference.resourceId); if (val == null) { result = LoadingResult.StringNotFound; return null; } else { result = LoadingResult.NoError; return val; } } catch (InvalidOperationException) { result = LoadingResult.ResourceNotFound; } catch (MissingManifestResourceException) { result = LoadingResult.ResourceNotFound; } catch (Exception e) // will rethrow { Diagnostics.Assert(false, "ResourceManagerCache.GetResourceString unexpected exception " + e.GetType().FullName); throw; } return null; } /// <summary> /// Get a reference to an assembly object by looking up the currently loaded assemblies. /// </summary> /// <param name="resourceReference">the string resource reference object containing /// the name of the assembly to load</param> /// <param name="foundInGac"> true if assembly was found in the GAC. NOTE: the current /// implementation always return FALSE</param> /// <returns></returns> private Assembly LoadAssemblyFromResourceReference(StringResourceReference resourceReference, out bool foundInGac) { // NOTE: we keep the function signature as and the calling code is able do deal // with dynamically loaded assemblies. If this functionality is implemented, this // method will have to be changed accordingly foundInGac = false; // it always be false, since we return already loaded assemblies return _assemblyNameResolver.ResolveAssemblyName(resourceReference.assemblyName); } private sealed class AssemblyLoadResult { internal Assembly a; internal AssemblyBindingStatus status; } /// <summary> /// Helper class to resolve an assembly name to an assembly reference /// The class caches previous results for faster lookup. /// </summary> private sealed class AssemblyNameResolver { /// <summary> /// Resolve the assembly name against the set of loaded assemblies. /// </summary> /// <param name="assemblyName"></param> /// <returns></returns> internal Assembly ResolveAssemblyName(string assemblyName) { if (string.IsNullOrEmpty(assemblyName)) { return null; } // look up the cache first if (_assemblyReferences.Contains(assemblyName)) { return (Assembly)_assemblyReferences[assemblyName]; } // not found, scan the loaded assemblies // first look for the full name Assembly retVal = ResolveAssemblyNameInLoadedAssemblies(assemblyName, true) ?? ResolveAssemblyNameInLoadedAssemblies(assemblyName, false); // NOTE: we cache the result (both for success and failure) // Porting note: this won't be hit in normal usage, but can be hit with bad build setup Diagnostics.Assert(retVal != null, "AssemblyName resolution failed, a resource file might be broken"); _assemblyReferences.Add(assemblyName, retVal); return retVal; } private static Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName) { Assembly result = null; #if false // This should be re-enabled once the default assembly list contains the // assemblies referenced by the S.M.A.dll. // First we need to get the execution context from thread-local storage. ExecutionContext context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (context != null) { context.AssemblyCache.GetAtKey(assemblyName, out result); } #else foreach (Assembly a in ClrFacade.GetAssemblies()) { AssemblyName aName = null; try { aName = a.GetName(); } catch (System.Security.SecurityException) { continue; } string nameToCompare = fullName ? aName.FullName : aName.Name; if (string.Equals(nameToCompare, assemblyName, StringComparison.Ordinal)) { return a; } } #endif return result; } private readonly Hashtable _assemblyReferences = new Hashtable(StringComparer.OrdinalIgnoreCase); } private readonly AssemblyNameResolver _assemblyNameResolver = new AssemblyNameResolver(); private readonly Hashtable _resourceReferenceToAssemblyCache = new Hashtable(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; namespace System { // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. public static class BitConverter { public static readonly bool IsLittleEndian = GetIsLittleEndian(); private static unsafe bool GetIsLittleEndian() { int i = 1; return *((byte*)&i) == 1; } // Converts a Boolean into an array of bytes with length one. public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)1 : (byte)0); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts a short into an array of bytes with length // two. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed (byte* b = bytes) *((short*)b) = value; return bytes; } // Converts an int into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed (byte* b = bytes) *((int*)b) = value; return bytes; } // Converts a long into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed (byte* b = bytes) *((long*)b) = value; return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } // Converts a float into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } // Converts a double into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } // Converts an array of bytes into a char. public static char ToChar(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (char)ToInt16(value, startIndex); } // Converts an array of bytes into a short. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe short ToInt16(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 2 == 0) { // data is aligned return *((short*)pbyte); } else if (IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)); } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } // Converts an array of bytes into an int. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe int ToInt32(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 4 == 0) { // data is aligned return *((int*)pbyte); } else if (IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } // Converts an array of bytes into a long. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe long ToInt64(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); fixed (byte* pbyte = &value[startIndex]) { if (startIndex % 8 == 0) { // data is aligned return *((long*)pbyte); } else if (IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } // Converts an array of bytes into an ushort. // [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 2) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (ushort)ToInt16(value, startIndex); } // Converts an array of bytes into an uint. // [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (uint)ToInt32(value, startIndex); } // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); return (ulong)ToInt64(value, startIndex); } // Converts an array of bytes into a float. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static float ToSingle(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 4) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); int val = ToInt32(value, startIndex); return *(float*)&val; } // Converts an array of bytes into a double. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static double ToDouble(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if ((uint)startIndex >= value.Length) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 8) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static char GetHexValue(int i) { Debug.Assert(i >= 0 && i < 16, "i is out of range."); if (i < 10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static string ToString(byte[] value, int startIndex, int length) { if (value == null) ThrowValueArgumentNull(); if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) ThrowStartIndexArgumentOutOfRange(); if (length < 0) throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_GenericPositive); if (startIndex > value.Length - length) ThrowValueArgumentTooSmall(); Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (int.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException("length", SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3))); } int chArrayLength = length * 3; char[] chArray = new char[chArrayLength]; int i = 0; int index = startIndex; for (i = 0; i < chArrayLength; i += 3) { byte b = value[index++]; chArray[i] = GetHexValue(b / 16); chArray[i + 1] = GetHexValue(b % 16); chArray[i + 2] = '-'; } // We don't need the last '-' character return new string(chArray, 0, chArray.Length - 1); } // Converts an array of bytes into a String. public static string ToString(byte[] value) { if (value == null) ThrowValueArgumentNull(); Contract.Ensures(Contract.Result<string>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } // Converts an array of bytes into a String. public static string ToString(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); Contract.Ensures(Contract.Result<string>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean(byte[] value, int startIndex) { if (value == null) ThrowValueArgumentNull(); if (startIndex < 0) ThrowStartIndexArgumentOutOfRange(); if (startIndex > value.Length - 1) ThrowStartIndexArgumentOutOfRange(); // differs from other overloads, which throw base ArgumentException Contract.EndContractBlock(); return value[startIndex] != 0; } [SecuritySafeCritical] public static unsafe long DoubleToInt64Bits(double value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Debug.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((long*)&value); } [SecuritySafeCritical] public static unsafe double Int64BitsToDouble(long value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Debug.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((double*)&value); } private static void ThrowValueArgumentNull() { throw new ArgumentNullException("value"); } private static void ThrowStartIndexArgumentOutOfRange() { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } private static void ThrowValueArgumentTooSmall() { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall, "value"); } } }
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; namespace DriveProxy.Utils { [Flags] public enum LogType { None = 0, Information = 1<<0, Warning = 1<<1, Error = 1<<2, Performance = 1<<3, Debug = 1 << 4, All = Information | Warning | Error | Performance | Debug, } public class Log { public delegate void WriteEntryEventHandler(string dateTime, string message, LogType type); private static LogType _level = LogType.None; private static string _createdSource; private static string _source; private static string _lastError; private static DateTime _lastErrorTime = default(DateTime); public static LogType Level { get { return _level; } set { _level = value; } } public static string Source { get { if (String.IsNullOrEmpty(_source)) { _source = System.Reflection.Assembly.GetEntryAssembly().Location; _source = System.IO.Path.GetFileNameWithoutExtension(_source); } return _source; } set { _source = value; } } public static string LastError { get { return _lastError; } protected set { _lastError = value; if (!String.IsNullOrEmpty(_lastError)) { _lastErrorTime = DateTime.Now; WriteEntry(value, LogType.Error); } } } public static DateTime LastErrorTime { get { return _lastErrorTime; } protected set { _lastErrorTime = value; } } public static event WriteEntryEventHandler OnWriteEntry = null; public static void Error(Exception exception, bool continueThrow = true, bool breakWithDebugger = true) { try { var logException = exception as LogException; if (logException == null) { logException = new LogException(exception.Message, continueThrow, breakWithDebugger, exception); } else { if (!logException.ContinueThrow) { continueThrow = false; } if (!logException.BreakWithDebugger) { breakWithDebugger = false; } if (logException.TriedToBreak) { breakWithDebugger = false; } } if (!logException.AlreadyLogged) { Error(exception.Message, false); logException.AlreadyLogged = true; } #if DEBUG if (breakWithDebugger) { logException.TriedToBreak = true; } #endif exception = logException; } catch { Debugger.Break(); } #if DEBUG if (breakWithDebugger) { if (!Debugger.IsAttached) { System.Diagnostics.Debugger.Launch(); } else { System.Diagnostics.Debugger.Break(); } } #endif if (continueThrow) { throw exception; } } public static void Error(string message, bool breakWithDebugger = false) { try { double totalSeconds = 0; bool bypass = false; if (!String.IsNullOrEmpty(message) && !String.IsNullOrEmpty(LastError) && message == LastError) { totalSeconds = DateTime.Now.Subtract(LastErrorTime).TotalSeconds; if (totalSeconds <= 1) { bypass = true; breakWithDebugger = false; } } if (!bypass) { LastError = message; } #if DEBUG if (breakWithDebugger) { Debugger.Break(); LastErrorTime = DateTime.Now; } #endif } catch { Debugger.Break(); } } public static void Information(string message) { try { WriteEntry(message, LogType.Information); } catch { Debugger.Break(); } } public static void Debug(string message) { try { WriteEntry(message, LogType.Debug); } catch { Debugger.Break(); } } public static void Performance(string message) { try { WriteEntry(message, LogType.Performance); } catch { Debugger.Break(); } } public static void StartPerformance(ref Stopwatch stopWatch, string message, LogType logType = LogType.Warning) { try { WriteEntry(message, LogType.Performance); stopWatch.Restart(); } catch { Debugger.Break(); } } public static void EndPerformance(ref Stopwatch stopWatch, string message, LogType logType = LogType.Information) { try { stopWatch.Stop(); WriteEntry(message + " (milliseconds " + stopWatch.ElapsedMilliseconds + ")", LogType.Performance); } catch { Debugger.Break(); } } public static void Warning(string message) { try { WriteEntry(message, LogType.Warning); } catch { Debugger.Break(); } } public static void WriteEntry(string message, LogType logType) { try { if ((_level & logType) == 0) { return; } try { if (_createdSource != Source) { if (!System.Diagnostics.EventLog.SourceExists(Source)) { var sourceData = new System.Diagnostics.EventSourceCreationData(Source, "Application"); System.Diagnostics.EventLog.CreateEventSource(sourceData); } _createdSource = Source; } var eventLogEntryType = System.Diagnostics.EventLogEntryType.Error; if (logType == LogType.Information) { eventLogEntryType = System.Diagnostics.EventLogEntryType.Information; } else if (logType == LogType.Warning) { eventLogEntryType = System.Diagnostics.EventLogEntryType.Warning; } System.Diagnostics.EventLog.WriteEntry(Source, message, eventLogEntryType); } catch (Exception e) { Log.Information(e.Message); } DateTime now = DateTime.Now; string nowValue = now.ToShortDateString() + " " + now.Hour + ":" + now.Minute.ToString().PadLeft(2, '0') + ":" + now.Second.ToString().PadLeft(2, '0') + ":" + now.Millisecond.ToString().PadLeft(3, '0'); #if DEBUG try { string consoleMessage = Source + " - " + nowValue + " - " + logType.ToString().ToUpper() + " - " + message; System.Diagnostics.Debug.WriteLine(consoleMessage); System.Diagnostics.Debug.Flush(); } catch { } #endif try { if (OnWriteEntry != null) { OnWriteEntry(nowValue, message, logType); } } catch { } } catch { Debugger.Break(); } } public class Stopwatch : System.Diagnostics.Stopwatch { } } public class LogException : Exception { public bool AlreadyLogged = false; public bool BreakWithDebugger = true; public bool ContinueThrow = true; public bool TriedToBreak = false; public LogException(string message, bool continueThrow = true, bool breakWithDebugger = true, Exception innerException = null) : base(message, innerException) { ContinueThrow = continueThrow; BreakWithDebugger = breakWithDebugger; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcvlv = Google.Cloud.Video.LiveStream.V1; using sys = System; namespace Google.Cloud.Video.LiveStream.V1 { /// <summary>Resource name for the <c>Input</c> resource.</summary> public sealed partial class InputName : gax::IResourceName, sys::IEquatable<InputName> { /// <summary>The possible contents of <see cref="InputName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/inputs/{input}</c>. /// </summary> ProjectLocationInput = 1, } private static gax::PathTemplate s_projectLocationInput = new gax::PathTemplate("projects/{project}/locations/{location}/inputs/{input}"); /// <summary>Creates a <see cref="InputName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="InputName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static InputName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InputName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InputName"/> with the pattern <c>projects/{project}/locations/{location}/inputs/{input}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="inputId">The <c>Input</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="InputName"/> constructed from the provided ids.</returns> public static InputName FromProjectLocationInput(string projectId, string locationId, string inputId) => new InputName(ResourceNameType.ProjectLocationInput, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), inputId: gax::GaxPreconditions.CheckNotNullOrEmpty(inputId, nameof(inputId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InputName"/> with pattern /// <c>projects/{project}/locations/{location}/inputs/{input}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="inputId">The <c>Input</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InputName"/> with pattern /// <c>projects/{project}/locations/{location}/inputs/{input}</c>. /// </returns> public static string Format(string projectId, string locationId, string inputId) => FormatProjectLocationInput(projectId, locationId, inputId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InputName"/> with pattern /// <c>projects/{project}/locations/{location}/inputs/{input}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="inputId">The <c>Input</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InputName"/> with pattern /// <c>projects/{project}/locations/{location}/inputs/{input}</c>. /// </returns> public static string FormatProjectLocationInput(string projectId, string locationId, string inputId) => s_projectLocationInput.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(inputId, nameof(inputId))); /// <summary>Parses the given resource name string into a new <see cref="InputName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/inputs/{input}</c></description></item> /// </list> /// </remarks> /// <param name="inputName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InputName"/> if successful.</returns> public static InputName Parse(string inputName) => Parse(inputName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InputName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/inputs/{input}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="inputName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="InputName"/> if successful.</returns> public static InputName Parse(string inputName, bool allowUnparsed) => TryParse(inputName, allowUnparsed, out InputName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InputName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/inputs/{input}</c></description></item> /// </list> /// </remarks> /// <param name="inputName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="InputName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string inputName, out InputName result) => TryParse(inputName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InputName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/inputs/{input}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="inputName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="InputName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string inputName, bool allowUnparsed, out InputName result) { gax::GaxPreconditions.CheckNotNull(inputName, nameof(inputName)); gax::TemplatedResourceName resourceName; if (s_projectLocationInput.TryParseName(inputName, out resourceName)) { result = FromProjectLocationInput(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(inputName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InputName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string inputId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; InputId = inputId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="InputName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/inputs/{input}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="inputId">The <c>Input</c> ID. Must not be <c>null</c> or empty.</param> public InputName(string projectId, string locationId, string inputId) : this(ResourceNameType.ProjectLocationInput, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), inputId: gax::GaxPreconditions.CheckNotNullOrEmpty(inputId, nameof(inputId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Input</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InputId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationInput: return s_projectLocationInput.Expand(ProjectId, LocationId, InputId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as InputName); /// <inheritdoc/> public bool Equals(InputName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(InputName a, InputName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(InputName a, InputName b) => !(a == b); } /// <summary>Resource name for the <c>Channel</c> resource.</summary> public sealed partial class ChannelName : gax::IResourceName, sys::IEquatable<ChannelName> { /// <summary>The possible contents of <see cref="ChannelName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/channels/{channel}</c>. /// </summary> ProjectLocationChannel = 1, } private static gax::PathTemplate s_projectLocationChannel = new gax::PathTemplate("projects/{project}/locations/{location}/channels/{channel}"); /// <summary>Creates a <see cref="ChannelName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ChannelName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ChannelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ChannelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ChannelName"/> with the pattern /// <c>projects/{project}/locations/{location}/channels/{channel}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ChannelName"/> constructed from the provided ids.</returns> public static ChannelName FromProjectLocationChannel(string projectId, string locationId, string channelId) => new ChannelName(ResourceNameType.ProjectLocationChannel, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), channelId: gax::GaxPreconditions.CheckNotNullOrEmpty(channelId, nameof(channelId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ChannelName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ChannelName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}</c>. /// </returns> public static string Format(string projectId, string locationId, string channelId) => FormatProjectLocationChannel(projectId, locationId, channelId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ChannelName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ChannelName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}</c>. /// </returns> public static string FormatProjectLocationChannel(string projectId, string locationId, string channelId) => s_projectLocationChannel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(channelId, nameof(channelId))); /// <summary>Parses the given resource name string into a new <see cref="ChannelName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/channels/{channel}</c></description></item> /// </list> /// </remarks> /// <param name="channelName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ChannelName"/> if successful.</returns> public static ChannelName Parse(string channelName) => Parse(channelName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ChannelName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/channels/{channel}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="channelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ChannelName"/> if successful.</returns> public static ChannelName Parse(string channelName, bool allowUnparsed) => TryParse(channelName, allowUnparsed, out ChannelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ChannelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/channels/{channel}</c></description></item> /// </list> /// </remarks> /// <param name="channelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ChannelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string channelName, out ChannelName result) => TryParse(channelName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ChannelName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/channels/{channel}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="channelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ChannelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string channelName, bool allowUnparsed, out ChannelName result) { gax::GaxPreconditions.CheckNotNull(channelName, nameof(channelName)); gax::TemplatedResourceName resourceName; if (s_projectLocationChannel.TryParseName(channelName, out resourceName)) { result = FromProjectLocationChannel(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(channelName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ChannelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string channelId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ChannelId = channelId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ChannelName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/channels/{channel}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> public ChannelName(string projectId, string locationId, string channelId) : this(ResourceNameType.ProjectLocationChannel, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), channelId: gax::GaxPreconditions.CheckNotNullOrEmpty(channelId, nameof(channelId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Channel</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ChannelId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationChannel: return s_projectLocationChannel.Expand(ProjectId, LocationId, ChannelId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ChannelName); /// <inheritdoc/> public bool Equals(ChannelName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ChannelName a, ChannelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ChannelName a, ChannelName b) => !(a == b); } /// <summary>Resource name for the <c>Event</c> resource.</summary> public sealed partial class EventName : gax::IResourceName, sys::IEquatable<EventName> { /// <summary>The possible contents of <see cref="EventName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c>. /// </summary> ProjectLocationChannelEvent = 1, } private static gax::PathTemplate s_projectLocationChannelEvent = new gax::PathTemplate("projects/{project}/locations/{location}/channels/{channel}/events/{event}"); /// <summary>Creates a <see cref="EventName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="EventName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static EventName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EventName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EventName"/> with the pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="eventId">The <c>Event</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EventName"/> constructed from the provided ids.</returns> public static EventName FromProjectLocationChannelEvent(string projectId, string locationId, string channelId, string eventId) => new EventName(ResourceNameType.ProjectLocationChannelEvent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), channelId: gax::GaxPreconditions.CheckNotNullOrEmpty(channelId, nameof(channelId)), eventId: gax::GaxPreconditions.CheckNotNullOrEmpty(eventId, nameof(eventId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EventName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="eventId">The <c>Event</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EventName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c>. /// </returns> public static string Format(string projectId, string locationId, string channelId, string eventId) => FormatProjectLocationChannelEvent(projectId, locationId, channelId, eventId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EventName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="eventId">The <c>Event</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EventName"/> with pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c>. /// </returns> public static string FormatProjectLocationChannelEvent(string projectId, string locationId, string channelId, string eventId) => s_projectLocationChannelEvent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(channelId, nameof(channelId)), gax::GaxPreconditions.CheckNotNullOrEmpty(eventId, nameof(eventId))); /// <summary>Parses the given resource name string into a new <see cref="EventName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c></description> /// </item> /// </list> /// </remarks> /// <param name="eventName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EventName"/> if successful.</returns> public static EventName Parse(string eventName) => Parse(eventName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EventName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="eventName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="EventName"/> if successful.</returns> public static EventName Parse(string eventName, bool allowUnparsed) => TryParse(eventName, allowUnparsed, out EventName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EventName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c></description> /// </item> /// </list> /// </remarks> /// <param name="eventName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EventName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string eventName, out EventName result) => TryParse(eventName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EventName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="eventName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="EventName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string eventName, bool allowUnparsed, out EventName result) { gax::GaxPreconditions.CheckNotNull(eventName, nameof(eventName)); gax::TemplatedResourceName resourceName; if (s_projectLocationChannelEvent.TryParseName(eventName, out resourceName)) { result = FromProjectLocationChannelEvent(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(eventName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EventName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string channelId = null, string eventId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ChannelId = channelId; EventId = eventId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="EventName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/channels/{channel}/events/{event}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelId">The <c>Channel</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="eventId">The <c>Event</c> ID. Must not be <c>null</c> or empty.</param> public EventName(string projectId, string locationId, string channelId, string eventId) : this(ResourceNameType.ProjectLocationChannelEvent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), channelId: gax::GaxPreconditions.CheckNotNullOrEmpty(channelId, nameof(channelId)), eventId: gax::GaxPreconditions.CheckNotNullOrEmpty(eventId, nameof(eventId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Channel</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ChannelId { get; } /// <summary> /// The <c>Event</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EventId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationChannelEvent: return s_projectLocationChannelEvent.Expand(ProjectId, LocationId, ChannelId, EventId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as EventName); /// <inheritdoc/> public bool Equals(EventName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EventName a, EventName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EventName a, EventName b) => !(a == b); } public partial class Input { /// <summary> /// <see cref="gcvlv::InputName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcvlv::InputName InputName { get => string.IsNullOrEmpty(Name) ? null : gcvlv::InputName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Channel { /// <summary> /// <see cref="gcvlv::ChannelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcvlv::ChannelName ChannelName { get => string.IsNullOrEmpty(Name) ? null : gcvlv::ChannelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class InputAttachment { /// <summary><see cref="InputName"/>-typed view over the <see cref="Input"/> resource name property.</summary> public InputName InputAsInputName { get => string.IsNullOrEmpty(Input) ? null : InputName.Parse(Input, allowUnparsed: true); set => Input = value?.ToString() ?? ""; } } public partial class Event { /// <summary> /// <see cref="gcvlv::EventName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcvlv::EventName EventName { get => string.IsNullOrEmpty(Name) ? null : gcvlv::EventName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.OsLogin.Common; using Google.Cloud.OsLogin.V1Beta; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.OsLogin.V1Beta.Snippets { /// <summary>Generated snippets</summary> public class GeneratedOsLoginServiceClientSnippets { /// <summary>Snippet for DeletePosixAccountAsync</summary> public async Task DeletePosixAccountAsync() { // Snippet: DeletePosixAccountAsync(ProjectName,CallSettings) // Additional: DeletePosixAccountAsync(ProjectName,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = new ProjectName("[USER]", "[PROJECT]"); // Make the request await osLoginServiceClient.DeletePosixAccountAsync(name); // End snippet } /// <summary>Snippet for DeletePosixAccount</summary> public void DeletePosixAccount() { // Snippet: DeletePosixAccount(ProjectName,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) ProjectName name = new ProjectName("[USER]", "[PROJECT]"); // Make the request osLoginServiceClient.DeletePosixAccount(name); // End snippet } /// <summary>Snippet for DeletePosixAccountAsync</summary> public async Task DeletePosixAccountAsync_RequestObject() { // Snippet: DeletePosixAccountAsync(DeletePosixAccountRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) DeletePosixAccountRequest request = new DeletePosixAccountRequest { ProjectName = new ProjectName("[USER]", "[PROJECT]"), }; // Make the request await osLoginServiceClient.DeletePosixAccountAsync(request); // End snippet } /// <summary>Snippet for DeletePosixAccount</summary> public void DeletePosixAccount_RequestObject() { // Snippet: DeletePosixAccount(DeletePosixAccountRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) DeletePosixAccountRequest request = new DeletePosixAccountRequest { ProjectName = new ProjectName("[USER]", "[PROJECT]"), }; // Make the request osLoginServiceClient.DeletePosixAccount(request); // End snippet } /// <summary>Snippet for DeleteSshPublicKeyAsync</summary> public async Task DeleteSshPublicKeyAsync() { // Snippet: DeleteSshPublicKeyAsync(FingerprintName,CallSettings) // Additional: DeleteSshPublicKeyAsync(FingerprintName,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); // Make the request await osLoginServiceClient.DeleteSshPublicKeyAsync(name); // End snippet } /// <summary>Snippet for DeleteSshPublicKey</summary> public void DeleteSshPublicKey() { // Snippet: DeleteSshPublicKey(FingerprintName,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); // Make the request osLoginServiceClient.DeleteSshPublicKey(name); // End snippet } /// <summary>Snippet for DeleteSshPublicKeyAsync</summary> public async Task DeleteSshPublicKeyAsync_RequestObject() { // Snippet: DeleteSshPublicKeyAsync(DeleteSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { FingerprintName = new FingerprintName("[USER]", "[FINGERPRINT]"), }; // Make the request await osLoginServiceClient.DeleteSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for DeleteSshPublicKey</summary> public void DeleteSshPublicKey_RequestObject() { // Snippet: DeleteSshPublicKey(DeleteSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { FingerprintName = new FingerprintName("[USER]", "[FINGERPRINT]"), }; // Make the request osLoginServiceClient.DeleteSshPublicKey(request); // End snippet } /// <summary>Snippet for GetLoginProfileAsync</summary> public async Task GetLoginProfileAsync() { // Snippet: GetLoginProfileAsync(UserName,CallSettings) // Additional: GetLoginProfileAsync(UserName,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UserName name = new UserName("[USER]"); // Make the request LoginProfile response = await osLoginServiceClient.GetLoginProfileAsync(name); // End snippet } /// <summary>Snippet for GetLoginProfile</summary> public void GetLoginProfile() { // Snippet: GetLoginProfile(UserName,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName name = new UserName("[USER]"); // Make the request LoginProfile response = osLoginServiceClient.GetLoginProfile(name); // End snippet } /// <summary>Snippet for GetLoginProfileAsync</summary> public async Task GetLoginProfileAsync_RequestObject() { // Snippet: GetLoginProfileAsync(GetLoginProfileRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = new UserName("[USER]"), }; // Make the request LoginProfile response = await osLoginServiceClient.GetLoginProfileAsync(request); // End snippet } /// <summary>Snippet for GetLoginProfile</summary> public void GetLoginProfile_RequestObject() { // Snippet: GetLoginProfile(GetLoginProfileRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = new UserName("[USER]"), }; // Make the request LoginProfile response = osLoginServiceClient.GetLoginProfile(request); // End snippet } /// <summary>Snippet for GetSshPublicKeyAsync</summary> public async Task GetSshPublicKeyAsync() { // Snippet: GetSshPublicKeyAsync(FingerprintName,CallSettings) // Additional: GetSshPublicKeyAsync(FingerprintName,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); // Make the request SshPublicKey response = await osLoginServiceClient.GetSshPublicKeyAsync(name); // End snippet } /// <summary>Snippet for GetSshPublicKey</summary> public void GetSshPublicKey() { // Snippet: GetSshPublicKey(FingerprintName,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); // Make the request SshPublicKey response = osLoginServiceClient.GetSshPublicKey(name); // End snippet } /// <summary>Snippet for GetSshPublicKeyAsync</summary> public async Task GetSshPublicKeyAsync_RequestObject() { // Snippet: GetSshPublicKeyAsync(GetSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { FingerprintName = new FingerprintName("[USER]", "[FINGERPRINT]"), }; // Make the request SshPublicKey response = await osLoginServiceClient.GetSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for GetSshPublicKey</summary> public void GetSshPublicKey_RequestObject() { // Snippet: GetSshPublicKey(GetSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { FingerprintName = new FingerprintName("[USER]", "[FINGERPRINT]"), }; // Make the request SshPublicKey response = osLoginServiceClient.GetSshPublicKey(request); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKeyAsync1() { // Snippet: ImportSshPublicKeyAsync(UserName,SshPublicKey,CallSettings) // Additional: ImportSshPublicKeyAsync(UserName,SshPublicKey,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UserName parent = new UserName("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(parent, sshPublicKey); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey1() { // Snippet: ImportSshPublicKey(UserName,SshPublicKey,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName parent = new UserName("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKeyAsync2() { // Snippet: ImportSshPublicKeyAsync(UserName,SshPublicKey,string,CallSettings) // Additional: ImportSshPublicKeyAsync(UserName,SshPublicKey,string,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UserName parent = new UserName("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(parent, sshPublicKey, projectId); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey2() { // Snippet: ImportSshPublicKey(UserName,SshPublicKey,string,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName parent = new UserName("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey, projectId); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKeyAsync_RequestObject() { // Snippet: ImportSshPublicKeyAsync(ImportSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = new UserName("[USER]"), SshPublicKey = new SshPublicKey(), }; // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey_RequestObject() { // Snippet: ImportSshPublicKey(ImportSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = new UserName("[USER]"), SshPublicKey = new SshPublicKey(), }; // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(request); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKeyAsync1() { // Snippet: UpdateSshPublicKeyAsync(FingerprintName,SshPublicKey,CallSettings) // Additional: UpdateSshPublicKeyAsync(FingerprintName,SshPublicKey,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey1() { // Snippet: UpdateSshPublicKey(FingerprintName,SshPublicKey,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(name, sshPublicKey); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKeyAsync2() { // Snippet: UpdateSshPublicKeyAsync(FingerprintName,SshPublicKey,FieldMask,CallSettings) // Additional: UpdateSshPublicKeyAsync(FingerprintName,SshPublicKey,FieldMask,CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey, updateMask); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey2() { // Snippet: UpdateSshPublicKey(FingerprintName,SshPublicKey,FieldMask,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) FingerprintName name = new FingerprintName("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(name, sshPublicKey, updateMask); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKeyAsync_RequestObject() { // Snippet: UpdateSshPublicKeyAsync(UpdateSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { FingerprintName = new FingerprintName("[USER]", "[FINGERPRINT]"), SshPublicKey = new SshPublicKey(), }; // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey_RequestObject() { // Snippet: UpdateSshPublicKey(UpdateSshPublicKeyRequest,CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { FingerprintName = new FingerprintName("[USER]", "[FINGERPRINT]"), SshPublicKey = new SshPublicKey(), }; // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(request); // End snippet } } }
using System; using System.Diagnostics; using Raksha.Crypto; using Raksha.Crypto.Parameters; namespace Raksha.Crypto.Modes { /** * A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to * be used to produce cipher text which is the same outLength as the plain text. */ public class CtsBlockCipher : BufferedBlockCipher { private readonly int blockSize; /** * Create a buffered block cipher that uses Cipher Text Stealing * * @param cipher the underlying block cipher this buffering object wraps. */ public CtsBlockCipher( IBlockCipher cipher) { // TODO Should this test for acceptable ones instead? if (cipher is OfbBlockCipher || cipher is CfbBlockCipher) throw new ArgumentException("CtsBlockCipher can only accept ECB, or CBC ciphers"); this.cipher = cipher; blockSize = cipher.GetBlockSize(); buf = new byte[blockSize * 2]; bufOff = 0; } /** * return the size of the output buffer required for an update of 'length' bytes. * * @param length the outLength of the input. * @return the space required to accommodate a call to update * with length bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; if (leftOver == 0) { return total - buf.Length; } return total - leftOver; } /** * return the size of the output buffer required for an update plus a * doFinal with an input of length bytes. * * @param length the outLength of the input. * @return the space required to accommodate a call to update and doFinal * with length bytes of input. */ public override int GetOutputSize( int length) { return length + bufOff; } /** * process a single byte, producing an output block if neccessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { int resultLen = 0; if (bufOff == buf.Length) { resultLen = cipher.ProcessBlock(buf, 0, output, outOff); Debug.Assert(resultLen == blockSize); Array.Copy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; } buf[bufOff++] = input; return resultLen; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param length the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if (length < 0) { throw new ArgumentException("Can't have a negative input outLength!"); } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if (outLength > 0) { if ((outOff + outLength) > output.Length) { throw new DataLengthException("output buffer too short"); } } int resultLen = 0; int gapLen = buf.Length - bufOff; if (length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); Array.Copy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; length -= gapLen; inOff += gapLen; while (length > blockSize) { Array.Copy(input, inOff, buf, bufOff, blockSize); resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); Array.Copy(buf, blockSize, buf, 0, blockSize); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; return resultLen; } /** * Process the last block in the buffer. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if cipher text decrypts wrongly (in * case the exception will never Get thrown). */ public override int DoFinal( byte[] output, int outOff) { if (bufOff + outOff > output.Length) { throw new DataLengthException("output buffer too small in doFinal"); } int blockSize = cipher.GetBlockSize(); int length = bufOff - blockSize; byte[] block = new byte[blockSize]; if (forEncryption) { cipher.ProcessBlock(buf, 0, block, 0); if (bufOff < blockSize) { throw new DataLengthException("need at least one block of input for CTS"); } for (int i = bufOff; i != buf.Length; i++) { buf[i] = block[i - blockSize]; } for (int i = blockSize; i != bufOff; i++) { buf[i] ^= block[i - blockSize]; } IBlockCipher c = (cipher is CbcBlockCipher) ? ((CbcBlockCipher)cipher).GetUnderlyingCipher() : cipher; c.ProcessBlock(buf, blockSize, output, outOff); Array.Copy(block, 0, output, outOff + blockSize, length); } else { byte[] lastBlock = new byte[blockSize]; IBlockCipher c = (cipher is CbcBlockCipher) ? ((CbcBlockCipher)cipher).GetUnderlyingCipher() : cipher; c.ProcessBlock(buf, 0, block, 0); for (int i = blockSize; i != bufOff; i++) { lastBlock[i - blockSize] = (byte)(block[i - blockSize] ^ buf[i]); } Array.Copy(buf, blockSize, block, 0, length); cipher.ProcessBlock(block, 0, output, outOff); Array.Copy(lastBlock, 0, output, outOff + blockSize, length); } int offset = bufOff; Reset(); return offset; } } }
using Loon.Utils; using System.Runtime.CompilerServices; namespace Loon.Core.Geom { public abstract class Shape { internal ShapeType type; public float x; public float y; protected internal float rotation; protected internal float[] points; protected internal float[] center; protected internal float scaleX, scaleY; protected internal float maxX, maxY; protected internal float minX, minY; protected internal float boundingCircleRadius; protected internal bool pointsDirty; protected internal Triangle triangle; protected internal bool trianglesDirty; protected internal AABB aabb; protected internal RectBox rect; public Shape() { pointsDirty = true; type = ShapeType.DEFAULT_SHAPE; scaleX = scaleY = 1f; } public virtual void SetLocation(float x_0, float y_1) { SetX(x_0); SetY(y_1); } public abstract Shape Transform(Matrix transform); protected abstract internal void CreatePoints(); public void Translate(int deltaX, int deltaY) { SetX(x + deltaX); SetY(y + deltaY); } public virtual float GetX() { return x; } public virtual void SetX(float x_0) { if (x_0 != this.x || x_0 == 0) { float dx = x_0 - this.x; this.x = x_0; if ((points == null) || (center == null)) { CheckPoints(); } for (int i = 0; i < points.Length / 2; i++) { points[i * 2] += dx; } center[0] += dx; x_0 += dx; maxX += dx; minX += dx; trianglesDirty = true; } } public virtual void SetY(float y_0) { if (y_0 != this.y || y_0 == 0) { float dy = y_0 - this.y; this.y = y_0; if ((points == null) || (center == null)) { CheckPoints(); } for (int i = 0; i < points.Length / 2; i++) { points[(i * 2) + 1] += dy; } center[1] += dy; y_0 += dy; maxY += dy; minY += dy; trianglesDirty = true; } } public virtual float GetY() { return y; } public virtual float Length() { return MathUtils.Sqrt(x * x + y * y); } public void SetLocation(Vector2f loc) { SetX(loc.x); SetY(loc.y); } public virtual float GetCenterX() { CheckPoints(); return center[0]; } public void SetCenterX(float centerX) { if ((points == null) || (center == null)) { CheckPoints(); } float xDiff = centerX - GetCenterX(); SetX(x + xDiff); } public virtual float GetCenterY() { CheckPoints(); return center[1]; } public void SetCenterY(float centerY) { if ((points == null) || (center == null)) { CheckPoints(); } float yDiff = centerY - GetCenterY(); SetY(y + yDiff); } public virtual float GetMaxX() { CheckPoints(); return maxX; } public virtual float GetMaxY() { CheckPoints(); return maxY; } public virtual float GetMinX() { CheckPoints(); return minX; } public virtual float GetMinY() { CheckPoints(); return minY; } public float GetBoundingCircleRadius() { CheckPoints(); return boundingCircleRadius; } public float[] GetCenter() { CheckPoints(); return center; } public float[] GetPoints() { CheckPoints(); return points; } public int GetPointCount() { CheckPoints(); return points.Length / 2; } public float[] GetPoint(int index) { CheckPoints(); float[] result = new float[2]; result[0] = points[index * 2]; result[1] = points[index * 2 + 1]; return result; } public float[] GetNormal(int index) { float[] current = GetPoint(index); float[] prev = GetPoint((index - 1 < 0) ? GetPointCount() - 1 : index - 1); float[] next = GetPoint((index + 1 >= GetPointCount()) ? 0 : index + 1); float[] t1 = GetNormal(prev, current); float[] t2 = GetNormal(current, next); if ((index == 0) && (!Closed())) { return t2; } if ((index == GetPointCount() - 1) && (!Closed())) { return t1; } float tx = (t1[0] + t2[0]) / 2; float ty = (t1[1] + t2[1]) / 2; float len = MathUtils.Sqrt((tx * tx) + (ty * ty)); return new float[] { tx / len, ty / len }; } public bool Contains(Shape other) { if (other.Intersects(this)) { return false; } for (int i = 0; i < other.GetPointCount(); i++) { float[] pt = other.GetPoint(i); if (!Contains(pt[0], pt[1])) { return false; } } return true; } private float[] GetNormal(float[] start, float[] end) { float dx = start[0] - end[0]; float dy = start[1] - end[1]; float len = MathUtils.Sqrt((dx * dx) + (dy * dy)); dx /= len; dy /= len; return new float[] { -dy, dx }; } public bool Includes(float x_0, float y_1) { if (points.Length == 0) { return false; } CheckPoints(); Line testLine = new Line(0, 0, 0, 0); Vector2f pt = new Vector2f(x_0, y_1); for (int i = 0; i < points.Length; i += 2) { int n = i + 2; if (n >= points.Length) { n = 0; } testLine.Set(points[i], points[i + 1], points[n], points[n + 1]); if (testLine.On(pt)) { return true; } } return false; } public int IndexOf(float x_0, float y_1) { for (int i = 0; i < points.Length; i += 2) { if ((points[i] == x_0) && (points[i + 1] == y_1)) { return i / 2; } } return -1; } public virtual bool Contains(float x_0, float y_1) { CheckPoints(); if (points.Length == 0) { return false; } bool result = false; float xnew, ynew; float xold, yold; float x1, y1; float x2, y2; int npoints = points.Length; xold = points[npoints - 2]; yold = points[npoints - 1]; for (int i = 0; i < npoints; i += 2) { xnew = points[i]; ynew = points[i + 1]; if (xnew > xold) { x1 = xold; x2 = xnew; y1 = yold; y2 = ynew; } else { x1 = xnew; x2 = xold; y1 = ynew; y2 = yold; } if ((xnew < x_0) == (x_0 <= xold) && ((double) y_1 - (double) y1) * (x2 - x1) < ((double) y2 - (double) y1) * (x_0 - x1)) { result = !result; } xold = xnew; yold = ynew; } return result; } public virtual bool Intersects(Shape shape) { if (shape == null) { return false; } CheckPoints(); bool result = false; float[] points_0 = GetPoints(); float[] thatPoints = shape.GetPoints(); int length = points_0.Length; int thatLength = thatPoints.Length; double unknownA; double unknownB; if (!Closed()) { length -= 2; } if (!shape.Closed()) { thatLength -= 2; } for (int i = 0; i < length; i += 2) { int iNext = i + 2; if (iNext >= points_0.Length) { iNext = 0; } for (int j = 0; j < thatLength; j += 2) { int jNext = j + 2; if (jNext >= thatPoints.Length) { jNext = 0; } unknownA = (((points_0[iNext] - points_0[i]) * (double) (thatPoints[j + 1] - points_0[i + 1])) - ((points_0[iNext + 1] - points_0[i + 1]) * (thatPoints[j] - points_0[i]))) / (((points_0[iNext + 1] - points_0[i + 1]) * (thatPoints[jNext] - thatPoints[j])) - ((points_0[iNext] - points_0[i]) * (thatPoints[jNext + 1] - thatPoints[j + 1]))); unknownB = (((thatPoints[jNext] - thatPoints[j]) * (double) (thatPoints[j + 1] - points_0[i + 1])) - ((thatPoints[jNext + 1] - thatPoints[j + 1]) * (thatPoints[j] - points_0[i]))) / (((points_0[iNext + 1] - points_0[i + 1]) * (thatPoints[jNext] - thatPoints[j])) - ((points_0[iNext] - points_0[i]) * (thatPoints[jNext + 1] - thatPoints[j + 1]))); if (unknownA >= 0 && unknownA <= 1 && unknownB >= 0 && unknownB <= 1) { result = true; break; } } if (result) { break; } } return result; } public bool HasVertex(float x_0, float y_1) { if (points.Length == 0) { return false; } CheckPoints(); for (int i = 0; i < points.Length; i += 2) { if ((points[i] == x_0) && (points[i + 1] == y_1)) { return true; } } return false; } protected internal virtual void FindCenter() { center = new float[] { 0, 0 }; int length = points.Length; for (int i = 0; i < length; i += 2) { center[0] += points[i]; center[1] += points[i + 1]; } center[0] /= (length / 2); center[1] /= (length / 2); } protected internal virtual void CalculateRadius() { boundingCircleRadius = 0; for (int i = 0; i < points.Length; i += 2) { float temp = ((points[i] - center[0]) * (points[i] - center[0])) + ((points[i + 1] - center[1]) * (points[i + 1] - center[1])); boundingCircleRadius = (boundingCircleRadius > temp) ? boundingCircleRadius : temp; } boundingCircleRadius = MathUtils.Sqrt(boundingCircleRadius); } protected internal void CalculateTriangles() { if ((!trianglesDirty) && (triangle != null)) { return; } if (points.Length >= 6) { triangle = new TriangleNeat(); for (int i = 0; i < points.Length; i += 2) { triangle.AddPolyPoint(points[i], points[i + 1]); } triangle.Triangulate(); } trianglesDirty = false; } private void CallTransform(Matrix m) { if (points != null) { float[] result = new float[points.Length]; m.Transform(points, 0, result, 0, points.Length / 2); this.points = result; this.CheckPoints(); } } public void SetScale(float s) { this.SetScale(s, s); } public virtual void SetScale(float sx, float sy) { if (scaleX != sx || scaleY != sy) { Matrix m = new Matrix(); m.Scale(scaleX = sx, scaleY = sy); this.CallTransform(m); } } public float GetScaleX() { return scaleX; } public float GetScaleY() { return scaleY; } public void SetRotation(float r) { if (rotation != r) { this.CallTransform(Matrix.CreateRotateTransform( rotation = (r / 180f * MathUtils.PI), this.center[0], this.center[1])); } } public void SetRotation(float r, float x_0, float y_1) { if (rotation != r) { this.CallTransform(Matrix.CreateRotateTransform( rotation = (r / 180f * MathUtils.PI), x_0, y_1)); } } public float GetRotation() { return (rotation * 180f / MathUtils.PI); } public void IncreaseTriangulation() { CheckPoints(); CalculateTriangles(); triangle = new TriangleOver(triangle); } public Triangle GetTriangles() { CheckPoints(); CalculateTriangles(); return triangle; } [MethodImpl(MethodImplOptions.Synchronized)] protected internal void CheckPoints() { if (pointsDirty) { CreatePoints(); FindCenter(); CalculateRadius(); if (points == null) { return; } lock (points) { int size = points.Length; if (size > 0) { maxX = points[0]; maxY = points[1]; minX = points[0]; minY = points[1]; for (int i = 0; i < size / 2; i++) { maxX = MathUtils.Max(points[i * 2], maxX); maxY = MathUtils.Max(points[(i * 2) + 1], maxY); minX = MathUtils.Min(points[i * 2], minX); minY = MathUtils.Min(points[(i * 2) + 1], minY); } } pointsDirty = false; trianglesDirty = true; } } } public void PreCache() { CheckPoints(); GetTriangles(); } public virtual bool Closed() { return true; } public Shape Prune() { Polygon result = new Polygon(); for (int i = 0; i < GetPointCount(); i++) { int next = (i + 1 >= GetPointCount()) ? 0 : i + 1; int prev = (i - 1 < 0) ? GetPointCount() - 1 : i - 1; float dx1 = GetPoint(i)[0] - GetPoint(prev)[0]; float dy1 = GetPoint(i)[1] - GetPoint(prev)[1]; float dx2 = GetPoint(next)[0] - GetPoint(i)[0]; float dy2 = GetPoint(next)[1] - GetPoint(i)[1]; float len1 = MathUtils.Sqrt((dx1 * dx1) + (dy1 * dy1)); float len2 = MathUtils.Sqrt((dx2 * dx2) + (dy2 * dy2)); dx1 /= len1; dy1 /= len1; dx2 /= len2; dy2 /= len2; if ((dx1 != dx2) || (dy1 != dy2)) { result.AddPoint(GetPoint(i)[0], GetPoint(i)[1]); } } return result; } public virtual float GetWidth() { return maxX - minX; } public virtual float GetHeight() { return maxY - minY; } public ShapeType GetShapeType() { return this.type; } public virtual RectBox GetRect() { if (rect == null) { rect = new RectBox(x, y, GetWidth(), GetHeight()); } else { rect.SetBounds(x, y, GetWidth(), GetHeight()); } return rect; } public AABB GetAABB() { if (aabb == null) { aabb = new AABB(minX, minY, maxX, maxY); } else { aabb.Set(minX, minY, maxX, maxY); } return aabb; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Finance.Server.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// TrustedIdProvidersOperations operations. /// </summary> internal partial class TrustedIdProvidersOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, ITrustedIdProvidersOperations { /// <summary> /// Initializes a new instance of the TrustedIdProvidersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal TrustedIdProvidersOperations(DataLakeStoreAccountManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the DataLakeStoreAccountManagementClient /// </summary> public DataLakeStoreAccountManagementClient Client { get; private set; } /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced /// with this new provider /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to add the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for /// differentiation of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create the create the trusted identity provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<TrustedIdProvider>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<TrustedIdProvider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new 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 HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<TrustedIdProvider>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<TrustedIdProvider>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<TrustedIdProvider>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<TrustedIdProvider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<TrustedIdProvider>>> ListByAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<TrustedIdProvider>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/************************************************************************* Copyright (c) 1992-2007 The University of Tennessee. All rights reserved. Contributors: * Sergey Bochkanov (ALGLIB project). Translation from FORTRAN to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ using System; namespace FuncLib.Mathematics.LinearAlgebra.AlgLib { internal class hblas { public static void hermitianmatrixvectormultiply(ref AP.Complex[,] a, bool isupper, int i1, int i2, ref AP.Complex[] x, AP.Complex alpha, ref AP.Complex[] y) { int i = 0; int ba1 = 0; int ba2 = 0; int by1 = 0; int by2 = 0; int bx1 = 0; int bx2 = 0; int n = 0; AP.Complex v = 0; int i_ = 0; int i1_ = 0; n = i2 - i1 + 1; if (n <= 0) { return; } // // Let A = L + D + U, where // L is strictly lower triangular (main diagonal is zero) // D is diagonal // U is strictly upper triangular (main diagonal is zero) // // A*x = L*x + D*x + U*x // // Calculate D*x first // for (i = i1; i <= i2; i++) { y[i - i1 + 1] = a[i, i] * x[i - i1 + 1]; } // // Add L*x + U*x // if (isupper) { for (i = i1; i <= i2 - 1; i++) { // // Add L*x to the result // v = x[i - i1 + 1]; by1 = i - i1 + 2; by2 = n; ba1 = i + 1; ba2 = i2; i1_ = (ba1) - (by1); for (i_ = by1; i_ <= by2; i_++) { y[i_] = y[i_] + v * AP.Math.Conj(a[i, i_ + i1_]); } // // Add U*x to the result // bx1 = i - i1 + 2; bx2 = n; ba1 = i + 1; ba2 = i2; i1_ = (ba1) - (bx1); v = 0.0; for (i_ = bx1; i_ <= bx2; i_++) { v += x[i_] * a[i, i_ + i1_]; } y[i - i1 + 1] = y[i - i1 + 1] + v; } } else { for (i = i1 + 1; i <= i2; i++) { // // Add L*x to the result // bx1 = 1; bx2 = i - i1; ba1 = i1; ba2 = i - 1; i1_ = (ba1) - (bx1); v = 0.0; for (i_ = bx1; i_ <= bx2; i_++) { v += x[i_] * a[i, i_ + i1_]; } y[i - i1 + 1] = y[i - i1 + 1] + v; // // Add U*x to the result // v = x[i - i1 + 1]; by1 = 1; by2 = i - i1; ba1 = i1; ba2 = i - 1; i1_ = (ba1) - (by1); for (i_ = by1; i_ <= by2; i_++) { y[i_] = y[i_] + v * AP.Math.Conj(a[i, i_ + i1_]); } } } for (i_ = 1; i_ <= n; i_++) { y[i_] = alpha * y[i_]; } } public static void hermitianrank2update(ref AP.Complex[,] a, bool isupper, int i1, int i2, ref AP.Complex[] x, ref AP.Complex[] y, ref AP.Complex[] t, AP.Complex alpha) { int i = 0; int tp1 = 0; int tp2 = 0; AP.Complex v = 0; int i_ = 0; int i1_ = 0; if (isupper) { for (i = i1; i <= i2; i++) { tp1 = i + 1 - i1; tp2 = i2 - i1 + 1; v = alpha * x[i + 1 - i1]; for (i_ = tp1; i_ <= tp2; i_++) { t[i_] = v * AP.Math.Conj(y[i_]); } v = AP.Math.Conj(alpha) * y[i + 1 - i1]; for (i_ = tp1; i_ <= tp2; i_++) { t[i_] = t[i_] + v * AP.Math.Conj(x[i_]); } i1_ = (tp1) - (i); for (i_ = i; i_ <= i2; i_++) { a[i, i_] = a[i, i_] + t[i_ + i1_]; } } } else { for (i = i1; i <= i2; i++) { tp1 = 1; tp2 = i + 1 - i1; v = alpha * x[i + 1 - i1]; for (i_ = tp1; i_ <= tp2; i_++) { t[i_] = v * AP.Math.Conj(y[i_]); } v = AP.Math.Conj(alpha) * y[i + 1 - i1]; for (i_ = tp1; i_ <= tp2; i_++) { t[i_] = t[i_] + v * AP.Math.Conj(x[i_]); } i1_ = (tp1) - (i1); for (i_ = i1; i_ <= i; i_++) { a[i, i_] = a[i, i_] + t[i_ + i1_]; } } } } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using Glass.Mapper.Sc.FakeDb.Infrastructure; using Glass.Mapper.Sc.FakeDb.Infrastructure.Pipelines.RenderField; using NUnit.Framework; using Sitecore.FakeDb; using Sitecore.Sites; namespace Glass.Mapper.Sc.FakeDb.DataMappers { [TestFixture] public class SitecoreFieldStringMapperFixture { protected const string FieldName = "Field"; #region Method - GetField [Test] public void GetField_FieldContainsData_StringIsReturned() { //Assign var fieldValue = "<p>hello world</p>"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); using (new ItemEditing(item, true)) { field.Value = fieldValue; } //Act var result = mapper.GetField(field, config, null) as string; //Assert Assert.AreEqual(fieldValue, result); } } [Test] public void GetField_ForceRenderFieldPipeline_StringIsReturned() { //Assign var fieldValue = SimpleRenderField.ReplacementKey + "<p>hello world</p>"; var expected = SimpleRenderField.ReplacementValue + "<p>hello world</p>"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { using (new FakeSite()) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); config.Setting = SitecoreFieldSettings.ForceRenderField; using (new ItemEditing(item, true)) { field.Value = fieldValue; } Sitecore.Context.Site = Sitecore.Configuration.Factory.GetSite("website"); Sitecore.Context.Site.SetDisplayMode(DisplayMode.Preview, DisplayModeDuration.Remember); //Act var result = mapper.GetField(field, config, null) as string; //Assert Sitecore.Context.Site = null; Assert.AreEqual(expected, result); } } } [Test] public void SetField_ForceRenderFieldPipeline_ThrowsException() { //Assign var fieldValue = "<p>hello world</p>"; var expected = "&lt;p&gt;hello world&lt;/p&gt;"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); config.Setting = SitecoreFieldSettings.ForceRenderField; config.PropertyInfo = new FakePropertyInfo(typeof(string), "String", typeof(StubClass)); using (new ItemEditing(item, true)) { field.Value = fieldValue; } //Act Assert.Throws<NotSupportedException>(()=> mapper.SetField(field, fieldValue, config, null)); //Assert } } [Test] public void GetField_RichText_ValueGoesByRenderFieldPipeline() { //Assign var fieldBase = "<p>Test with <a href=\"~/link.aspx?_id=BFD7975DF42F41E19DDA9A38E971555F&amp;_z=z\">link</a></p>"; var fieldValue = SimpleRenderField.ReplacementKey + fieldBase; ; var expected = SimpleRenderField.ReplacementValue + fieldBase; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue, Type = "Rich Text" } } }) { using (new FakeSite()) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); Sitecore.Context.Site = Sitecore.Configuration.Factory.GetSite("website"); Sitecore.Context.Site.SetDisplayMode(DisplayMode.Preview, DisplayModeDuration.Remember); using (new ItemEditing(item, true)) { field.Value = fieldValue; } //Act var result = mapper.GetField(field, config, null) as string; Sitecore.Context.Site = null; //Assert Assert.AreEqual(expected, result); } } } [Test] public void GetField_RichTextSettingsIsRaw_StringIsReturnedWithoutEscaping() { //Assign var fieldValue = "<p>Test with <a href=\"~/link.aspx?_id=BFD7975DF42F41E19DDA9A38E971555F&amp;_z=z\">link</a></p>"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Value = fieldValue } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); config.Setting = SitecoreFieldSettings.RichTextRaw; Sitecore.Context.Site = Sitecore.Configuration.Factory.GetSite("website"); using (new ItemEditing(item, true)) { field.Value = fieldValue; } //Act var result = mapper.GetField(field, config, null) as string; Sitecore.Context.Site = null; //Assert Assert.AreEqual(fieldValue, result); } } #endregion #region Method - SetField [Test] public void SetField_RichText_ThrowsException() { //Assign var expected = "<p>Test with <a href=\"~/link.aspx?_id=BFD7975DF42F41E19DDA9A38E971555F&amp;_z=z\">link</a></p>"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { Type = "Rich Text" } } }) { using (new FakeSite()) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(StubClass).GetProperty("String"); Sitecore.Context.Site = Sitecore.Configuration.Factory.GetSite("website"); using (new ItemEditing(item, true)) { field.Value = string.Empty; } //Act using (new ItemEditing(item, true)) { //Rich text not raw throws exception Assert.Throws<NotSupportedException>(() => mapper.SetField(field, expected, config, null)); } Sitecore.Context.Site = null; //Assert Assert.AreEqual(string.Empty, field.Value); } } } [Test] public void SetField_FielNonRichText_ValueWrittenToField() { //Assign var expected = "<p>Test with <a href=\"~/link.aspx?_id=BFD7975DF42F41E19DDA9A38E971555F&amp;_z=z\">link</a></p>"; using (Db database = new Db { new Sitecore.FakeDb.DbItem("TestItem") { new DbField(FieldName) { } } }) { var item = database.GetItem("/sitecore/content/TestItem"); var field = item.Fields[FieldName]; var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); config.Setting = SitecoreFieldSettings.RichTextRaw; Sitecore.Context.Site = Sitecore.Configuration.Factory.GetSite("website"); using (new ItemEditing(item, true)) { field.Value = string.Empty; } //Act using (new ItemEditing(item, true)) { mapper.SetField(field, expected, config, null); } Sitecore.Context.Site = null; //Assert Assert.AreEqual(expected, field.Value); } } #endregion #region Method - CanHandle [Test] public void CanHandle_StreamType_ReturnsTrue() { //Assign var mapper = new SitecoreFieldStringMapper(); var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("String"); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } #endregion #region Stub public class StubClass { public string String { get; set; } } #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; using System.Buffers; using System.Buffers.Binary; using System.Diagnostics; using System.Text; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial; using Microsoft.Win32.SafeHandles; using CryptProvParam=Interop.Advapi32.CryptProvParam; using static Interop.Crypt32; namespace Internal.Cryptography.Pal.Windows { internal static class HelpersWindows { public static CryptographicException ToCryptographicException(this ErrorCode errorCode) { return ((int)errorCode).ToCryptographicException(); } public static string ToStringAnsi(this IntPtr psz) { return Marshal.PtrToStringAnsi(psz); } // Used for binary blobs without internal pointers. public static byte[] GetMsgParamAsByteArray(this SafeCryptMsgHandle hCryptMsg, CryptMsgParamType paramType, int index = 0) { int cbData = 0; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, null, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] pvData = new byte[cbData]; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, pvData, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return pvData.Resize(cbData); } // Used for binary blobs with internal pointers. public static SafeHandle GetMsgParamAsMemory(this SafeCryptMsgHandle hCryptMsg, CryptMsgParamType paramType, int index = 0) { int cbData = 0; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, null, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); SafeHandle pvData = SafeHeapAllocHandle.Alloc(cbData); if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, pvData.DangerousGetHandle(), ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return pvData; } public static byte[] ToByteArray(this DATA_BLOB blob) { if (blob.cbData == 0) return Array.Empty<byte>(); int length = (int)(blob.cbData); byte[] data = new byte[length]; Marshal.Copy(blob.pbData, data, 0, length); return data; } public static CryptMsgType GetMessageType(this SafeCryptMsgHandle hCryptMsg) { int cbData = sizeof(CryptMsgType); CryptMsgType cryptMsgType; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_TYPE_PARAM, 0, out cryptMsgType, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return cryptMsgType; } public static int GetVersion(this SafeCryptMsgHandle hCryptMsg) { int cbData = sizeof(int); int version; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_VERSION_PARAM, 0, out version, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return version; } /// <summary> /// Returns the inner content of the CMS. /// /// Special case: If the CMS is an enveloped CMS that has been decrypted and the inner content type is Oids.Pkcs7Data, the returned /// content bytes are the decoded octet bytes, rather than the encoding of those bytes. This is a documented convenience behavior of /// CryptMsgGetParam(CMSG_CONTENT_PARAM) that apparently got baked into the behavior of the managed EnvelopedCms class. /// </summary> public static ContentInfo GetContentInfo(this SafeCryptMsgHandle hCryptMsg) { byte[] oidBytes = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_INNER_CONTENT_TYPE_PARAM); // Desktop compat: If we get a null or non-terminated string back from Crypt32, throwing an exception seems more apropros but // for the desktop compat, we throw the result at the ASCII Encoder and let the chips fall where they may. int length = oidBytes.Length; if (length > 0 && oidBytes[length - 1] == 0) { length--; } string oidValue = Encoding.ASCII.GetString(oidBytes, 0, length); Oid contentType = new Oid(oidValue); byte[] content = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return new ContentInfo(contentType, content); } public static X509Certificate2Collection GetOriginatorCerts(this SafeCryptMsgHandle hCryptMsg) { int numCertificates = 0; int cbNumCertificates = sizeof(int); if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_CERT_COUNT_PARAM, 0, out numCertificates, ref cbNumCertificates)) throw Marshal.GetLastWin32Error().ToCryptographicException(); X509Certificate2Collection certs = new X509Certificate2Collection(); for (int index = 0; index < numCertificates; index++) { byte[] encodedCertificate = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CERT_PARAM, index); X509Certificate2 cert = new X509Certificate2(encodedCertificate); certs.Add(cert); } return certs; } /// <summary> /// Returns (AlgId)(-1) if oid is unknown. /// </summary> public static AlgId ToAlgId(this string oidValue) { CRYPT_OID_INFO info = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oidValue, OidGroup.All, false); return (AlgId)(info.AlgId); } public static SafeCertContextHandle CreateCertContextHandle(this X509Certificate2 cert) { IntPtr pCertContext = cert.Handle; pCertContext = Interop.Crypt32.CertDuplicateCertificateContext(pCertContext); SafeCertContextHandle hCertContext = new SafeCertContextHandle(pCertContext); GC.KeepAlive(cert); return hCertContext; } public static unsafe byte[] GetSubjectKeyIdentifer(this SafeCertContextHandle hCertContext) { int cbData = 0; if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_IDENTIFIER_PROP_ID, null, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] ski = new byte[cbData]; if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_IDENTIFIER_PROP_ID, ski, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return ski.Resize(cbData); } public static SubjectIdentifier ToSubjectIdentifier(this CERT_ID certId) { switch (certId.dwIdChoice) { case CertIdChoice.CERT_ID_ISSUER_SERIAL_NUMBER: { const int dwStrType = (int)(CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG); string issuer; unsafe { DATA_BLOB* dataBlobPtr = &certId.u.IssuerSerialNumber.Issuer; int nc = Interop.Crypt32.CertNameToStr((int)MsgEncodingType.All, dataBlobPtr, dwStrType, null, 0); if (nc <= 1) // The API actually return 1 when it fails; which is not what the documentation says. { throw Marshal.GetLastWin32Error().ToCryptographicException(); } Span<char> name = nc <= 128 ? stackalloc char[128] : new char[nc]; fixed (char* namePtr = name) { nc = Interop.Crypt32.CertNameToStr((int)MsgEncodingType.All, dataBlobPtr, dwStrType, namePtr, nc); if (nc <= 1) // The API actually return 1 when it fails; which is not what the documentation says. { throw Marshal.GetLastWin32Error().ToCryptographicException(); } issuer = new string(namePtr); } } byte[] serial = certId.u.IssuerSerialNumber.SerialNumber.ToByteArray(); X509IssuerSerial issuerSerial = new X509IssuerSerial(issuer, serial.ToSerialString()); return new SubjectIdentifier(SubjectIdentifierType.IssuerAndSerialNumber, issuerSerial); } case CertIdChoice.CERT_ID_KEY_IDENTIFIER: { byte[] ski = certId.u.KeyId.ToByteArray(); return new SubjectIdentifier(SubjectIdentifierType.SubjectKeyIdentifier, ski.ToSkiString()); } default: throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, certId.dwIdChoice)); } } public static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this CERT_ID certId) { // // SubjectIdentifierOrKey is just a SubjectIdentifier with an (irrelevant here) "key" option thumbtacked onto it so // the easiest way is to subcontract the job to SubjectIdentifier. // SubjectIdentifier subjectIdentifier = certId.ToSubjectIdentifier(); SubjectIdentifierType subjectIdentifierType = subjectIdentifier.Type; switch (subjectIdentifierType) { case SubjectIdentifierType.IssuerAndSerialNumber: return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, subjectIdentifier.Value); case SubjectIdentifierType.SubjectKeyIdentifier: return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value); default: Debug.Fail("Only the framework can construct SubjectIdentifier's so if we got a bad value here, that's our fault."); throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, subjectIdentifierType)); } } public static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this CERT_PUBLIC_KEY_INFO publicKeyInfo) { int keyLength = Interop.Crypt32.CertGetPublicKeyLength(MsgEncodingType.All, ref publicKeyInfo); string oidValue = publicKeyInfo.Algorithm.pszObjId.ToStringAnsi(); AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(Oid.FromOidValue(oidValue, OidGroup.PublicKeyAlgorithm), keyLength); byte[] keyValue = publicKeyInfo.PublicKey.ToByteArray(); PublicKeyInfo pki = new PublicKeyInfo(algorithmId, keyValue); return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.PublicKeyInfo, pki); } public static AlgorithmIdentifier ToAlgorithmIdentifier(this CRYPT_ALGORITHM_IDENTIFIER cryptAlgorithmIdentifer) { string oidValue = cryptAlgorithmIdentifer.pszObjId.ToStringAnsi(); AlgId algId = oidValue.ToAlgId(); int keyLength; switch (algId) { case AlgId.CALG_RC2: { if (cryptAlgorithmIdentifer.Parameters.cbData == 0) { keyLength = 0; } else { CRYPT_RC2_CBC_PARAMETERS rc2Parameters; unsafe { int cbSize = sizeof(CRYPT_RC2_CBC_PARAMETERS); if (!Interop.Crypt32.CryptDecodeObject(CryptDecodeObjectStructType.PKCS_RC2_CBC_PARAMETERS, cryptAlgorithmIdentifer.Parameters.pbData, (int)(cryptAlgorithmIdentifer.Parameters.cbData), &rc2Parameters, ref cbSize)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } switch (rc2Parameters.dwVersion) { case CryptRc2Version.CRYPT_RC2_40BIT_VERSION: keyLength = KeyLengths.Rc2_40Bit; break; case CryptRc2Version.CRYPT_RC2_56BIT_VERSION: keyLength = KeyLengths.Rc2_56Bit; break; case CryptRc2Version.CRYPT_RC2_64BIT_VERSION: keyLength = KeyLengths.Rc2_64Bit; break; case CryptRc2Version.CRYPT_RC2_128BIT_VERSION: keyLength = KeyLengths.Rc2_128Bit; break; default: keyLength = 0; break; } } break; } case AlgId.CALG_RC4: { int saltLength = 0; if (cryptAlgorithmIdentifer.Parameters.cbData != 0) { using (SafeHandle sh = Interop.Crypt32.CryptDecodeObjectToMemory(CryptDecodeObjectStructType.X509_OCTET_STRING, cryptAlgorithmIdentifer.Parameters.pbData, (int)cryptAlgorithmIdentifer.Parameters.cbData)) { unsafe { DATA_BLOB* pDataBlob = (DATA_BLOB*)(sh.DangerousGetHandle()); saltLength = (int)(pDataBlob->cbData); } } } // For RC4, keyLength = 128 - (salt length * 8). keyLength = KeyLengths.Rc4Max_128Bit - saltLength * 8; break; } case AlgId.CALG_DES: // DES key length is fixed at 64 (or 56 without the parity bits). keyLength = KeyLengths.Des_64Bit; break; case AlgId.CALG_3DES: // 3DES key length is fixed at 192 (or 168 without the parity bits). keyLength = KeyLengths.TripleDes_192Bit; break; default: // We've exhausted all the algorithm types that the desktop used to set the KeyLength for. Key lengths are not a viable way of // identifying algorithms in the long run so we will not extend this list any further. keyLength = 0; break; } AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Oid.FromOidValue(oidValue, OidGroup.All), keyLength); switch (oidValue) { case Oids.RsaOaep: algorithmIdentifier.Parameters = cryptAlgorithmIdentifer.Parameters.ToByteArray(); break; } return algorithmIdentifier; } public static CryptographicAttributeObjectCollection GetUnprotectedAttributes(this SafeCryptMsgHandle hCryptMsg) { // For some reason, you can't ask how many attributes there are - you have to ask for the attributes and // get a CRYPT_E_ATTRIBUTES_MISSING failure if the count is 0. int cbUnprotectedAttr = 0; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_UNPROTECTED_ATTR_PARAM, 0, null, ref cbUnprotectedAttr)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == (int)ErrorCode.CRYPT_E_ATTRIBUTES_MISSING) return new CryptographicAttributeObjectCollection(); throw lastError.ToCryptographicException(); } using (SafeHandle sh = hCryptMsg.GetMsgParamAsMemory(CryptMsgParamType.CMSG_UNPROTECTED_ATTR_PARAM)) { unsafe { CRYPT_ATTRIBUTES* pCryptAttributes = (CRYPT_ATTRIBUTES*)(sh.DangerousGetHandle()); return ToCryptographicAttributeObjectCollection(pCryptAttributes); } } } public static CspParameters GetProvParameters(this SafeProvOrNCryptKeyHandle handle) { // A normal key container name is a GUID (~34 bytes ASCII) // The longest standard provider name is 64 bytes (including the \0), // but we shouldn't have a CAPI call with a software CSP. // // In debug builds use a buffer which will need to be resized, but is big // enough to hold the DWORD "can't fail" values. Span<byte> stackSpan = stackalloc byte[ #if DEBUG sizeof(int) #else 64 #endif ]; stackSpan.Clear(); int size = stackSpan.Length; if (!Interop.Advapi32.CryptGetProvParam(handle, CryptProvParam.PP_PROVTYPE, stackSpan, ref size)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (size != sizeof(int)) { Debug.Fail("PP_PROVTYPE writes a DWORD - enum misalignment?"); throw new CryptographicException(); } int provType = MemoryMarshal.Read<int>(stackSpan.Slice(0, size)); size = stackSpan.Length; if (!Interop.Advapi32.CryptGetProvParam(handle, CryptProvParam.PP_KEYSET_TYPE, stackSpan, ref size)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (size != sizeof(int)) { Debug.Fail("PP_KEYSET_TYPE writes a DWORD - enum misalignment?"); throw new CryptographicException(); } int keysetType = MemoryMarshal.Read<int>(stackSpan.Slice(0, size)); // Only CRYPT_MACHINE_KEYSET is described as coming back, but be defensive. CspProviderFlags provFlags = ((CspProviderFlags)keysetType & CspProviderFlags.UseMachineKeyStore) | CspProviderFlags.UseExistingKey; byte[] rented = null; Span<byte> asciiStringBuf = stackSpan; string provName = GetStringProvParam(handle, CryptProvParam.PP_NAME, ref asciiStringBuf, ref rented, 0); int maxClear = provName.Length; string keyName = GetStringProvParam(handle, CryptProvParam.PP_CONTAINER, ref asciiStringBuf, ref rented, maxClear); maxClear = Math.Max(maxClear, keyName.Length); if (rented != null) { CryptoPool.Return(rented, maxClear); } return new CspParameters(provType) { Flags = provFlags, KeyContainerName = keyName, ProviderName = provName, }; } private static string GetStringProvParam( SafeProvOrNCryptKeyHandle handle, CryptProvParam dwParam, ref Span<byte> buf, ref byte[] rented, int clearLen) { int len = buf.Length; if (!Interop.Advapi32.CryptGetProvParam(handle, dwParam, buf, ref len)) { if (len > buf.Length) { if (rented != null) { CryptoPool.Return(rented, clearLen); } rented = CryptoPool.Rent(len); buf = rented; len = rented.Length; } else { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (!Interop.Advapi32.CryptGetProvParam(handle, dwParam, buf, ref len)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } } unsafe { fixed (byte* asciiPtr = &MemoryMarshal.GetReference(buf)) { return Marshal.PtrToStringAnsi((IntPtr)asciiPtr, len); } } } private static unsafe CryptographicAttributeObjectCollection ToCryptographicAttributeObjectCollection(CRYPT_ATTRIBUTES* pCryptAttributes) { CryptographicAttributeObjectCollection collection = new CryptographicAttributeObjectCollection(); for (int i = 0; i < pCryptAttributes->cAttr; i++) { CRYPT_ATTRIBUTE* pCryptAttribute = &(pCryptAttributes->rgAttr[i]); AddCryptAttribute(collection, pCryptAttribute); } return collection; } private static unsafe void AddCryptAttribute(CryptographicAttributeObjectCollection collection, CRYPT_ATTRIBUTE* pCryptAttribute) { string oidValue = pCryptAttribute->pszObjId.ToStringAnsi(); Oid oid = new Oid(oidValue); AsnEncodedDataCollection attributeCollection = new AsnEncodedDataCollection(); for (int i = 0; i < pCryptAttribute->cValue; i++) { byte[] encodedAttribute = pCryptAttribute->rgValue[i].ToByteArray(); AsnEncodedData attributeObject = PkcsHelpers.CreateBestPkcs9AttributeObjectAvailable(oid, encodedAttribute); attributeCollection.Add(attributeObject); } collection.Add(new CryptographicAttributeObject(oid, attributeCollection)); } } }
namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IBits = Lucene.Net.Util.IBits; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using OpenBitSet = Lucene.Net.Util.OpenBitSet; /// <summary> /// Base class for <see cref="DocIdSet"/> to be used with <see cref="IFieldCache"/>. The implementation /// of its iterator is very stupid and slow if the implementation of the /// <see cref="MatchDoc(int)"/> method is not optimized, as iterators simply increment /// the document id until <see cref="MatchDoc(int)"/> returns <c>true</c>. Because of this /// <see cref="MatchDoc(int)"/> must be as fast as possible and in no case do any /// I/O. /// <para/> /// @lucene.internal /// </summary> public abstract class FieldCacheDocIdSet : DocIdSet { protected readonly int m_maxDoc; protected readonly IBits m_acceptDocs; public FieldCacheDocIdSet(int maxDoc, IBits acceptDocs) { this.m_maxDoc = maxDoc; this.m_acceptDocs = acceptDocs; } /// <summary> /// This method checks, if a doc is a hit /// </summary> protected internal abstract bool MatchDoc(int doc); /// <summary> /// This DocIdSet is always cacheable (does not go back /// to the reader for iteration) /// </summary> public override sealed bool IsCacheable { get { return true; } } public override sealed IBits Bits { get { return (m_acceptDocs == null) ? (IBits)new BitsAnonymousInnerClassHelper(this) : new BitsAnonymousInnerClassHelper2(this); } } private class BitsAnonymousInnerClassHelper : IBits { private readonly FieldCacheDocIdSet outerInstance; public BitsAnonymousInnerClassHelper(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; } public virtual bool Get(int docid) { return outerInstance.MatchDoc(docid); } public virtual int Length { get { return outerInstance.m_maxDoc; } } } private class BitsAnonymousInnerClassHelper2 : IBits { private readonly FieldCacheDocIdSet outerInstance; public BitsAnonymousInnerClassHelper2(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; } public virtual bool Get(int docid) { return outerInstance.MatchDoc(docid) && outerInstance.m_acceptDocs.Get(docid); } public virtual int Length { get { return outerInstance.m_maxDoc; } } } public override sealed DocIdSetIterator GetIterator() { if (m_acceptDocs == null) { // Specialization optimization disregard acceptDocs return new DocIdSetIteratorAnonymousInnerClassHelper(this); } else if (m_acceptDocs is FixedBitSet || m_acceptDocs is OpenBitSet) { // special case for FixedBitSet / OpenBitSet: use the iterator and filter it // (used e.g. when Filters are chained by FilteredQuery) return new FilteredDocIdSetIteratorAnonymousInnerClassHelper(this, ((DocIdSet)m_acceptDocs).GetIterator()); } else { // Stupid consultation of acceptDocs and matchDoc() return new DocIdSetIteratorAnonymousInnerClassHelper2(this); } } private class DocIdSetIteratorAnonymousInnerClassHelper : DocIdSetIterator { private readonly FieldCacheDocIdSet outerInstance; public DocIdSetIteratorAnonymousInnerClassHelper(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; doc = -1; } private int doc; public override int DocID { get { return doc; } } public override int NextDoc() { do { doc++; if (doc >= outerInstance.m_maxDoc) { return doc = NO_MORE_DOCS; } } while (!outerInstance.MatchDoc(doc)); return doc; } public override int Advance(int target) { for (doc = target; doc < outerInstance.m_maxDoc; doc++) { if (outerInstance.MatchDoc(doc)) { return doc; } } return doc = NO_MORE_DOCS; } public override long GetCost() { return outerInstance.m_maxDoc; } } private class FilteredDocIdSetIteratorAnonymousInnerClassHelper : FilteredDocIdSetIterator { private readonly FieldCacheDocIdSet outerInstance; public FilteredDocIdSetIteratorAnonymousInnerClassHelper(FieldCacheDocIdSet outerInstance, Lucene.Net.Search.DocIdSetIterator iterator) : base(iterator) { this.outerInstance = outerInstance; } protected override bool Match(int doc) { return outerInstance.MatchDoc(doc); } } private class DocIdSetIteratorAnonymousInnerClassHelper2 : DocIdSetIterator { private readonly FieldCacheDocIdSet outerInstance; public DocIdSetIteratorAnonymousInnerClassHelper2(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; doc = -1; } private int doc; public override int DocID { get { return doc; } } public override int NextDoc() { do { doc++; if (doc >= outerInstance.m_maxDoc) { return doc = NO_MORE_DOCS; } } while (!(outerInstance.MatchDoc(doc) && outerInstance.m_acceptDocs.Get(doc))); return doc; } public override int Advance(int target) { for (doc = target; doc < outerInstance.m_maxDoc; doc++) { if (outerInstance.MatchDoc(doc) && outerInstance.m_acceptDocs.Get(doc)) { return doc; } } return doc = NO_MORE_DOCS; } public override long GetCost() { return outerInstance.m_maxDoc; } } } }
using System; namespace DesignScript.Editor.Core { public class Parser { public const int _EOF = 0; public const int _ident = 1; public const int _number = 2; public const int _float = 3; public const int _textstring = 4; public const int _period = 5; public const int _openbracket = 6; public const int _closebracket = 7; public const int _openparen = 8; public const int _closeparen = 9; public const int _not = 10; public const int _neg = 11; public const int _pipe = 12; public const int _lessthan = 13; public const int _greaterthan = 14; public const int _lessequal = 15; public const int _greaterequal = 16; public const int _equal = 17; public const int _notequal = 18; public const int _endline = 19; public const int _rangeop = 20; public const int _and = 21; public const int _or = 22; public const int _comment1 = 23; public const int _comment2 = 24; public const int _comment3 = 25; public const int _newline = 26; public const int _kw_native = 27; public const int _kw_class = 28; public const int _kw_constructor = 29; public const int _kw_def = 30; public const int _kw_external = 31; public const int _kw_extend = 32; public const int _kw_heap = 33; public const int _kw_if = 34; public const int _kw_elseif = 35; public const int _kw_else = 36; public const int _kw_while = 37; public const int _kw_for = 38; public const int _kw_import = 39; public const int _kw_prefix = 40; public const int _kw_from = 41; public const int _kw_break = 42; public const int _kw_continue = 43; public const int _kw_static = 44; public const int _literal_true = 45; public const int _literal_false = 46; public const int _literal_null = 47; public const int maxT = 48; const bool T = true; const bool x = false; const int minErrDist = 2; public Scanner scanner; public Errors errors; public Token t; // last recognized token public Token la; // lookahead token int errDist = minErrDist; public Parser(Scanner scanner) { this.scanner = scanner; errors = new Errors(); } void SynErr (int n) { if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n); errDist = 0; } public void SemErr (string msg) { if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg); errDist = 0; } void Get () { for (;;) { t = la; la = scanner.Scan(); if (la.kind <= maxT) { ++errDist; break; } la = t; } } void Expect (int n) { if (la.kind==n) Get(); else { SynErr(n); } } bool StartOf (int s) { return set[s, la.kind]; } void ExpectWeak (int n, int follow) { if (la.kind == n) Get(); else { SynErr(n); while (!StartOf(follow)) Get(); } } bool WeakSeparator(int n, int syFol, int repFol) { int kind = la.kind; if (kind == n) {Get(); return true;} else if (StartOf(repFol)) {return false;} else { SynErr(n); while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) { Get(); kind = la.kind; } return StartOf(syFol); } } void DesignScriptParser() { Expect(1); } public void Parse() { la = new Token(); la.val = ""; Get(); DesignScriptParser(); Expect(0); } static readonly bool[,] set = { {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x} }; } // end Parser public class Errors { public int count = 0; // number of errors detected public System.IO.TextWriter errorStream = Console.Out; // error messages go to this stream public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text public virtual void SynErr (int line, int col, int n) { string s; switch (n) { case 0: s = "EOF expected"; break; case 1: s = "ident expected"; break; case 2: s = "number expected"; break; case 3: s = "float expected"; break; case 4: s = "textstring expected"; break; case 5: s = "period expected"; break; case 6: s = "openbracket expected"; break; case 7: s = "closebracket expected"; break; case 8: s = "openparen expected"; break; case 9: s = "closeparen expected"; break; case 10: s = "not expected"; break; case 11: s = "neg expected"; break; case 12: s = "pipe expected"; break; case 13: s = "lessthan expected"; break; case 14: s = "greaterthan expected"; break; case 15: s = "lessequal expected"; break; case 16: s = "greaterequal expected"; break; case 17: s = "equal expected"; break; case 18: s = "notequal expected"; break; case 19: s = "endline expected"; break; case 20: s = "rangeop expected"; break; case 21: s = "and expected"; break; case 22: s = "or expected"; break; case 23: s = "comment1 expected"; break; case 24: s = "comment2 expected"; break; case 25: s = "comment3 expected"; break; case 26: s = "newline expected"; break; case 27: s = "kw_native expected"; break; case 28: s = "kw_class expected"; break; case 29: s = "kw_constructor expected"; break; case 30: s = "kw_def expected"; break; case 31: s = "kw_external expected"; break; case 32: s = "kw_extend expected"; break; case 33: s = "kw_heap expected"; break; case 34: s = "kw_if expected"; break; case 35: s = "kw_elseif expected"; break; case 36: s = "kw_else expected"; break; case 37: s = "kw_while expected"; break; case 38: s = "kw_for expected"; break; case 39: s = "kw_import expected"; break; case 40: s = "kw_prefix expected"; break; case 41: s = "kw_from expected"; break; case 42: s = "kw_break expected"; break; case 43: s = "kw_continue expected"; break; case 44: s = "kw_static expected"; break; case 45: s = "literal_true expected"; break; case 46: s = "literal_false expected"; break; case 47: s = "literal_null expected"; break; case 48: s = "??? expected"; break; default: s = "error " + n; break; } errorStream.WriteLine(errMsgFormat, line, col, s); count++; } public virtual void SemErr (int line, int col, string s) { errorStream.WriteLine(errMsgFormat, line, col, s); count++; } public virtual void SemErr (string s) { errorStream.WriteLine(s); count++; } public virtual void Warning (int line, int col, string s) { errorStream.WriteLine(errMsgFormat, line, col, s); } public virtual void Warning(string s) { errorStream.WriteLine(s); } } // Errors public class FatalError: Exception { public FatalError(string m): base(m) {} } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 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.Collections.Specialized; using System.IO; using System.Net; using System.Text; using System.Web; using Node.Cs.Lib.Contexts.ContentUtils; namespace Node.Cs.Lib.Contexts { public class NodeCsRequest : HttpRequestBase { private NodeCsHttpFileCollection _files; private readonly HttpListenerRequest _request; private readonly NodeCsContext _context; private Encoding _contentEncoding; private NameValueCollection _queryString; private NameValueCollection _form; private Stream _inputStream; public override bool IsAuthenticated { get { return _context.User != null; } } public NodeCsRequest(Uri url) { _url = url; } public NodeCsRequest(HttpListenerRequest request, NodeCsContext context) { Initialized = false; _queryString = new NameValueCollection(); _form = new NameValueCollection(); _files = new NodeCsHttpFileCollection(new Dictionary<string, NodeCsFile>(StringComparer.OrdinalIgnoreCase)); _request = request; _context = context; _url = _request.Url; try { _contentEncoding = _request.ContentEncoding; } catch { _contentEncoding = Encoding.UTF8; } _queryString = HttpUtility.ParseQueryString(_request.Url.Query); } public void Initialize() { FillInFormCollection(); FillInCookies(); } private HttpCookieCollection _cookies; private void FillInCookies() { _cookies = new HttpCookieCollection(); foreach (Cookie cookie in _request.Cookies) { _cookies.Add(new HttpCookie(cookie.Name, cookie.Value) { //Domain = cookie.Domain, Expires = cookie.Expires, HttpOnly = cookie.HttpOnly, Path = "/", Secure = cookie.Secure }); } } public override HttpCookieCollection Cookies { get { return _cookies; } } public bool Initialized { get; set; } public void Initialize(HttpListenerRequest request) { try { _contentEncoding = _request.ContentEncoding; } catch { _contentEncoding = Encoding.UTF8; } _queryString = HttpUtility.ParseQueryString(_request.Url.Query); FillInFormCollection(); FillInCookies(); } public NodeCsRequest() { Initialized = false; _queryString = new NameValueCollection(); _form = new NameValueCollection(); _files = new NodeCsHttpFileCollection(new Dictionary<string, NodeCsFile>(StringComparer.OrdinalIgnoreCase)); } public override NameValueCollection Headers { get { return _request.Headers; } } public override Stream InputStream { get { return _inputStream; } } private void FillInFormCollection() { _form = new NameValueCollection(); if (ContentType == null) { _inputStream = new MemoryStream(new byte[] { }); _files = new NodeCsHttpFileCollection(new Dictionary<string, NodeCsFile>()); return; } if (ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { var formUlrEncoded = new UrlEncodedStreamConverter(); formUlrEncoded.Initialize(_request.InputStream, ContentEncoding, ContentType); foreach (var key in formUlrEncoded.Keys) { _form.Add(key,HttpUtility.UrlDecode(formUlrEncoded[key])); } } else if (ContentType.StartsWith("multipart/form-data", StringComparison.OrdinalIgnoreCase)) { var multipartForm = new MultipartFormStreamConverter(); multipartForm.Initialize(_request.InputStream, ContentEncoding, ContentType); foreach (var key in multipartForm.Keys) { _form.Add(key, multipartForm[key]); } var filesDictionary = new Dictionary<string, NodeCsFile>(StringComparer.OrdinalIgnoreCase); foreach (var file in multipartForm.Files) { var stream = new MemoryStream(); stream.Write(multipartForm.Content, file.Start, file.Length); filesDictionary.Add(file.Name, new NodeCsFile(file.FileName, stream, file.ContentType)); } _files = new NodeCsHttpFileCollection(filesDictionary); } else { _inputStream = _request.InputStream; } } public override NameValueCollection QueryString { get { return _queryString; } } public override NameValueCollection Form { get { return _form; } } public override string ContentType { get { return _request.ContentType; } set { } } public override string HttpMethod { get { return _request.HttpMethod; } } public override Uri Url { get { return _url; } } public override Uri UrlReferrer { get { return _request.UrlReferrer; } } public override Encoding ContentEncoding { get { return _contentEncoding; } set { _contentEncoding = value; } } public override HttpFileCollectionBase Files { get { return _files; } } private NameValueCollection _params; private Uri _url; public void ForceUrl(Uri url) { _url = url; } public override NameValueCollection Params { get { if (_params != null) return _params; var parameters = new NameValueCollection(); foreach (var item in Form.AllKeys) { parameters.Add(item, Form[item]); } foreach (var item in QueryString.AllKeys) { parameters.Add(item, QueryString[item]); } _params = parameters; return _params; } } public override bool IsLocal { get { return _request.IsLocal; } } } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit { using System; using System.Threading; using System.Threading.Tasks; using Pipeline; using Scheduling; public static class TimeSpanContextScheduleExtensions { /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="scheduler">The message scheduler</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="message">The message</param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage<T>> ScheduleSend<T>(this MessageSchedulerContext scheduler, TimeSpan delay, T message, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, cancellationToken); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="scheduler">The message scheduler</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="message">The message</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage<T>> ScheduleSend<T>(this MessageSchedulerContext scheduler, TimeSpan delay, T message, IPipe<SendContext<T>> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, pipe, cancellationToken); } /// <summary> /// Send a message /// </summary> /// <typeparam name="T">The message type</typeparam> /// <param name="scheduler">The message scheduler</param> /// <param name="message">The message</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage<T>> ScheduleSend<T>(this MessageSchedulerContext scheduler, TimeSpan delay, T message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, pipe, cancellationToken); } /// <summary> /// Sends an object as a message, using the type of the message instance. /// </summary> /// <param name="scheduler">The message scheduler</param> /// <param name="message">The message object</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage> ScheduleSend(this MessageSchedulerContext scheduler, TimeSpan delay, object message, CancellationToken cancellationToken = default(CancellationToken)) { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, cancellationToken); } /// <summary> /// Sends an object as a message, using the message type specified. If the object cannot be cast /// to the specified message type, an exception will be thrown. /// </summary> /// <param name="scheduler">The message scheduler</param> /// <param name="message">The message object</param> /// <param name="messageType">The type of the message (use message.GetType() if desired)</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage> ScheduleSend(this MessageSchedulerContext scheduler, TimeSpan delay, object message, Type messageType, CancellationToken cancellationToken = default(CancellationToken)) { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, messageType, cancellationToken); } /// <summary> /// Sends an object as a message, using the message type specified. If the object cannot be cast /// to the specified message type, an exception will be thrown. /// </summary> /// <param name="scheduler">The message scheduler</param> /// <param name="message">The message object</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage> ScheduleSend(this MessageSchedulerContext scheduler, TimeSpan delay, object message, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, pipe, cancellationToken); } /// <summary> /// Sends an object as a message, using the message type specified. If the object cannot be cast /// to the specified message type, an exception will be thrown. /// </summary> /// <param name="scheduler">The message scheduler</param> /// <param name="message">The message object</param> /// <param name="messageType">The type of the message (use message.GetType() if desired)</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage> ScheduleSend(this MessageSchedulerContext scheduler, TimeSpan delay, object message, Type messageType, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, message, messageType, pipe, cancellationToken); } /// <summary> /// Sends an interface message, initializing the properties of the interface using the anonymous /// object specified /// </summary> /// <typeparam name="T">The interface type to send</typeparam> /// <param name="scheduler">The message scheduler</param> /// <param name="values">The property values to initialize on the interface</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage<T>> ScheduleSend<T>(this MessageSchedulerContext scheduler, TimeSpan delay, object values, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend<T>(scheduledTime, values, cancellationToken); } /// <summary> /// Sends an interface message, initializing the properties of the interface using the anonymous /// object specified /// </summary> /// <typeparam name="T">The interface type to send</typeparam> /// <param name="scheduler">The message scheduler</param> /// <param name="values">The property values to initialize on the interface</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage<T>> ScheduleSend<T>(this MessageSchedulerContext scheduler, TimeSpan delay, object values, IPipe<SendContext<T>> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend(scheduledTime, values, pipe, cancellationToken); } /// <summary> /// Sends an interface message, initializing the properties of the interface using the anonymous /// object specified /// </summary> /// <typeparam name="T">The interface type to send</typeparam> /// <param name="scheduler">The message scheduler</param> /// <param name="values">The property values to initialize on the interface</param> /// <param name="delay">The time at which the message should be delivered to the queue</param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <returns>The task which is completed once the Send is acknowledged by the broker</returns> public static Task<ScheduledMessage<T>> ScheduleSend<T>(this MessageSchedulerContext scheduler, TimeSpan delay, object values, IPipe<SendContext> pipe, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var scheduledTime = DateTime.UtcNow + delay; return scheduler.ScheduleSend<T>(scheduledTime, values, pipe, cancellationToken); } } }
using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BytesRef = Lucene.Net.Util.BytesRef; using CachingTokenFilter = Lucene.Net.Analysis.CachingTokenFilter; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using MockTokenFilter = Lucene.Net.Analysis.MockTokenFilter; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using StringField = StringField; using TextField = TextField; using TokenStream = Lucene.Net.Analysis.TokenStream; /// <summary> /// tests for writing term vectors </summary> [TestFixture] public class TestTermVectorsWriter : LuceneTestCase { // LUCENE-1442 [Test] public virtual void TestDoubleOffsetCounting() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); FieldType customType = new FieldType(StringField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "abcd", customType); doc.Add(f); doc.Add(f); Field f2 = NewField("field", "", customType); doc.Add(f2); doc.Add(f); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); Terms vector = r.GetTermVectors(0).GetTerms("field"); Assert.IsNotNull(vector); TermsEnum termsEnum = vector.GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); Assert.AreEqual("", termsEnum.Term.Utf8ToString()); // Token "" occurred once Assert.AreEqual(1, termsEnum.TotalTermFreq); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(8, dpEnum.StartOffset); Assert.AreEqual(8, dpEnum.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc()); // Token "abcd" occurred three times Assert.IsTrue(termsEnum.MoveNext()); Assert.AreEqual(new BytesRef("abcd"), termsEnum.Term); dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.AreEqual(3, termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); dpEnum.NextPosition(); Assert.AreEqual(4, dpEnum.StartOffset); Assert.AreEqual(8, dpEnum.EndOffset); dpEnum.NextPosition(); Assert.AreEqual(8, dpEnum.StartOffset); Assert.AreEqual(12, dpEnum.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc()); Assert.IsFalse(termsEnum.MoveNext()); r.Dispose(); dir.Dispose(); } // LUCENE-1442 [Test] public virtual void TestDoubleOffsetCounting2() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "abcd", customType); doc.Add(f); doc.Add(f); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.AreEqual(2, termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); dpEnum.NextPosition(); Assert.AreEqual(5, dpEnum.StartOffset); Assert.AreEqual(9, dpEnum.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc()); r.Dispose(); dir.Dispose(); } // LUCENE-1448 [Test] public virtual void TestEndOffsetPositionCharAnalyzer() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "abcd ", customType); doc.Add(f); doc.Add(f); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.AreEqual(2, termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); dpEnum.NextPosition(); Assert.AreEqual(8, dpEnum.StartOffset); Assert.AreEqual(12, dpEnum.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc()); r.Dispose(); dir.Dispose(); } // LUCENE-1448 [Test] public virtual void TestEndOffsetPositionWithCachingTokenFilter() { Directory dir = NewDirectory(); Analyzer analyzer = new MockAnalyzer(Random); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer)); Document doc = new Document(); IOException priorException = null; TokenStream stream = analyzer.GetTokenStream("field", new StringReader("abcd ")); try { stream.Reset(); // TODO: weird to reset before wrapping with CachingTokenFilter... correct? TokenStream cachedStream = new CachingTokenFilter(stream); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = new Field("field", cachedStream, customType); doc.Add(f); doc.Add(f); w.AddDocument(doc); } catch (IOException e) { priorException = e; } finally { IOUtils.DisposeWhileHandlingException(priorException, stream); } w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.AreEqual(2, termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); dpEnum.NextPosition(); Assert.AreEqual(8, dpEnum.StartOffset); Assert.AreEqual(12, dpEnum.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc()); r.Dispose(); dir.Dispose(); } // LUCENE-1448 [Test] public virtual void TestEndOffsetPositionStopFilter() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET))); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "abcd the", customType); doc.Add(f); doc.Add(f); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.AreEqual(2, termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); dpEnum.NextPosition(); Assert.AreEqual(9, dpEnum.StartOffset); Assert.AreEqual(13, dpEnum.EndOffset); Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dpEnum.NextDoc()); r.Dispose(); dir.Dispose(); } // LUCENE-1448 [Test] public virtual void TestEndOffsetPositionStandard() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "abcd the ", customType); Field f2 = NewField("field", "crunch man", customType); doc.Add(f); doc.Add(f2); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); Assert.IsTrue(termsEnum.MoveNext()); dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(11, dpEnum.StartOffset); Assert.AreEqual(17, dpEnum.EndOffset); Assert.IsTrue(termsEnum.MoveNext()); dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(18, dpEnum.StartOffset); Assert.AreEqual(21, dpEnum.EndOffset); r.Dispose(); dir.Dispose(); } // LUCENE-1448 [Test] public virtual void TestEndOffsetPositionStandardEmptyField() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "", customType); Field f2 = NewField("field", "crunch man", customType); doc.Add(f); doc.Add(f2); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.AreEqual(1, (int)termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(1, dpEnum.StartOffset); Assert.AreEqual(7, dpEnum.EndOffset); Assert.IsTrue(termsEnum.MoveNext()); dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(8, dpEnum.StartOffset); Assert.AreEqual(11, dpEnum.EndOffset); r.Dispose(); dir.Dispose(); } // LUCENE-1448 [Test] public virtual void TestEndOffsetPositionStandardEmptyField2() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.StoreTermVectors = true; customType.StoreTermVectorPositions = true; customType.StoreTermVectorOffsets = true; Field f = NewField("field", "abcd", customType); doc.Add(f); doc.Add(NewField("field", "", customType)); Field f2 = NewField("field", "crunch", customType); doc.Add(f2); w.AddDocument(doc); w.Dispose(); IndexReader r = DirectoryReader.Open(dir); TermsEnum termsEnum = r.GetTermVectors(0).GetTerms("field").GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.AreEqual(1, (int)termsEnum.TotalTermFreq); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(0, dpEnum.StartOffset); Assert.AreEqual(4, dpEnum.EndOffset); Assert.IsTrue(termsEnum.MoveNext()); dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); dpEnum.NextPosition(); Assert.AreEqual(6, dpEnum.StartOffset); Assert.AreEqual(12, dpEnum.EndOffset); r.Dispose(); dir.Dispose(); } // LUCENE-1168 [Test] public virtual void TestTermVectorCorruption() { Directory dir = NewDirectory(); for (int iter = 0; iter < 2; iter++) { IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy())); Document document = new Document(); FieldType customType = new FieldType(); customType.IsStored = true; Field storedField = NewField("stored", "stored", customType); document.Add(storedField); writer.AddDocument(document); writer.AddDocument(document); document = new Document(); document.Add(storedField); FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED); customType2.StoreTermVectors = true; customType2.StoreTermVectorPositions = true; customType2.StoreTermVectorOffsets = true; Field termVectorField = NewField("termVector", "termVector", customType2); document.Add(termVectorField); writer.AddDocument(document); writer.ForceMerge(1); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); for (int i = 0; i < reader.NumDocs; i++) { reader.Document(i); reader.GetTermVectors(i); } reader.Dispose(); writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy())); Directory[] indexDirs = new Directory[] { new MockDirectoryWrapper(Random, new RAMDirectory(dir, NewIOContext(Random))) }; writer.AddIndexes(indexDirs); writer.ForceMerge(1); writer.Dispose(); } dir.Dispose(); } // LUCENE-1168 [Test] public virtual void TestTermVectorCorruption2() { Directory dir = NewDirectory(); for (int iter = 0; iter < 2; iter++) { IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy())); Document document = new Document(); FieldType customType = new FieldType(); customType.IsStored = true; Field storedField = NewField("stored", "stored", customType); document.Add(storedField); writer.AddDocument(document); writer.AddDocument(document); document = new Document(); document.Add(storedField); FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED); customType2.StoreTermVectors = true; customType2.StoreTermVectorPositions = true; customType2.StoreTermVectorOffsets = true; Field termVectorField = NewField("termVector", "termVector", customType2); document.Add(termVectorField); writer.AddDocument(document); writer.ForceMerge(1); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); Assert.IsNull(reader.GetTermVectors(0)); Assert.IsNull(reader.GetTermVectors(1)); Assert.IsNotNull(reader.GetTermVectors(2)); reader.Dispose(); } dir.Dispose(); } // LUCENE-1168 [Test] public virtual void TestTermVectorCorruption3() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy())); Document document = new Document(); FieldType customType = new FieldType(); customType.IsStored = true; Field storedField = NewField("stored", "stored", customType); document.Add(storedField); FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED); customType2.StoreTermVectors = true; customType2.StoreTermVectorPositions = true; customType2.StoreTermVectorOffsets = true; Field termVectorField = NewField("termVector", "termVector", customType2); document.Add(termVectorField); for (int i = 0; i < 10; i++) { writer.AddDocument(document); } writer.Dispose(); writer = new IndexWriter(dir, ((IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(new LogDocMergePolicy())); for (int i = 0; i < 6; i++) { writer.AddDocument(document); } writer.ForceMerge(1); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); for (int i = 0; i < 10; i++) { reader.GetTermVectors(i); reader.Document(i); } reader.Dispose(); dir.Dispose(); } // LUCENE-1008 [Test] public virtual void TestNoTermVectorAfterTermVector() { Directory dir = NewDirectory(); IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document document = new Document(); FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED); customType2.StoreTermVectors = true; customType2.StoreTermVectorPositions = true; customType2.StoreTermVectorOffsets = true; document.Add(NewField("tvtest", "a b c", customType2)); iw.AddDocument(document); document = new Document(); document.Add(NewTextField("tvtest", "x y z", Field.Store.NO)); iw.AddDocument(document); // Make first segment iw.Commit(); FieldType customType = new FieldType(StringField.TYPE_NOT_STORED); customType.StoreTermVectors = true; document.Add(NewField("tvtest", "a b c", customType)); iw.AddDocument(document); // Make 2nd segment iw.Commit(); iw.ForceMerge(1); iw.Dispose(); dir.Dispose(); } // LUCENE-1010 [Test] public virtual void TestNoTermVectorAfterTermVectorMerge() { Directory dir = NewDirectory(); IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document document = new Document(); FieldType customType = new FieldType(StringField.TYPE_NOT_STORED); customType.StoreTermVectors = true; document.Add(NewField("tvtest", "a b c", customType)); iw.AddDocument(document); iw.Commit(); document = new Document(); document.Add(NewTextField("tvtest", "x y z", Field.Store.NO)); iw.AddDocument(document); // Make first segment iw.Commit(); iw.ForceMerge(1); FieldType customType2 = new FieldType(StringField.TYPE_NOT_STORED); customType2.StoreTermVectors = true; document.Add(NewField("tvtest", "a b c", customType2)); iw.AddDocument(document); // Make 2nd segment iw.Commit(); iw.ForceMerge(1); iw.Dispose(); dir.Dispose(); } } }
/* * Copyright (c) Citrix Systems, 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) 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. * * 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.Collections; using System.Collections.Generic; using System.IO; using System.Management.Automation; using System.Reflection; using System.Xml; using XenAPI; namespace Citrix.XenServer { class CommonCmdletFunctions { private const string SessionsVariable = "global:Citrix.XenServer.Sessions"; private const string DefaultSessionVariable = "global:XenServer_Default_Session"; private static string CertificatePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),@"WindowsPowerShell\XenServer_Known_Certificates.xml"); static CommonCmdletFunctions() { Session.UserAgent = string.Format("XenServerPSModule/{0}", Assembly.GetExecutingAssembly().GetName().Version); } internal static Dictionary<string, Session> GetAllSessions(PSCmdlet cmdlet) { object obj = cmdlet.SessionState.PSVariable.GetValue(SessionsVariable); return obj as Dictionary<string, Session> ?? new Dictionary<string, Session>(); } /// <summary> /// Save the session dictionary as a PowerShell variable. It includes the /// PSCredential so, in case the session times out, any cmdlet can try to /// remake it /// </summary> internal static void SetAllSessions(PSCmdlet cmdlet, Dictionary<string, Session> sessions) { cmdlet.SessionState.PSVariable.Set(SessionsVariable, sessions); } internal static Session GetDefaultXenSession(PSCmdlet cmdlet) { object obj = cmdlet.SessionState.PSVariable.GetValue(DefaultSessionVariable); return obj as Session; } internal static void SetDefaultXenSession(PSCmdlet cmdlet, Session session) { cmdlet.SessionState.PSVariable.Set(DefaultSessionVariable, session); } internal static string GetUrl(string hostname, int port) { return string.Format("{0}://{1}:{2}", port == 80 ? "http" : "https", hostname, port); } public static Dictionary<string, string> LoadCertificates() { Dictionary<string, string> certificates = new Dictionary<string, string>(); if(File.Exists(CertificatePath)) { XmlDocument doc = new XmlDocument(); try { doc.Load(CertificatePath); foreach (XmlNode node in doc.GetElementsByTagName("certificate")) { XmlAttribute hostAtt = node.Attributes["hostname"]; XmlAttribute fngprtAtt = node.Attributes["fingerprint"]; if (hostAtt != null && fngprtAtt != null) certificates[hostAtt.Value] = fngprtAtt.Value; } } catch {} } return certificates; } public static void SaveCertificates(Dictionary<string, string> certificates) { string dirName = Path.GetDirectoryName(CertificatePath); if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName); XmlDocument doc = new XmlDocument(); XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(decl); XmlNode node = doc.CreateElement("certificates"); foreach(KeyValuePair<string, string> cert in certificates) { XmlNode cert_node = doc.CreateElement("certificate"); XmlAttribute hostname = doc.CreateAttribute("hostname"); XmlAttribute fingerprint = doc.CreateAttribute("fingerprint"); hostname.Value = cert.Key; fingerprint.Value = cert.Value; cert_node.Attributes.Append(hostname); cert_node.Attributes.Append(fingerprint); node.AppendChild(cert_node); } doc.AppendChild(node); try { doc.Save(CertificatePath); } catch {} } public static string FingerprintPrettyString(string fingerprint) { List<string> pairs = new List<string>(); while(fingerprint.Length > 1) { pairs.Add(fingerprint.Substring(0,2)); fingerprint = fingerprint.Substring(2); } if(fingerprint.Length > 0) pairs.Add(fingerprint); return string.Join(":", pairs.ToArray()); } public static Dictionary<T, S> ConvertHashTableToDictionary<T, S>(Hashtable tbl) { if (tbl == null) return null; var dict = new Dictionary<T, S>(); foreach (DictionaryEntry entry in tbl) dict.Add((T)entry.Key, (S)entry.Value); return dict; } public static Hashtable ConvertDictionaryToHashtable<T, S>(Dictionary<T, S> dict) { if (dict == null) return null; var tbl = new Hashtable(); foreach(KeyValuePair<T, S> pair in dict) tbl.Add(pair.Key, pair.Value); return tbl; } internal static object EnumParseDefault(Type t, string s) { try { return Enum.Parse(t, s == null ? null : s.Replace('-','_')); } catch (ArgumentException) { try { return Enum.Parse(t, "unknown"); } catch (ArgumentException) { try { return Enum.Parse(t, "Unknown"); } catch (ArgumentException) { return 0; } } } } } }
using UnityEngine; using UnityEditor; using System; using System.Xml; using System.IO; using System.Collections; using System.Collections.Generic; public class EditorUnitList{ public UnitListPrefab prefab; public string[] nameList=new string[0]; } public class UnitTBManagerWindow : EditorWindow { static private UnitTBManagerWindow window; private static UnitListPrefab prefab; private static List<UnitTB> unitList=new List<UnitTB>(); private static List<int> unitIDList=new List<int>(); private UnitTB newUnit=null; public static void Init () { // Get existing open window or if none, make a new one: window = (UnitTBManagerWindow)EditorWindow.GetWindow(typeof (UnitTBManagerWindow)); window.minSize=new Vector2(375, 449); window.maxSize=new Vector2(375, 800); EditorUnitList eUnitList=LoadUnit(); prefab=eUnitList.prefab; unitList=prefab.unitList; foreach(UnitTB unit in unitList){ unitIDList.Add(unit.prefabID); } } public static EditorUnitList LoadUnit(){ GameObject obj=Resources.Load("PrefabList/UnitListPrefab", typeof(GameObject)) as GameObject; if(obj==null) obj=CreatePrefab(); UnitListPrefab prefab=obj.GetComponent<UnitListPrefab>(); if(prefab==null) prefab=obj.AddComponent<UnitListPrefab>(); for(int i=0; i<prefab.unitList.Count; i++){ if(prefab.unitList[i]==null){ prefab.unitList.RemoveAt(i); i-=1; } } string[] nameList=new string[prefab.unitList.Count]; for(int i=0; i<prefab.unitList.Count; i++){ if(prefab.unitList[i]!=null){ nameList[i]=prefab.unitList[i].unitName; //prefab.unitList[i].prefabID=i; unitIDList.Add(prefab.unitList[i].prefabID); } } EditorUnitList eUnitList=new EditorUnitList(); eUnitList.prefab=prefab; eUnitList.nameList=nameList; return eUnitList; } private static GameObject CreatePrefab(){ GameObject obj=new GameObject(); obj.AddComponent<UnitListPrefab>(); GameObject prefab=PrefabUtility.CreatePrefab("Assets/TBTK/Resources/PrefabList/UnitListPrefab.prefab", obj, ReplacePrefabOptions.ConnectToPrefab); DestroyImmediate(obj); AssetDatabase.Refresh (); return prefab; } int delete=-1; private Vector2 scrollPos; void OnGUI () { if(window==null) Init(); Undo.SetSnapshotTarget(this, "UnitManagerWindow"); int currentUnitCount=unitList.Count; if(GUI.Button(new Rect(window.position.width-110, 5, 100, 25), "UnitEditor")){ this.Close(); UnitTBEditorWindow.Init(); } EditorGUI.LabelField(new Rect(5, 10, 150, 17), "Add new unit:"); newUnit=(UnitTB)EditorGUI.ObjectField(new Rect(100, 10, 150, 17), newUnit, typeof(UnitTB), false); if(newUnit!=null){ if(!unitList.Contains(newUnit)){ int rand=0; while(unitIDList.Contains(rand)) rand+=1; unitIDList.Add(rand); newUnit.prefabID=rand; newUnit.unitName=newUnit.gameObject.name; unitList.Add(newUnit); GUI.changed=true; } newUnit=null; } if(unitList.Count>0){ GUI.Box(new Rect(5, 40, 50, 20), "ID"); GUI.Box(new Rect(5+50-1, 40, 60+1, 20), "Icon"); GUI.Box(new Rect(5+110-1, 40, 160+2, 20), "Name"); GUI.Box(new Rect(5+270, 40, window.position.width-300, 20), ""); } scrollPos = GUI.BeginScrollView(new Rect(5, 60, window.position.width-12, window.position.height-50), scrollPos, new Rect(5, 55, window.position.width-30, 15+((unitList.Count))*50)); int row=0; for(int i=0; i<unitList.Count; i++){ if(i%2==0) GUI.color=new Color(.8f, .8f, .8f, 1); else GUI.color=Color.white; GUI.Box(new Rect(5, 60+i*49, window.position.width-30, 50), ""); GUI.color=Color.white; if(currentSwapID==i) GUI.color=new Color(.9f, .9f, .0f, 1); if(GUI.Button(new Rect(19, 12+60+i*49, 30, 30), unitList[i].prefabID.ToString())){ if(currentSwapID==i) currentSwapID=-1; else if(currentSwapID==-1) currentSwapID=i; else{ SwapCreep(i); GUI.changed=true; } } if(currentSwapID==i) GUI.color=Color.white; if(unitList[i]!=null){ unitList[i].icon=(Texture)EditorGUI.ObjectField(new Rect(12+50, 3+60+i*49, 44, 44), unitList[i].icon, typeof(Texture), false); unitList[i].unitName=EditorGUI.TextField(new Rect(5+120, 6+60+i*49, 150, 17), unitList[i].unitName); if(unitList[i].icon!=null && unitList[i].icon.name!=unitList[i].iconName){ unitList[i].iconName=unitList[i].icon.name; GUI.changed=true; } EditorGUI.LabelField(new Rect(5+120, 6+60+i*49+20, 150, 17), "Prefab:"); EditorGUI.ObjectField(new Rect(5+165, 6+60+i*49+20, 105, 17), unitList[i].gameObject, typeof(GameObject), false); } if(delete!=i){ if(GUI.Button(new Rect(window.position.width-55, 12+60+i*49, 25, 25), "X")){ delete=i; } } else{ GUI.color = Color.red; if(GUI.Button(new Rect(window.position.width-90, 12+60+i*49, 60, 25), "Remove")){ if(currentSwapID==i) currentSwapID=-1; unitIDList.Remove(unitList[i].prefabID); unitList.RemoveAt(i); delete=-1; //~ if(onCreepUpdateE!=null) onCreepUpdateE(); GUI.changed=true; } GUI.color = Color.white; } row+=1; } GUI.EndScrollView(); if(GUI.changed || currentUnitCount!=unitList.Count){ EditorUtility.SetDirty(prefab); for(int i=0; i<unitList.Count; i++) EditorUtility.SetDirty(unitList[i]); } if (GUI.changed || currentUnitCount!=unitList.Count){ Undo.CreateSnapshot(); Undo.RegisterSnapshot(); } Undo.ClearSnapshotTarget(); } private int currentSwapID=-1; void SwapCreep(int ID){ UnitTB unit=unitList[currentSwapID]; unitList[currentSwapID]=unitList[ID]; unitList[ID]=unit; currentSwapID=-1; } }
//----------------------------------------------------------------------- // <copyright file="PatomValues.cs" company="Pat Inc."> // Copyright (c) Pat Inc. 2016. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace PatTuring2016.Common { public enum PatomValues { Word = 0, // used for words - obsolete Noun = 1, // used for words representing phrases Verb = 2, // used for words representing phrases Determiner = 3, Compound = 4, // compound phrases First = 5, // first compound element Second = 6, // second compound element Third = 7, // third compound element Fourth = 8, // fourth compound element Base = 9, // used for base blobs (i.e. generic) Sense = 10, // used for a single sense Interjection = 11, Gerund = 12, // used for words representing phrases Adjective = 13, // used for words representing phrases How = 14, // used for words representing phrases When = 15, // used for words representing phrases Where = 16, // used for words representing phrases Preposition = 17, // used for words representing phrases DeterminerHead = 18, Negative = 19, Question = 20, // used for question words and phrases Which = 21, // used for question words and phrases Hidden = 22, // used for question words and phrases Prefix = 23, // used for question words and phrases Senses = 24, // used for multiple senses Verbtype = 25, // identifies a specific set of verb patterns Nountype = 26, // identifies a specific set of noun patterns Postposition = 27, // identifies a postposition (cf preposition) Is = 28, // who IS running Has = 29, // John'S house Of = 30, // noun OF noun Was = 31, // who WAS Does = 32, // who DOES Clause = 33, Jclause = 34, Headedclause = 35, Sentence = 36, That = 37, Relative = 39, Conjunction = 40, Inflection = 41, Passivesubject = 42, Subjectofcomp = 43, Why = 44, Wherecomplement = 45, Pivotverb = 47, Pivot = 48, Comparitive = 50, // comparitive object, happier than "the dog" Fullword = 52, // used for words - obsolete PSA = 53, Title = 54, // used for titles and phrases List = 55, // used for titles and phrases Literal = 56, // used for literal phrases Clausehead = 59, Quantity = 60, Language = 61, Modal = 66, // the modal word in a clause - flipped with questions Subject = 67, // for phrases that don't link on their own Predicate = 68, // for phrases that don't link on their own Yndetail = 69, // Pattern types Multiphrase = 70, Multidenseanyphrase = 72, // this can replace all dense multi phrases Simplephrase = 73, Multidensephrase = 74, Phrase = 75, Adjsc = 76, Nounsc = 77, Predsc = 78, // Attribute Forms Personclause = 89, Time = 90, // attributes denoting time in verbs Tense = 91, // attributes denoting tense in verbs Gender = 93, // attributes denoting gender Person = 94, // attributes denoting person, singular or plural) Thing = 95, // attributes denoting titles and things Sign = 96, // attributes for positive and negative Adjtype = 97, // attributes for adjectives Status = 98, // attributes for status, like if a verb is full // ADJECTIVE TYPES - USED FOR MAPPING Cardinal = 100, Opinion = 101, Size = 102, Length = 103, Shape = 104, Width = 105, Pastpart = 106, Prespart = 107, Age = 108, Colour = 109, Origin = 110, Material = 111, Denominal = 112, Auxiliary = 113, Clausetype = 114, Nucauxiliary = 115, Verbtransitive = 116, Nucverb = 117, Semelfactivexclause = 118, Semelfactivexyclause = 119, // THEMATIC ROLES Actor = 120, Agent = 121, Asset = 122, Attribute = 123, Beneficiary = 124, Cause = 125, Location = 126, Destination = 127, Source = 128, Location2 = 129, Experiencer = 130, Extent = 131, Instrument = 132, Materialtheme = 133, Product = 134, Patient = 135, Predtheme = 136, Recipient = 137, Stimulus = 138, Theme = 139, Timetheme = 140, Topic = 141, Verbtheme = 142, Oblique = 143, Closed = 144, Sentences = 145, Clausetheme = 146, Senselist = 147, Undergoer = 148, Nucleus = 149, Uses = 150, Passive = 151, Verbaspect = 152, Intrans = 153, Trans = 154, Iforce = 157, Adjlinkedclause = 158, Nounlinkedclause = 159, Wherelinkedclause = 160, Link = 161, Complement = 162, Whenlinkedclause = 163, Verbhow = 164, Verbnot = 165, Verbinterjection = 166, Hownuc = 167, Howcore = 168, Howclause = 169, Clauseheadverb = 170, Ismodal = 171, Domodal = 172, Achievementclause = 174, Achievementxyclause = 175, Activityclause = 176, Whenclause = 178, Whereclause = 179, Verbwhy = 180, Nonmacrorole = 181, Frommacrorole = 182, Tomacrorole = 183, Macrorole = 185, Verbvoice = 187, Verbhead = 188, Deontic = 189, Epistemic = 190, Particle = 191, Verbnoun = 192, Version = 193, Questiona = 194, Questionu = 195, Questionn = 196, Verbwhere = 199, Verbwhen = 200, Causeaccomplishmentclause = 203, Verbwithoblique = 204, Accomplishmentclause = 206, Verbmatrix = 208, Verblinkadj = 209, Controllernomr = 210, Controllermake = 211, Controllernomradj = 212, Transxyclause = 213, Causeonemraccomplishmentclause = 214, Nounhead = 215, Transxynounclause = 216, Semelfactivexynounclause = 217, Achievementnounclause = 218, Accomplishmentnounclause = 219, Activitynounclause = 220, Questions = 221, Causeaccomplishmentonenounclause = 222, Verbwithnoun = 223, Causeaccomplishmentnounclause = 224, To = 225, With = 226, For = 227, From = 228, By = 229, Loc = 230, Nounclauseinitial = 231, Verbfromnoun = 232, Verbtonoun = 233, Transbenounclause = 234, Verbnounwhere = 235, Verbnounheadwhere = 236, Questionwhen = 237, Questionwhere = 238, Controllernoadj = 239, Controllereageradj = 240, Verbtagquestion = 241, Questiont = 242, Questionf = 243, Verblinkfulladj = 244, Nucleus2 = 245, Controllergerund = 246, Controlleradjgerund = 247, Verbthat = 248, Fail = 249, MatrixThatClause = 250, ClauseEllipsis = 251, ClauseMatrix = 252, ClauseShort = 253, ClauseNounEllipsis = 254, Adjective2 = 255, Positive = 256, // attributes for status, like if a verb is full Undergoer2 = 300, Sentence2Join = 301, SentenceIf = 302, Actor2 = 303, SentenceBecause = 304, Noun2 = 305, Deixis = 306, Npip = 307, AdjectiveHead = 308, ActivityGerundClause = 309, PassiveActivityGerundClause = 310, LatinAddPhrase = 311, LatinConsolidate = 312, LatinAspectPhrase = 313, GermanVerbAspect = 314, GermanClausehead = 315, GermanDativeVerb = 316, UndergoAccomplishmentclause = 350, UndergoCauseaccomplishmentclause = 351, UndergoCauseonemraccomplishmentclause = 352, UndergoSemelfactivexclause = 353, UndergoSemelfactivexyclause = 354, UndergoAchievementclause = 355, UndergoActivityclause = 356, UndergoerVerbClauseIntersect = 357, PassiveSemelfactivexclause = 358, PassiveSemelfactivexyclause = 359, PassiveAchievementclause = 360, PassiveAccomplishmentclause = 361, PassiveCauseaccomplishmentclause = 362, PassiveCauseonemraccomplishmentclause = 363, PassiveActivityclause = 364, PassiveTransxynounclause = 365, PassiveSemelfactivexynounclause = 366, PassiveAchievementnounclause = 367, PassiveAccomplishmentnounclause = 368, PassiveActivitynounclause = 369, PassiveCauseaccomplishmentonenounclause = 370, PassiveCauseaccomplishmentnounclause = 371, PassiveTransbenounclause = 372, PassiveTransxyclause = 373, PassiveMatrixThatClause = 374, Transxclause = 375, ControllerState = 376, ActorPronoun = 377, // used to show actual noun when pronoun used UndergoerPronoun = 378, NmrPronoun = 379, VerbSeparable = 380, Clauseheadphrasalverb = 381, NucleusPrep = 382, VerbOnlyHow = 383, VerbSeparate = 384, Nounclauseend = 385, Nounclauseupdate = 386, Causeaccomplishmentposclause = 387, CountBlessings = 388, Nothing = 389, NounClause = 390, Transxnounclause = 391, EmbeddedClause = 392, VerbNoVerb = 393, VerbNoMacrorole = 394, VerbNoVerbNewHead = 395, HeadError = 396, ClauseEllipsisNot = 397, Calc = 398, Function = 399, Number = 400, Hundred = 401, Thousand = 402, Million = 403, Billion = 404, VerbToWhere = 405, NucleusVerb = 406, NucleusNoun = 407, NucleusAdj = 408, NucleusWhen = 409, NucleusWhere = 410, Adjwhere = 411, NounBaseLinkedClause = 412, Date = 413, DateTime = 414, AmPm = 415 } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace CppSharp { public enum NewLineKind { Never, Always, BeforeNextBlock, IfNotEmpty } public enum BlockKind { Unknown, BlockComment, InlineComment, Header, Footer, Usings, Namespace, Enum, EnumItem, Typedef, Class, InternalsClass, InternalsClassMethod, InternalsClassField, Functions, Function, Method, Event, Variable, Property, Field, VTableDelegate, Region, Interface, Finalizer, Includes, IncludesForwardReferences, ForwardReferences, MethodBody, FunctionsClass, Template, Destructor, AccessSpecifier, Fields, ConstructorBody, DestructorBody, FinalizerBody } [DebuggerDisplay("{Kind} | {Object}")] public class Block : ITextGenerator { public TextGenerator Text { get; set; } public BlockKind Kind { get; set; } public NewLineKind NewLineKind { get; set; } public object Object { get; set; } public Block Parent { get; set; } public List<Block> Blocks { get; set; } private bool hasIndentChanged; public Func<bool> CheckGenerate; public Block() : this(BlockKind.Unknown) { } public Block(BlockKind kind) { Kind = kind; Blocks = new List<Block>(); Text = new TextGenerator(); hasIndentChanged = false; } public void AddBlock(Block block) { if (Text.StringBuilder.Length != 0 || hasIndentChanged) { hasIndentChanged = false; var newBlock = new Block { Text = Text.Clone() }; Text.StringBuilder.Clear(); AddBlock(newBlock); } block.Parent = this; Blocks.Add(block); } public IEnumerable<Block> FindBlocks(BlockKind kind) { foreach (var block in Blocks) { if (block.Kind == kind) yield return block; foreach (var childBlock in block.FindBlocks(kind)) yield return childBlock; } } public virtual StringBuilder Generate() { if (CheckGenerate != null && !CheckGenerate()) return new StringBuilder(); if (Blocks.Count == 0) return Text.StringBuilder; var builder = new StringBuilder(); Block previousBlock = null; var blockIndex = 0; foreach (var childBlock in Blocks) { var childText = childBlock.Generate(); var nextBlock = (++blockIndex < Blocks.Count) ? Blocks[blockIndex] : null; var skipBlock = false; if (nextBlock != null) { var nextText = nextBlock.Generate(); if (nextText.Length == 0 && childBlock.NewLineKind == NewLineKind.IfNotEmpty) skipBlock = true; } if (skipBlock) continue; if (childText.Length == 0) continue; if (previousBlock != null && previousBlock.NewLineKind == NewLineKind.BeforeNextBlock) builder.AppendLine(); builder.Append(childText); if (childBlock.NewLineKind == NewLineKind.Always) builder.AppendLine(); previousBlock = childBlock; } if (Text.StringBuilder.Length != 0) builder.Append(Text.StringBuilder); return builder; } public bool IsEmpty { get { if (Blocks.Any(block => !block.IsEmpty)) return false; return string.IsNullOrEmpty(Text.ToString()); } } #region ITextGenerator implementation public void Write(string msg, params object[] args) { Text.Write(msg, args); } public void WriteLine(string msg, params object[] args) { Text.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { Text.WriteLineIndent(msg, args); } public void NewLine() { Text.NewLine(); } public void NewLineIfNeeded() { Text.NewLineIfNeeded(); } public void NeedNewLine() { Text.NeedNewLine(); } public void ResetNewLine() { Text.ResetNewLine(); } public void Indent(uint indentation = 4u) { hasIndentChanged = true; Text.Indent(indentation); } public void Unindent() { hasIndentChanged = true; Text.Unindent(); } public void WriteOpenBraceAndIndent() { Text.WriteOpenBraceAndIndent(); } public void UnindentAndWriteCloseBrace() { Text.UnindentAndWriteCloseBrace(); } #endregion } public abstract class BlockGenerator : ITextGenerator { public Block RootBlock { get; } public Block ActiveBlock { get; private set; } public uint CurrentIndentation => ActiveBlock.Text.CurrentIndentation; protected BlockGenerator() { RootBlock = new Block(); ActiveBlock = RootBlock; } public virtual string Generate() { return RootBlock.Generate().ToString(); } #region Block helpers public void AddBlock(Block block) { ActiveBlock.AddBlock(block); } public void PushBlock(BlockKind kind = BlockKind.Unknown, object obj = null) { var block = new Block { Kind = kind, Object = obj }; block.Text.CurrentIndentation = CurrentIndentation; block.Text.IsStartOfLine = ActiveBlock.Text.IsStartOfLine; block.Text.NeedsNewLine = ActiveBlock.Text.NeedsNewLine; PushBlock(block); } public void PushBlock(Block block) { block.Parent = ActiveBlock; ActiveBlock.AddBlock(block); ActiveBlock = block; } public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never) { var block = ActiveBlock; ActiveBlock.NewLineKind = newLineKind; ActiveBlock = ActiveBlock.Parent; return block; } public IEnumerable<Block> FindBlocks(BlockKind kind) { return RootBlock.FindBlocks(kind); } public Block FindBlock(BlockKind kind) { return FindBlocks(kind).SingleOrDefault(); } #endregion #region ITextGenerator implementation public void Write(string msg, params object[] args) { ActiveBlock.Write(msg, args); } public void WriteLine(string msg, params object[] args) { ActiveBlock.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { ActiveBlock.WriteLineIndent(msg, args); } public void NewLine() { ActiveBlock.NewLine(); } public void NewLineIfNeeded() { ActiveBlock.NewLineIfNeeded(); } public void NeedNewLine() { ActiveBlock.NeedNewLine(); } public void ResetNewLine() { ActiveBlock.ResetNewLine(); } public void Indent(uint indentation = 4u) { ActiveBlock.Indent(indentation); } public void Unindent() { ActiveBlock.Unindent(); } public void WriteOpenBraceAndIndent() { ActiveBlock.WriteOpenBraceAndIndent(); } public void UnindentAndWriteCloseBrace() { ActiveBlock.UnindentAndWriteCloseBrace(); } #endregion } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Htc.Vita.Core.Log; namespace Htc.Vita.Core.IO { public abstract partial class FileVerifierV2 { /// <summary> /// Generates the checksum in Base64 form asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksumType">The checksum type.</param> /// <returns>Task&lt;System.String&gt;.</returns> public Task<string> GenerateChecksumInBase64Async( FileInfo fileInfo, ChecksumType checksumType) { return GenerateChecksumInBase64Async( fileInfo, checksumType, CancellationToken.None ); } /// <summary> /// Generates the checksum in Base64 form asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksumType">The checksum type.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A Task&lt;System.String&gt; representing the asynchronous operation.</returns> public async Task<string> GenerateChecksumInBase64Async( FileInfo fileInfo, ChecksumType checksumType, CancellationToken cancellationToken) { if (fileInfo == null) { return null; } if (checksumType == ChecksumType.Unknown || checksumType == ChecksumType.Auto) { Logger.GetInstance(typeof(FileVerifierV2)).Error("You should specify the checksum type"); return null; } var newFileInfo = new FileInfo(fileInfo.ToString()); if (!newFileInfo.Exists) { return null; } string result = null; try { result = await OnGenerateChecksumInBase64Async( newFileInfo, checksumType, cancellationToken ).ConfigureAwait(false); } catch (Exception e) { Logger.GetInstance(typeof(FileVerifierV2)).Error(e.ToString()); } return result; } /// <summary> /// Generates the checksum in hexadecimal form asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksumType">The checksum type.</param> /// <returns>Task&lt;System.String&gt;.</returns> public Task<string> GenerateChecksumInHexAsync( FileInfo fileInfo, ChecksumType checksumType) { return GenerateChecksumInHexAsync( fileInfo, checksumType, CancellationToken.None ); } /// <summary> /// Generates the checksum in hexadecimal form asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksumType">The checksum type.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A Task&lt;System.String&gt; representing the asynchronous operation.</returns> public async Task<string> GenerateChecksumInHexAsync( FileInfo fileInfo, ChecksumType checksumType, CancellationToken cancellationToken) { if (fileInfo == null) { return null; } if (checksumType == ChecksumType.Unknown || checksumType == ChecksumType.Auto) { Logger.GetInstance(typeof(FileVerifierV2)).Error("You should specify the checksum type"); return null; } var newFileInfo = new FileInfo(fileInfo.ToString()); if (!newFileInfo.Exists) { return null; } string result = null; try { result = await OnGenerateChecksumInHexAsync( newFileInfo, checksumType, cancellationToken ).ConfigureAwait(false); } catch (Exception e) { Logger.GetInstance(typeof(FileVerifierV2)).Error(e.ToString()); } return result; } /// <summary> /// Verifies the integrity asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksum">The checksum.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public Task<bool> VerifyIntegrityAsync( FileInfo fileInfo, string checksum) { return VerifyIntegrityAsync( fileInfo, checksum, CancellationToken.None ); } /// <summary> /// Verifies the integrity asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksum">The checksum.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public Task<bool> VerifyIntegrityAsync( FileInfo fileInfo, string checksum, CancellationToken cancellationToken) { return VerifyIntegrityAsync( fileInfo, checksum, ChecksumType.Auto, cancellationToken ); } /// <summary> /// Verifies the integrity asynchronous. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksum">The checksum.</param> /// <param name="checksumType">The checksum type.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> public Task<bool> VerifyIntegrityAsync( FileInfo fileInfo, string checksum, ChecksumType checksumType) { return VerifyIntegrityAsync( fileInfo, checksum, checksumType, CancellationToken.None ); } /// <summary> /// Verifies the integrity asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksum">The checksum.</param> /// <param name="checksumType">The checksum type.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A Task&lt;System.Boolean&gt; representing the asynchronous operation.</returns> public async Task<bool> VerifyIntegrityAsync( FileInfo fileInfo, string checksum, ChecksumType checksumType, CancellationToken cancellationToken) { if (fileInfo == null || string.IsNullOrWhiteSpace(checksum)) { return false; } if (checksumType == ChecksumType.Unknown) { Logger.GetInstance(typeof(FileVerifierV2)).Error("You should specify the checksum type"); return false; } var newFileInfo = new FileInfo(fileInfo.ToString()); if (!newFileInfo.Exists) { return false; } var result = false; try { result = await OnVerifyIntegrityAsync( newFileInfo, checksum, checksumType, cancellationToken ).ConfigureAwait(false); } catch (Exception e) { Logger.GetInstance(typeof(FileVerifierV2)).Error(e.ToString()); } return result; } /// <summary> /// Called when generating checksum in Base64 form asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksumType">The checksum type.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Task&lt;System.String&gt;.</returns> protected abstract Task<string> OnGenerateChecksumInBase64Async( FileInfo fileInfo, ChecksumType checksumType, CancellationToken cancellationToken ); /// <summary> /// Called when generating checksum in hexadecimal form asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksumType">The checksum type.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Task&lt;System.String&gt;.</returns> protected abstract Task<string> OnGenerateChecksumInHexAsync( FileInfo fileInfo, ChecksumType checksumType, CancellationToken cancellationToken ); /// <summary> /// Called when verifying integrity asynchronously. /// </summary> /// <param name="fileInfo">The file information.</param> /// <param name="checksum">The checksum.</param> /// <param name="checksumType">The checksum type.</param> /// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> protected abstract Task<bool> OnVerifyIntegrityAsync( FileInfo fileInfo, string checksum, ChecksumType checksumType, CancellationToken cancellationToken ); } }
using System; using FsCheck; using FsCheck.Fluent; using Microsoft.FSharp.Core; using Microsoft.FSharp.Collections; namespace FsCheckUtils { /// <summary> /// Extension methods for <see cref="FsCheck.Config" />. /// </summary> public static class ConfigExtensions { /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.MaxTest" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="maxTest">The value to user to override <see cref="FsCheck.Config.MaxTest" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithMaxTest(this Config config, int maxTest) { return new Config( maxTest, config.MaxFail, config.Replay, config.Name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.MaxFail" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="maxFail">The value to user to override <see cref="FsCheck.Config.MaxFail" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithMaxFail(this Config config, int maxFail) { return new Config( config.MaxTest, maxFail, config.Replay, config.Name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.Replay" /> property /// with a value of Some(<paramref name="replay"/>). /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="replay">The value to user to override <see cref="FsCheck.Config.Replay" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithReplay(this Config config, FsCheck.Random.StdGen replay) { return new Config( config.MaxTest, config.MaxFail, FSharpOption<FsCheck.Random.StdGen>.Some(replay), config.Name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.Replay" /> property /// with a value of None. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithNoReplay(this Config config) { return new Config( config.MaxTest, config.MaxFail, FSharpOption<FsCheck.Random.StdGen>.None, config.Name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.Name" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="name">The value to user to override <see cref="FsCheck.Config.Name" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithName(this Config config, string name) { return new Config( config.MaxTest, config.MaxFail, config.Replay, name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.StartSize" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="startSize">The value to user to override <see cref="FsCheck.Config.StartSize" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithStartSize(this Config config, int startSize) { return new Config( config.MaxTest, config.MaxFail, config.Replay, config.Name, startSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.EndSize" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="endSize">The value to user to override <see cref="FsCheck.Config.EndSize" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithEndSize(this Config config, int endSize) { return new Config( config.MaxTest, config.MaxFail, config.Replay, config.Name, config.StartSize, endSize, config.Every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.Every" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="every">The value to user to override <see cref="FsCheck.Config.Every" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithEvery(this Config config, FSharpFunc<int, FSharpFunc<FSharpList<object>, string>> every) { return new Config( config.MaxTest, config.MaxFail, config.Replay, config.Name, config.StartSize, config.EndSize, every, config.EveryShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.EveryShrink" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="everyShrink">The value to user to override <see cref="FsCheck.Config.EveryShrink" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithEveryShrink(this Config config, FSharpFunc<FSharpList<object>, string> everyShrink) { return new Config( config.MaxTest, config.MaxFail, config.Replay, config.Name, config.StartSize, config.EndSize, config.Every, everyShrink, config.Arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.Arbitrary" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="arbitrary">The value to user to override <see cref="FsCheck.Config.Arbitrary" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithArbitrary(this Config config, FSharpList<Type> arbitrary) { return new Config( config.MaxTest, config.MaxFail, config.Replay, config.Name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, arbitrary, config.Runner); } /// <summary> /// Clones a <see cref="FsCheck.Config" /> object but overrides the <see cref="FsCheck.Config.Runner" /> property. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to clone.</param> /// <param name="runner">The value to user to override <see cref="FsCheck.Config.Runner" /></param> /// <returns>A <see cref="FsCheck.Config" /> object.</returns> public static Config WithRunner(this Config config, IRunner runner) { return new Config( config.MaxTest, config.MaxFail, config.Replay, config.Name, config.StartSize, config.EndSize, config.Every, config.EveryShrink, config.Arbitrary, runner); } /// <summary> /// Creates a <see cref="FsCheck.Fluent.Configuration" /> object from a <see cref="FsCheck.Config" /> object. /// </summary> /// <param name="config">The <see cref="FsCheck.Config" /> object to be used to populate the /// properties of the new <see cref="FsCheck.Fluent.Configuration" /> object.</param> /// <returns>A <see cref="FsCheck.Fluent.Configuration" /> object.</returns> public static Configuration ToConfiguration(this Config config) { return new Configuration { MaxNbOfTest = config.MaxTest, MaxNbOfFailedTests = config.MaxFail, Name = config.Name, StartSize = config.StartSize, EndSize = config.EndSize, Every = ConvertEveryToFunc(config.Every), EveryShrink = ConvertEveryShrinkToFunc(config.EveryShrink), Runner = config.Runner }; } private static Func<int, object[], string> ConvertEveryToFunc(FSharpFunc<int, FSharpFunc<FSharpList<object>, string>> every) { return (n, args) => every.Invoke(n).Invoke(ListModule.OfSeq(args)); } private static Func<object[], string> ConvertEveryShrinkToFunc(FSharpFunc<FSharpList<object>, string> everyShrink) { return args => everyShrink.Invoke(ListModule.OfSeq(args)); } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack, Inc. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Globalization; using ServiceStack.Text.Common; namespace ServiceStack.Text { /// <summary> /// A fast, standards-based, serialization-issue free DateTime serializer. /// </summary> public static class DateTimeExtensions { public const long UnixEpoch = 621355968000000000L; private static readonly DateTime UnixEpochDateTimeUtc = new DateTime(UnixEpoch, DateTimeKind.Utc); private static readonly DateTime UnixEpochDateTimeUnspecified = new DateTime(UnixEpoch, DateTimeKind.Unspecified); private static readonly DateTime MinDateTimeUtc = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime FromUnixTime(this int unixTime) { return UnixEpochDateTimeUtc + TimeSpan.FromSeconds(unixTime); } public static DateTime FromUnixTime(this double unixTime) { return UnixEpochDateTimeUtc + TimeSpan.FromSeconds(unixTime); } public static DateTime FromUnixTime(this long unixTime) { return UnixEpochDateTimeUtc + TimeSpan.FromSeconds(unixTime); } public static long ToUnixTimeMsAlt(this DateTime dateTime) { return (dateTime.ToStableUniversalTime().Ticks - UnixEpoch) / TimeSpan.TicksPerMillisecond; } public static long ToUnixTimeMs(this DateTime dateTime) { var universal = ToDateTimeSinceUnixEpoch(dateTime); return (long)universal.TotalMilliseconds; } public static long ToUnixTime(this DateTime dateTime) { return (dateTime.ToDateTimeSinceUnixEpoch().Ticks) / TimeSpan.TicksPerSecond; } private static TimeSpan ToDateTimeSinceUnixEpoch(this DateTime dateTime) { var dtUtc = dateTime; if (dateTime.Kind != DateTimeKind.Utc) { dtUtc = dateTime.Kind == DateTimeKind.Unspecified && dateTime > DateTime.MinValue && dateTime < DateTime.MaxValue ? DateTime.SpecifyKind(dateTime.Subtract(DateTimeSerializer.LocalTimeZone.GetUtcOffset(dateTime)), DateTimeKind.Utc) : dateTime.ToStableUniversalTime(); } var universal = dtUtc.Subtract(UnixEpochDateTimeUtc); return universal; } public static long ToUnixTimeMs(this long ticks) { return (ticks - UnixEpoch) / TimeSpan.TicksPerMillisecond; } public static DateTime FromUnixTimeMs(this double msSince1970) { return UnixEpochDateTimeUtc + TimeSpan.FromMilliseconds(msSince1970); } public static DateTime FromUnixTimeMs(this long msSince1970) { return UnixEpochDateTimeUtc + TimeSpan.FromMilliseconds(msSince1970); } public static DateTime FromUnixTimeMs(this long msSince1970, TimeSpan offset) { return DateTime.SpecifyKind(UnixEpochDateTimeUnspecified + TimeSpan.FromMilliseconds(msSince1970) + offset, DateTimeKind.Local); } public static DateTime FromUnixTimeMs(this double msSince1970, TimeSpan offset) { return DateTime.SpecifyKind(UnixEpochDateTimeUnspecified + TimeSpan.FromMilliseconds(msSince1970) + offset, DateTimeKind.Local); } public static DateTime FromUnixTimeMs(string msSince1970) { long ms; if (long.TryParse(msSince1970, out ms)) return ms.FromUnixTimeMs(); // Do we really need to support fractional unix time ms time strings?? return double.Parse(msSince1970).FromUnixTimeMs(); } public static DateTime FromUnixTimeMs(string msSince1970, TimeSpan offset) { long ms; if (long.TryParse(msSince1970, out ms)) return ms.FromUnixTimeMs(offset); // Do we really need to support fractional unix time ms time strings?? return double.Parse(msSince1970).FromUnixTimeMs(offset); } public static DateTime RoundToMs(this DateTime dateTime) { return new DateTime((dateTime.Ticks / TimeSpan.TicksPerMillisecond) * TimeSpan.TicksPerMillisecond, dateTime.Kind); } public static DateTime RoundToSecond(this DateTime dateTime) { return new DateTime((dateTime.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond, dateTime.Kind); } public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan) { return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks)); } public static string ToShortestXsdDateTimeString(this DateTime dateTime) { return DateTimeSerializer.ToShortestXsdDateTimeString(dateTime); } public static DateTime FromShortestXsdDateTimeString(this string xsdDateTime) { return DateTimeSerializer.ParseShortestXsdDateTime(xsdDateTime); } public static bool IsEqualToTheSecond(this DateTime dateTime, DateTime otherDateTime) { return dateTime.ToStableUniversalTime().RoundToSecond().Equals(otherDateTime.ToStableUniversalTime().RoundToSecond()); } public static string ToTimeOffsetString(this TimeSpan offset, string seperator = "") { var hours = Math.Abs(offset.Hours).ToString(CultureInfo.InvariantCulture); var minutes = Math.Abs(offset.Minutes).ToString(CultureInfo.InvariantCulture); return (offset < TimeSpan.Zero ? "-" : "+") + (hours.Length == 1 ? "0" + hours : hours) + seperator + (minutes.Length == 1 ? "0" + minutes : minutes); } public static TimeSpan FromTimeOffsetString(this string offsetString) { if (!offsetString.Contains(":")) offsetString = offsetString.Insert(offsetString.Length - 2, ":"); offsetString = offsetString.TrimStart('+'); return TimeSpan.Parse(offsetString); } public static DateTime ToStableUniversalTime(this DateTime dateTime) { if (dateTime.Kind == DateTimeKind.Utc) return dateTime; if (dateTime == DateTime.MinValue) return MinDateTimeUtc; return PclExport.Instance.ToStableUniversalTime(dateTime); } public static string FmtSortableDate(this DateTime from) { return from.ToString("yyyy-MM-dd"); } public static string FmtSortableDateTime(this DateTime from) { return from.ToString("u"); } public static DateTime LastMonday(this DateTime from) { var mondayOfWeek = from.Date.AddDays(-(int)from.DayOfWeek + 1); return mondayOfWeek; } public static DateTime StartOfLastMonth(this DateTime from) { return new DateTime(from.Date.Year, from.Date.Month, 1).AddMonths(-1); } public static DateTime EndOfLastMonth(this DateTime from) { return new DateTime(from.Date.Year, from.Date.Month, 1).AddDays(-1); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; namespace Orleans.Messaging { // <summary> // This class is used on the client only. // It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side. // // There is one ClientMessageCenter instance per OutsideRuntimeClient. There can be multiple ClientMessageCenter instances // in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not // generally done in practice. // // Each ClientMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection // to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to // the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together // based on their hash code mod a reasonably large number (currently 8192). // // When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known // gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to // the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the // connection is live. // // Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to // reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily) // dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected). // There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes. // // The list of known gateways is managed by the GatewayManager class. See comments there for details... // ======================================================================================================================================= // Locking and lock protocol: // The ClientMessageCenter instance itself may be accessed by many client threads simultaneously, and each GatewayConnection instance // is accessed by its own thread, by the thread for its Receiver, and potentially by client threads from within the ClientMessageCenter. // Thus, we need locks to protect the various data structured from concurrent modifications. // // Each GatewayConnection instance has a "lockable" field that is used to lock local information. This lock is used by both the GatewayConnection // thread and the Receiver thread. // // The ClientMessageCenter instance also has a "lockable" field. This lock is used by any client thread running methods within the instance. // // Note that we take care to ensure that client threads never need locked access to GatewayConnection state and GatewayConnection threads never need // locked access to ClientMessageCenter state. Thus, we don't need to worry about lock ordering across these objects. // // Finally, the GatewayManager instance within the ClientMessageCenter has two collections, knownGateways and knownDead, that it needs to // protect with locks. Rather than using a "lockable" field, each collection is lcoked to protect the collection. // All sorts of threads can run within the GatewayManager, including client threads and GatewayConnection threads, so we need to // be careful about locks here. The protocol we use is to always take GatewayManager locks last, to only take them within GatewayManager methods, // and to always release them before returning from the method. In addition, we never simultaneously hold the knownGateways and knownDead locks, // so there's no need to worry about the order in which we take and release those locks. // </summary> internal class ClientMessageCenter : IMessageCenter, IDisposable { internal readonly SerializationManager SerializationManager; #region Constants internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server #endregion internal GrainId ClientId { get; private set; } public IRuntimeClient RuntimeClient { get; } internal bool Running { get; private set; } internal readonly GatewayManager GatewayManager; internal readonly BlockingCollection<Message> PendingInboundMessages; private readonly Dictionary<Uri, GatewayConnection> gatewayConnections; private int numMessages; // The grainBuckets array is used to select the connection to use when sending an ordered message to a grain. // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. private readonly WeakReference[] grainBuckets; private readonly ILogger logger; private readonly object lockable; public SiloAddress MyAddress { get; private set; } private readonly QueueTrackingStatistic queueTracking; private int numberOfConnectedGateways = 0; private readonly MessageFactory messageFactory; private readonly IClusterConnectionStatusListener connectionStatusListener; private readonly ILoggerFactory loggerFactory; private readonly TimeSpan openConnectionTimeout; private readonly ExecutorService executorService; public ClientMessageCenter( IOptions<GatewayOptions> gatewayOptions, IOptions<ClientMessagingOptions> clientMessagingOptions, IPAddress localAddress, int gen, GrainId clientId, IGatewayListProvider gatewayListProvider, SerializationManager serializationManager, IRuntimeClient runtimeClient, MessageFactory messageFactory, IClusterConnectionStatusListener connectionStatusListener, ExecutorService executorService, ILoggerFactory loggerFactory, IOptions<NetworkingOptions> networkingOptions) { this.loggerFactory = loggerFactory; this.openConnectionTimeout = networkingOptions.Value.OpenConnectionTimeout; this.SerializationManager = serializationManager; this.executorService = executorService; lockable = new object(); MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen); ClientId = clientId; this.RuntimeClient = runtimeClient; this.messageFactory = messageFactory; this.connectionStatusListener = connectionStatusListener; Running = false; GatewayManager = new GatewayManager(gatewayOptions.Value, gatewayListProvider, loggerFactory); PendingInboundMessages = new BlockingCollection<Message>(); gatewayConnections = new Dictionary<Uri, GatewayConnection>(); numMessages = 0; grainBuckets = new WeakReference[clientMessagingOptions.Value.ClientSenderBuckets]; logger = loggerFactory.CreateLogger<ClientMessageCenter>(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Proxy grain client constructed"); IntValueStatistic.FindOrCreate( StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () => { lock (gatewayConnections) { return gatewayConnections.Values.Count(conn => conn.IsLive); } }); if (StatisticsCollector.CollectQueueStats) { queueTracking = new QueueTrackingStatistic("ClientReceiver"); } } public void Start() { Running = true; if (StatisticsCollector.CollectQueueStats) { queueTracking.OnStartExecution(); } if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Proxy grain client started"); } public void PrepareToStop() { // put any pre stop logic here. } public void Stop() { Running = false; Utils.SafeExecute(() => { PendingInboundMessages.CompleteAdding(); }); if (StatisticsCollector.CollectQueueStats) { queueTracking.OnStopExecution(); } GatewayManager.Stop(); foreach (var gateway in gatewayConnections.Values.ToArray()) { gateway.Stop(); } } public void SendMessage(Message msg) { GatewayConnection gatewayConnection = null; bool startRequired = false; if (!Running) { this.logger.Error(ErrorCode.ProxyClient_MsgCtrNotRunning, $"Ignoring {msg} because the Client message center is not running"); return; } // If there's a specific gateway specified, use it if (msg.TargetSilo != null && GatewayManager.GetLiveGateways().Contains(msg.TargetSilo.ToGatewayUri())) { Uri addr = msg.TargetSilo.ToGatewayUri(); lock (lockable) { if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive) { gatewayConnection = new GatewayConnection(addr, this, this.messageFactory, executorService, this.loggerFactory, this.openConnectionTimeout); gatewayConnections[addr] = gatewayConnection; if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Creating gateway to {0} for pre-addressed message", addr); startRequired = true; } } } // For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion. else if (msg.TargetGrain.IsSystemTarget || msg.IsUnordered) { // Get the cached list of live gateways. // Pick a next gateway name in a round robin fashion. // See if we have a live connection to it. // If Yes, use it. // If not, create a new GatewayConnection and start it. // If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames. lock (lockable) { int msgNumber = numMessages; numMessages = unchecked(numMessages + 1); IList<Uri> gatewayNames = GatewayManager.GetLiveGateways(); int numGateways = gatewayNames.Count; if (numGateways == 0) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager); return; } Uri addr = gatewayNames[msgNumber % numGateways]; if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive) { gatewayConnection = new GatewayConnection(addr, this, this.messageFactory, this.executorService, this.loggerFactory, this.openConnectionTimeout); gatewayConnections[addr] = gatewayConnection; if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_CreatedGatewayUnordered, "Creating gateway to {0} for unordered message to grain {1}", addr, msg.TargetGrain); startRequired = true; } // else - Fast path - we've got a live gatewayConnection to use } } // Otherwise, use the buckets to ensure ordering. else { var index = msg.TargetGrain.GetHashCode_Modulo((uint)grainBuckets.Length); lock (lockable) { // Repeated from above, at the declaration of the grainBuckets array: // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. var weakRef = grainBuckets[index]; if ((weakRef != null) && weakRef.IsAlive) { gatewayConnection = weakRef.Target as GatewayConnection; } if ((gatewayConnection == null) || !gatewayConnection.IsLive) { var addr = GatewayManager.GetLiveGateway(); if (addr == null) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager); return; } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain); if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive) { gatewayConnection = new GatewayConnection(addr, this, this.messageFactory, this.executorService, this.loggerFactory, this.openConnectionTimeout); gatewayConnections[addr] = gatewayConnection; if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index, msg.TargetGrain.GetHashCode().ToString("x")); startRequired = true; } grainBuckets[index] = new WeakReference(gatewayConnection); } } } if (startRequired) { gatewayConnection.Start(); if (!gatewayConnection.IsLive) { // if failed to start Gateway connection (failed to connect), try sending this msg to another Gateway. RejectOrResend(msg); return; } } try { gatewayConnection.QueueRequest(msg); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, gatewayConnection.Address); } catch (InvalidOperationException) { // This exception can be thrown if the gateway connection we selected was closed since we checked (i.e., we lost the race) // If this happens, we reject if the message is targeted to a specific silo, or try again if not RejectOrResend(msg); } } private void RejectOrResend(Message msg) { if (msg.TargetSilo != null) { RejectMessage(msg, String.Format("Target silo {0} is unavailable", msg.TargetSilo)); } else { SendMessage(msg); } } public Task<IGrainTypeResolver> GetGrainTypeResolver(IInternalGrainFactory grainFactory) { var silo = GetLiveGatewaySiloAddress(); return GetTypeManager(silo, grainFactory).GetClusterGrainTypeResolver(); } public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(IInternalGrainFactory grainFactory) { var silo = GetLiveGatewaySiloAddress(); return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public Message WaitMessage(Message.Categories type, CancellationToken ct) { try { if (ct.IsCancellationRequested) { return null; } // Don't pass CancellationToken to Take. It causes too much spinning. Message msg = PendingInboundMessages.Take(); #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectQueueStats) { queueTracking.OnDeQueueRequest(msg); } #endif return msg; } catch (ThreadAbortException exc) { // Silo may be shutting-down, so downgrade to verbose log logger.Debug(ErrorCode.ProxyClient_ThreadAbort, "Received thread abort exception -- exiting. {0}", exc); Thread.ResetAbort(); return null; } catch (OperationCanceledException exc) { logger.Debug(ErrorCode.ProxyClient_OperationCancelled, "Received operation cancelled exception -- exiting. {0}", exc); return null; } catch (ObjectDisposedException exc) { logger.Debug(ErrorCode.ProxyClient_OperationCancelled, "Received Object Disposed exception -- exiting. {0}", exc); return null; } catch (InvalidOperationException exc) { logger.Debug(ErrorCode.ProxyClient_OperationCancelled, "Received Invalid Operation exception -- exiting. {0}", exc); return null; } catch (Exception ex) { logger.Error(ErrorCode.ProxyClient_ReceiveError, "Unexpected error getting an inbound message", ex); return null; } } public void RegisterLocalMessageHandler(Message.Categories category, Action<Message> handler) { } internal void QueueIncomingMessage(Message msg) { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectQueueStats) { queueTracking.OnEnQueueRequest(1, PendingInboundMessages.Count, msg); } #endif PendingInboundMessages.Add(msg); } private void RejectMessage(Message msg, string reasonFormat, params object[] reasonParams) { if (!Running) return; var reason = String.Format(reasonFormat, reasonParams); if (msg.Direction != Message.Directions.Request) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); } else { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason); QueueIncomingMessage(error); } } /// <summary> /// For testing use only /// </summary> public void Disconnect() { foreach (var connection in gatewayConnections.Values.ToArray()) { connection.Stop(); } } /// <summary> /// For testing use only. /// </summary> public void Reconnect() { throw new NotImplementedException("Reconnect"); } #region Random IMessageCenter stuff public int SendQueueLength { get { return 0; } } public int ReceiveQueueLength { get { return 0; } } #endregion private IClusterTypeManager GetTypeManager(SiloAddress destination, IInternalGrainFactory grainFactory) { return grainFactory.GetSystemTarget<IClusterTypeManager>(Constants.TypeManagerId, destination); } private SiloAddress GetLiveGatewaySiloAddress() { var gateway = GatewayManager.GetLiveGateway(); if (gateway == null) { throw new OrleansException("Not connected to a gateway"); } return gateway.ToSiloAddress(); } internal void UpdateClientId(GrainId clientId) { if (ClientId.Category != UniqueKey.Category.Client) throw new InvalidOperationException("Only handshake client ID can be updated with a cluster ID."); if (clientId.Category != UniqueKey.Category.GeoClient) throw new ArgumentException("Handshake client ID can only be updated with a geo client.", nameof(clientId)); ClientId = clientId; } internal void OnGatewayConnectionOpen() { Interlocked.Increment(ref numberOfConnectedGateways); } internal void OnGatewayConnectionClosed() { if (Interlocked.Decrement(ref numberOfConnectedGateways) == 0) { this.connectionStatusListener.NotifyClusterConnectionLost(); } } public void Dispose() { PendingInboundMessages.Dispose(); if (gatewayConnections != null) foreach (var item in gatewayConnections) { item.Value.Dispose(); } GatewayManager.Dispose(); } } }
/* * Copyright (c) Citrix Systems, 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) 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. * * 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.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// A secret /// First published in XenServer 5.6. /// </summary> public partial class Secret : XenObject<Secret> { public Secret() { } public Secret(string uuid, string value, Dictionary<string, string> other_config) { this.uuid = uuid; this.value = value; this.other_config = other_config; } /// <summary> /// Creates a new Secret from a Proxy_Secret. /// </summary> /// <param name="proxy"></param> public Secret(Proxy_Secret proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Secret update) { uuid = update.uuid; value = update.value; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_Secret proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; value = proxy.value == null ? null : (string)proxy.value; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Secret ToProxy() { Proxy_Secret result_ = new Proxy_Secret(); result_.uuid = uuid ?? ""; result_.value = value ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new Secret from a Hashtable. /// </summary> /// <param name="table"></param> public Secret(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); value = Marshalling.ParseString(table, "value"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Secret other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._value, other._value) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Secret server) { if (opaqueRef == null) { Proxy_Secret p = this.ToProxy(); return session.proxy.secret_create(session.uuid, p).parse(); } else { if (!Helper.AreEqual2(_value, server._value)) { Secret.set_value(session, opaqueRef, _value); } if (!Helper.AreEqual2(_other_config, server._other_config)) { Secret.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static Secret get_record(Session session, string _secret) { return new Secret((Proxy_Secret)session.proxy.secret_get_record(session.uuid, _secret ?? "").parse()); } /// <summary> /// Get a reference to the secret instance with the specified UUID. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Secret> get_by_uuid(Session session, string _uuid) { return XenRef<Secret>.Create(session.proxy.secret_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Create a new secret instance, and return its handle. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Secret> create(Session session, Secret _record) { return XenRef<Secret>.Create(session.proxy.secret_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Create a new secret instance, and return its handle. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, Secret _record) { return XenRef<Task>.Create(session.proxy.async_secret_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified secret instance. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static void destroy(Session session, string _secret) { session.proxy.secret_destroy(session.uuid, _secret ?? "").parse(); } /// <summary> /// Destroy the specified secret instance. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static XenRef<Task> async_destroy(Session session, string _secret) { return XenRef<Task>.Create(session.proxy.async_secret_destroy(session.uuid, _secret ?? "").parse()); } /// <summary> /// Get the uuid field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static string get_uuid(Session session, string _secret) { return (string)session.proxy.secret_get_uuid(session.uuid, _secret ?? "").parse(); } /// <summary> /// Get the value field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static string get_value(Session session, string _secret) { return (string)session.proxy.secret_get_value(session.uuid, _secret ?? "").parse(); } /// <summary> /// Get the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> public static Dictionary<string, string> get_other_config(Session session, string _secret) { return Maps.convert_from_proxy_string_string(session.proxy.secret_get_other_config(session.uuid, _secret ?? "").parse()); } /// <summary> /// Set the value field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_value">New value to set</param> public static void set_value(Session session, string _secret, string _value) { session.proxy.secret_set_value(session.uuid, _secret ?? "", _value ?? "").parse(); } /// <summary> /// Set the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _secret, Dictionary<string, string> _other_config) { session.proxy.secret_set_other_config(session.uuid, _secret ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given secret. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _secret, string _key, string _value) { session.proxy.secret_add_to_other_config(session.uuid, _secret ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given secret. If the key is not in that Map, then do nothing. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_secret">The opaque_ref of the given secret</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _secret, string _key) { session.proxy.secret_remove_from_other_config(session.uuid, _secret ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the secrets known to the system. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Secret>> get_all(Session session) { return XenRef<Secret>.Create(session.proxy.secret_get_all(session.uuid).parse()); } /// <summary> /// Get all the secret Records at once, in a single XML RPC call /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Secret>, Secret> get_all_records(Session session) { return XenRef<Secret>.Create<Proxy_Secret>(session.proxy.secret_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// the secret /// </summary> public virtual string value { get { return _value; } set { if (!Helper.AreEqual(value, _value)) { _value = value; Changed = true; NotifyPropertyChanged("value"); } } } private string _value; /// <summary> /// other_config /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System; using System.Globalization; using System.Text; ////using Microsoft.Win32; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // Represents a Globally Unique Identifier. [Serializable] [StructLayout( LayoutKind.Sequential )] public struct Guid : /*IFormattable,*/ IComparable, IComparable< Guid >, IEquatable< Guid > { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid( byte[] b ) { if(b == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "b" ); #else throw new ArgumentNullException(); #endif } if(b.Length != 16) { #if EXCEPTION_STRINGS throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_GuidArrayCtor" ), "16" ) ); #else throw new ArgumentException(); #endif } _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant( false )] public Guid( uint a , ushort b , ushort c , byte d , byte e , byte f , byte g , byte h , byte i , byte j , byte k ) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } //// // Creates a new guid based on the value in the string. The value is made up //// // of hex digits speared by the dash ("-"). The string may begin and end with //// // brackets ("{", "}"). //// // //// // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where //// // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, //// // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" //// // //// public Guid( String g ) //// { //// if(g == null) //// { //// throw new ArgumentNullException( "g" ); //// } //// //// int startPos = 0; //// int temp; //// long templ; //// int currentPos = 0; //// //// try //// { //// // Check if it's of the form dddddddd-dddd-dddd-dddd-dddddddddddd //// if(g.IndexOf( '-', 0 ) >= 0) //// { //// //// String guidString = g.Trim(); //Remove Whitespace //// //// // check to see that it's the proper length //// if(guidString[0] == '{') //// { //// if(guidString.Length != 38 || guidString[37] != '}') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// startPos = 1; //// } //// else if(guidString[0] == '(') //// { //// if(guidString.Length != 38 || guidString[37] != ')') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// startPos = 1; //// } //// else if(guidString.Length != 36) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// if(guidString[8 + startPos] != '-' || //// guidString[13 + startPos] != '-' || //// guidString[18 + startPos] != '-' || //// guidString[23 + startPos] != '-') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidDashes" ) ); //// } //// //// currentPos = startPos; //// _a = TryParse( guidString, ref currentPos, 8 ); //// ++currentPos; //Increment past the '-'; //// _b = (short)TryParse( guidString, ref currentPos, 4 ); //// ++currentPos; //Increment past the '-'; //// _c = (short)TryParse( guidString, ref currentPos, 4 ); //// ++currentPos; //Increment past the '-'; //// temp = TryParse( guidString, ref currentPos, 4 ); //// ++currentPos; //Increment past the '-'; //// startPos = currentPos; //// templ = ParseNumbers.StringToLong( guidString, 16, ParseNumbers.NoSpace, ref currentPos ); //// if(currentPos - startPos != 12) //// { //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidInvLen" ) ) ); //// } //// _d = (byte)(temp >> 8); //// _e = (byte)(temp); //// temp = (int)(templ >> 32); //// _f = (byte)(temp >> 8); //// _g = (byte)(temp); //// temp = (int)(templ); //// _h = (byte)(temp >> 24); //// _i = (byte)(temp >> 16); //// _j = (byte)(temp >> 8); //// _k = (byte)(temp); //// } //// // Else check if it is of the form //// // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} //// else if(g.IndexOf( '{', 0 ) >= 0) //// { //// int numStart = 0; //// int numLen = 0; //// //// // Convert to lower case //// //g = g.ToLower(); //// //// // Eat all of the whitespace //// g = EatAllWhitespace( g ); //// //// // Check for leading '{' //// if(g[0] != '{') //// throw new FormatException( Environment.GetResourceString( "Format_GuidBrace" ) ); //// //// // Check for '0x' //// if(!IsHexPrefix( g, 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{0xdddddddd, etc}" ) ); //// //// // Find the end of this hex number (since it is not fixed length) //// numStart = 3; //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// //// // Read in the number //// _a = (int)ParseNumbers.StringToInt( g.Substring( numStart, numLen ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// //// // Check for '0x' //// if(!IsHexPrefix( g, numStart + numLen + 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{0xdddddddd, 0xdddd, etc}" ) ); //// //// // +3 to get by ',0x' //// numStart = numStart + numLen + 3; //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// //// // Read in the number //// _b = (short)ParseNumbers.StringToInt( //// g.Substring( numStart, numLen ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// //// // Check for '0x' //// if(!IsHexPrefix( g, numStart + numLen + 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{0xdddddddd, 0xdddd, 0xdddd, etc}" ) ); //// //// // +3 to get by ',0x' //// numStart = numStart + numLen + 3; //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// //// // Read in the number //// _c = (short)ParseNumbers.StringToInt( //// g.Substring( numStart, numLen ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// //// // Check for '{' //// if(g.Length <= numStart + numLen + 1 || g[numStart + numLen + 1] != '{') //// throw new FormatException( Environment.GetResourceString( "Format_GuidBrace" ) ); //// //// // Prepare for loop //// numLen++; //// byte[] bytes = new byte[8]; //// //// for(int i = 0; i < 8; i++) //// { //// // Check for '0x' //// if(!IsHexPrefix( g, numStart + numLen + 1 )) //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidHexPrefix" ), "{... { ... 0xdd, ...}}" ) ); //// //// // +3 to get by ',0x' or '{0x' for first case //// numStart = numStart + numLen + 3; //// //// // Calculate number length //// if(i < 7) // first 7 cases //// { //// numLen = g.IndexOf( ',', numStart ) - numStart; //// if(numLen <= 0) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidComma" ) ); //// } //// } //// else // last case ends with '}', not ',' //// { //// numLen = g.IndexOf( '}', numStart ) - numStart; //// if(numLen <= 0) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidBraceAfterLastNumber" ) ); //// } //// } //// //// // Read in the number //// uint number = (uint)Convert.ToInt32( g.Substring( numStart, numLen ), 16 ); //// // check for overflow //// if(number > 255) //// { //// throw new FormatException( Environment.GetResourceString( "Overflow_Byte" ) ); //// } //// bytes[i] = (byte)number; //// } //// //// _d = bytes[0]; //// _e = bytes[1]; //// _f = bytes[2]; //// _g = bytes[3]; //// _h = bytes[4]; //// _i = bytes[5]; //// _j = bytes[6]; //// _k = bytes[7]; //// //// // Check for last '}' //// if(numStart + numLen + 1 >= g.Length || g[numStart + numLen + 1] != '}') //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidEndBrace" ) ); //// } //// //// // Check if we have extra characters at the end //// if(numStart + numLen + 1 != g.Length - 1) //// { //// throw new FormatException( Environment.GetResourceString( "Format_ExtraJunkAtEnd" ) ); //// } //// //// return; //// } //// else //// // Check if it's of the form dddddddddddddddddddddddddddddddd //// { //// String guidString = g.Trim(); //Remove Whitespace //// //// if(guidString.Length != 32) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvLen" ) ); //// } //// //// for(int i = 0; i < guidString.Length; i++) //// { //// char ch = guidString[i]; //// if(ch >= '0' && ch <= '9') //// { //// continue; //// } //// else //// { //// char upperCaseCh = Char.ToUpper( ch, CultureInfo.InvariantCulture ); //// if(upperCaseCh >= 'A' && upperCaseCh <= 'F') //// { //// continue; //// } //// } //// //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvalidChar" ) ); //// } //// //// _a = (int)ParseNumbers.StringToInt( guidString.Substring( startPos, 8 ), // first DWORD //// 16, // hex //// ParseNumbers.IsTight ); // tight parsing //// startPos += 8; //// _b = (short)ParseNumbers.StringToInt( guidString.Substring( startPos, 4 ), //// 16, //// ParseNumbers.IsTight ); //// startPos += 4; //// _c = (short)ParseNumbers.StringToInt( guidString.Substring( startPos, 4 ), //// 16, //// ParseNumbers.IsTight ); //// //// startPos += 4; //// temp = (short)ParseNumbers.StringToInt( guidString.Substring( startPos, 4 ), //// 16, //// ParseNumbers.IsTight ); //// startPos += 4; //// currentPos = startPos; //// templ = ParseNumbers.StringToLong( guidString, 16, startPos, ref currentPos ); //// if(currentPos - startPos != 12) //// { //// throw new FormatException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Format_GuidInvLen" ) ) ); //// } //// _d = (byte)(temp >> 8); //// _e = (byte)(temp); //// temp = (int)(templ >> 32); //// _f = (byte)(temp >> 8); //// _g = (byte)(temp); //// temp = (int)(templ); //// _h = (byte)(temp >> 24); //// _i = (byte)(temp >> 16); //// _j = (byte)(temp >> 8); //// _k = (byte)(temp); //// } //// } //// catch(IndexOutOfRangeException) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidUnrecognized" ) ); //// } //// } //// //// // Creates a new GUID initialized to the value represented by the arguments. //// // //// public Guid( int a, short b, short c, byte[] d ) //// { //// if(d == null) //// throw new ArgumentNullException( "d" ); //// // Check that array is not too big //// if(d.Length != 8) //// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_GuidArrayCtor" ), "8" ) ); //// //// _a = a; //// _b = b; //// _c = c; //// _d = d[0]; //// _e = d[1]; //// _f = d[2]; //// _g = d[3]; //// _h = d[4]; //// _i = d[5]; //// _j = d[6]; //// _k = d[7]; //// } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid( int a , short b , short c , byte d , byte e , byte f , byte g , byte h , byte i , byte j , byte k ) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } //// private static int TryParse( String str, ref int parsePos, int requiredLength ) //// { //// int currStart = parsePos; //// // the exception message from ParseNumbers is better //// int retVal = ParseNumbers.StringToInt( str, 16, ParseNumbers.NoSpace, ref parsePos ); //// //// //If we didn't parse enough characters, there's clearly an error. //// if(parsePos - currStart != requiredLength) //// { //// throw new FormatException( Environment.GetResourceString( "Format_GuidInvalidChar" ) ); //// } //// return retVal; //// } //// //// private static String EatAllWhitespace( String str ) //// { //// int newLength = 0; //// char[] chArr = new char[str.Length]; //// char curChar; //// //// // Now get each char from str and if it is not whitespace add it to chArr //// for(int i = 0; i < str.Length; i++) //// { //// curChar = str[i]; //// if(!Char.IsWhiteSpace( curChar )) //// { //// chArr[newLength++] = curChar; //// } //// } //// //// // Return a new string based on chArr //// return new String( chArr, 0, newLength ); //// } //// //// private static bool IsHexPrefix( String str, int i ) //// { //// if(str[i] == '0' && (Char.ToLower( str[i + 1], CultureInfo.InvariantCulture ) == 'x')) //// return true; //// else //// return false; //// } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } //// // Returns the guid in "registry" format. //// public override String ToString() //// { //// return ToString( "D", null ); //// } public override int GetHashCode() { return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k); } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals( Object o ) { // Check that o is a Guid first if(o == null || !(o is Guid)) { return false; } return Equals( (Guid)o ); } public bool Equals( Guid g ) { // Now compare each of the elements if(g._a != _a) return false; if(g._b != _b) return false; if(g._c != _c) return false; if(g._d != _d) return false; if(g._e != _e) return false; if(g._f != _f) return false; if(g._g != _g) return false; if(g._h != _h) return false; if(g._i != _i) return false; if(g._j != _j) return false; if(g._k != _k) return false; return true; } private int GetResult( uint me, uint them ) { if(me < them) { return -1; } return 1; } public int CompareTo( Object value ) { if(value == null) { return 1; } if(!(value is Guid)) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeGuid" ) ); #else throw new ArgumentException(); #endif } return CompareTo( (Guid)value ); } public int CompareTo(Guid value) { if (value._a!=this._a) { return GetResult((uint)this._a, (uint)value._a); } if (value._b!=this._b) { return GetResult((uint)this._b, (uint)value._b); } if (value._c!=this._c) { return GetResult((uint)this._c, (uint)value._c); } if (value._d!=this._d) { return GetResult((uint)this._d, (uint)value._d); } if (value._e!=this._e) { return GetResult((uint)this._e, (uint)value._e); } if (value._f!=this._f) { return GetResult((uint)this._f, (uint)value._f); } if (value._g!=this._g) { return GetResult((uint)this._g, (uint)value._g); } if (value._h!=this._h) { return GetResult((uint)this._h, (uint)value._h); } if (value._i!=this._i) { return GetResult((uint)this._i, (uint)value._i); } if (value._j!=this._j) { return GetResult((uint)this._j, (uint)value._j); } if (value._k!=this._k) { return GetResult((uint)this._k, (uint)value._k); } return 0; } public static bool operator ==( Guid a, Guid b ) { // Now compare each of the elements if(a._a != b._a) return false; if(a._b != b._b) return false; if(a._c != b._c) return false; if(a._d != b._d) return false; if(a._e != b._e) return false; if(a._f != b._f) return false; if(a._g != b._g) return false; if(a._h != b._h) return false; if(a._i != b._i) return false; if(a._j != b._j) return false; if(a._k != b._k) return false; return true; } public static bool operator !=( Guid a, Guid b ) { return !(a == b); } // This will create a new guid. Since we've now decided that constructors should 0-init, // we need a method that allows users to create a guid. public static Guid NewGuid() { //// Guid guid; //// Marshal.ThrowExceptionForHR( Win32Native.CoCreateGuid( out guid ), new IntPtr( -1 ) ); //// return guid; byte[] buf = new byte[16]; Random rnd = new Random(); rnd.NextBytes( buf ); return new Guid( buf ); } //// public String ToString( String format ) //// { //// return ToString( format, null ); //// } //// //// private static char HexToChar( int a ) //// { //// a = a & 0xf; //// return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); //// } //// //// private static int HexsToChars( char[] guidChars, int offset, int a, int b ) //// { //// guidChars[offset++] = HexToChar( a >> 4 ); //// guidChars[offset++] = HexToChar( a ); //// guidChars[offset++] = HexToChar( b >> 4 ); //// guidChars[offset++] = HexToChar( b ); //// return offset; //// } //// //// // IFormattable interface //// // We currently ignore provider //// public String ToString( String format, IFormatProvider provider ) //// { //// if(format == null || format.Length == 0) //// format = "D"; //// //// char[] guidChars; //// int offset = 0; //// int strLength = 38; //// bool dash = true; //// //// if(format.Length != 1) //// { //// // all acceptable format string are of length 1 //// throw new FormatException( Environment.GetResourceString( "Format_InvalidGuidFormatSpecification" ) ); //// } //// //// char formatCh = format[0]; //// if(formatCh == 'D' || formatCh == 'd') //// { //// guidChars = new char[36]; //// strLength = 36; //// } //// else if(formatCh == 'N' || formatCh == 'n') //// { //// guidChars = new char[32]; //// strLength = 32; //// dash = false; //// } //// else if(formatCh == 'B' || formatCh == 'b') //// { //// guidChars = new char[38]; //// guidChars[offset++] = '{'; //// guidChars[37] = '}'; //// } //// else if(formatCh == 'P' || formatCh == 'p') //// { //// guidChars = new char[38]; //// guidChars[offset++] = '('; //// guidChars[37] = ')'; //// } //// else //// { //// throw new FormatException( Environment.GetResourceString( "Format_InvalidGuidFormatSpecification" ) ); //// } //// //// offset = HexsToChars( guidChars, offset, _a >> 24, _a >> 16 ); //// offset = HexsToChars( guidChars, offset, _a >> 8, _a ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _b >> 8, _b ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _c >> 8, _c ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _d, _e ); //// //// if(dash) guidChars[offset++] = '-'; //// //// offset = HexsToChars( guidChars, offset, _f, _g ); //// offset = HexsToChars( guidChars, offset, _h, _i ); //// offset = HexsToChars( guidChars, offset, _j, _k ); //// //// return new String( guidChars, 0, strLength ); //// } } }
// <copyright file="TurnBasedMultiplayerManager.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native.Cwrapper { using System; using System.Runtime.InteropServices; using System.Text; internal static class TurnBasedMultiplayerManager { internal delegate void TurnBasedMatchCallback( /* from(TurnBasedMultiplayerManager_TurnBasedMatchResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); internal delegate void MultiplayerStatusCallback( /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus arg0, /* from(void *) */ IntPtr arg1); internal delegate void TurnBasedMatchesCallback( /* from(TurnBasedMultiplayerManager_TurnBasedMatchesResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); internal delegate void MatchInboxUICallback( /* from(TurnBasedMultiplayerManager_MatchInboxUIResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); internal delegate void PlayerSelectUICallback( /* from(TurnBasedMultiplayerManager_PlayerSelectUIResponse_t) */ IntPtr arg0, /* from(void *) */ IntPtr arg1); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_ShowPlayerSelectUI( HandleRef self, /* from(uint32_t) */uint minimum_players, /* from(uint32_t) */uint maximum_players, [MarshalAs(UnmanagedType.I1)] /* from(bool) */ bool allow_automatch, /* from(TurnBasedMultiplayerManager_PlayerSelectUICallback_t) */PlayerSelectUICallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_CancelMatch( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_DismissMatch( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_ShowMatchInboxUI( HandleRef self, /* from(TurnBasedMultiplayerManager_MatchInboxUICallback_t) */MatchInboxUICallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_SynchronizeData( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_Rematch( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_DismissInvitation( HandleRef self, /* from(MultiplayerInvitation_t) */IntPtr invitation); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_FetchMatch( HandleRef self, /* from(char const *) */string match_id, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_DeclineInvitation( HandleRef self, /* from(MultiplayerInvitation_t) */IntPtr invitation); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_FinishMatchDuringMyTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(uint8_t const *) */byte[] match_data, /* from(size_t) */UIntPtr match_data_size, /* from(ParticipantResults_t) */IntPtr results, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_FetchMatches( HandleRef self, /* from(TurnBasedMultiplayerManager_TurnBasedMatchesCallback_t) */TurnBasedMatchesCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_CreateTurnBasedMatch( HandleRef self, /* from(TurnBasedMatchConfig_t) */IntPtr config, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_AcceptInvitation( HandleRef self, /* from(MultiplayerInvitation_t) */IntPtr invitation, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_TakeMyTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(uint8_t const *) */byte[] match_data, /* from(size_t) */UIntPtr match_data_size, /* from(ParticipantResults_t) */IntPtr results, /* from(MultiplayerParticipant_t) */IntPtr next_participant, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_ConfirmPendingCompletion( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_LeaveMatchDuringMyTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(MultiplayerParticipant_t) */IntPtr next_participant, /* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_LeaveMatchDuringTheirTurn( HandleRef self, /* from(TurnBasedMatch_t) */IntPtr match, /* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback, /* from(void *) */IntPtr callback_arg); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_TurnBasedMatchResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetMatch( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_TurnBasedMatchesResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(MultiplayerInvitation_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_GetElement( HandleRef self, /* from(size_t) */UIntPtr index); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_MatchInboxUIResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(UIStatus_t) */ CommonErrorStatus.UIStatus TurnBasedMultiplayerManager_MatchInboxUIResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_MatchInboxUIResponse_GetMatch( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern void TurnBasedMultiplayerManager_PlayerSelectUIResponse_Dispose( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(UIStatus_t) */ CommonErrorStatus.UIStatus TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetStatus( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetPlayerIds_Length( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetPlayerIds_GetElement( HandleRef self, /* from(size_t) */UIntPtr index, [In, Out] /* from(char *) */char[] out_arg, /* from(size_t) */UIntPtr out_size); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(uint32_t) */ uint TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetMinimumAutomatchingPlayers( HandleRef self); [DllImport(SymbolLocation.NativeSymbolLocation)] internal static extern /* from(uint32_t) */ uint TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetMaximumAutomatchingPlayers( HandleRef self); } } #endif // (UNITY_ANDROID || UNITY_IPHONE)
using System; using System.Collections; using System.Collections.Generic; namespace AppLimit.CloudComputing.SharpBox.Common.Net { public static class MimeMapping { private static readonly Hashtable ExtensionToMimeMappingTable = new Hashtable(200, StringComparer. CurrentCultureIgnoreCase); private static readonly IDictionary<string, IList<string>> MimeSynonyms = new Dictionary<string, IList<string>>(); static MimeMapping() { AddMimeMapping(".3dm", "x-world/x-3dmf"); AddMimeMapping(".3dmf", "x-world/x-3dmf"); AddMimeMapping(".a", "application/octet-stream"); AddMimeMapping(".aab", "application/x-authorware-bin"); AddMimeMapping(".aam", "application/x-authorware-map"); AddMimeMapping(".aas", "application/x-authorware-seg"); AddMimeMapping(".abc", "text/vnd.abc"); AddMimeMapping(".acgi", "text/html"); AddMimeMapping(".afl", "video/animaflex"); AddMimeMapping(".ai", "application/postscript"); AddMimeMapping(".aif", "audio/aiff"); AddMimeMapping(".aif", "audio/x-aiff"); AddMimeMapping(".aifc", "audio/aiff"); AddMimeMapping(".aifc", "audio/x-aiff"); AddMimeMapping(".aiff", "audio/aiff"); AddMimeMapping(".aiff", "audio/x-aiff"); AddMimeMapping(".aim", "application/x-aim"); AddMimeMapping(".aip", "text/x-audiosoft-intra"); AddMimeMapping(".ani", "application/x-navi-animation"); AddMimeMapping(".aos", "application/x-nokia-9000-communicator-add-on-software"); AddMimeMapping(".aps", "application/mime"); AddMimeMapping(".arc", "application/octet-stream"); AddMimeMapping(".arj", "application/arj"); AddMimeMapping(".arj", "application/octet-stream"); AddMimeMapping(".art", "image/x-jg"); AddMimeMapping(".asf", "video/x-ms-asf"); AddMimeMapping(".asm", "text/x-asm"); AddMimeMapping(".asp", "text/asp"); AddMimeMapping(".asx", "application/x-mplayer2"); AddMimeMapping(".asx", "video/x-ms-asf"); AddMimeMapping(".asx", "video/x-ms-asf-plugin"); AddMimeMapping(".au", "audio/basic"); AddMimeMapping(".au", "audio/x-au"); AddMimeMapping(".avi", "video/avi"); AddMimeMapping(".avi", "application/x-troff-msvideo"); AddMimeMapping(".avi", "video/msvideo"); AddMimeMapping(".avi", "video/x-msvideo"); AddMimeMapping(".avs", "video/avs-video"); AddMimeMapping(".bcpio", "application/x-bcpio"); AddMimeMapping(".bin", "application/octet-stream"); AddMimeMapping(".bin", "application/mac-binary"); AddMimeMapping(".bin", "application/macbinary"); AddMimeMapping(".bin", "application/x-binary"); AddMimeMapping(".bin", "application/x-macbinary"); AddMimeMapping(".bm", "image/bmp"); AddMimeMapping(".bmp", "image/bmp"); AddMimeMapping(".bmp", "image/x-windows-bmp"); AddMimeMapping(".bmp", "image/x-ms-bmp"); AddMimeMapping(".boo", "application/book"); AddMimeMapping(".book", "application/book"); AddMimeMapping(".boz", "application/x-bzip2"); AddMimeMapping(".bsh", "application/x-bsh"); AddMimeMapping(".bz", "application/x-bzip"); AddMimeMapping(".bz2", "application/x-bzip2"); AddMimeMapping(".c", "text/plain"); AddMimeMapping(".c", "text/x-c"); AddMimeMapping(".c++", "text/plain"); AddMimeMapping(".cat", "application/vnd.ms-pki.seccat"); AddMimeMapping(".cc", "text/plain"); AddMimeMapping(".cc", "text/x-c"); AddMimeMapping(".ccad", "application/clariscad"); AddMimeMapping(".cco", "application/x-cocoa"); AddMimeMapping(".cdf", "application/cdf"); AddMimeMapping(".cdf", "application/x-cdf"); AddMimeMapping(".cdf", "application/x-netcdf"); AddMimeMapping(".cer", "application/pkix-cert"); AddMimeMapping(".cer", "application/x-x509-ca-cert"); AddMimeMapping(".cha", "application/x-chat"); AddMimeMapping(".chat", "application/x-chat"); AddMimeMapping(".class", "application/java"); AddMimeMapping(".class", "application/java-byte-code"); AddMimeMapping(".class", "application/x-java-class"); AddMimeMapping(".com", "application/octet-stream"); AddMimeMapping(".com", "text/plain"); AddMimeMapping(".conf", "text/plain"); AddMimeMapping(".cpio", "application/x-cpio"); AddMimeMapping(".cpp", "text/x-c"); AddMimeMapping(".cpt", "application/mac-compactpro"); AddMimeMapping(".cpt", "application/x-compactpro"); AddMimeMapping(".cpt", "application/x-cpt"); AddMimeMapping(".crl", "application/pkcs-crl"); AddMimeMapping(".crl", "application/pkix-crl"); AddMimeMapping(".crt", "application/pkix-cert"); AddMimeMapping(".crt", "application/x-x509-ca-cert"); AddMimeMapping(".crt", "application/x-x509-user-cert"); AddMimeMapping(".csh", "application/x-csh"); AddMimeMapping(".csh", "text/x-script.csh"); AddMimeMapping(".css", "text/css"); AddMimeMapping(".css", "application/x-pointplus"); AddMimeMapping(".cxx", "text/plain"); AddMimeMapping(".dcr", "application/x-director"); AddMimeMapping(".deepv", "application/x-deepv"); AddMimeMapping(".def", "text/plain"); AddMimeMapping(".der", "application/x-x509-ca-cert"); AddMimeMapping(".dif", "video/x-dv"); AddMimeMapping(".dir", "application/x-director"); AddMimeMapping(".dll", "application/octet-stream"); AddMimeMapping(".dl", "video/dl"); AddMimeMapping(".dl", "video/x-dl"); AddMimeMapping(".doc", "application/msword"); AddMimeMapping(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); AddMimeMapping(".dot", "application/msword"); AddMimeMapping(".dp", "application/commonground"); AddMimeMapping(".drw", "application/drafting"); AddMimeMapping(".dump", "application/octet-stream"); AddMimeMapping(".dv", "video/x-dv"); AddMimeMapping(".dvi", "application/x-dvi"); AddMimeMapping(".dwf", "drawing/x-dwf (old)"); AddMimeMapping(".dwf", "model/vnd.dwf"); AddMimeMapping(".dwg", "application/acad"); AddMimeMapping(".dwg", "image/vnd.dwg"); AddMimeMapping(".dwg", "image/x-dwg"); AddMimeMapping(".dxf", "application/dxf"); AddMimeMapping(".dxf", "image/vnd.dwg"); AddMimeMapping(".dxf", "image/x-dwg"); AddMimeMapping(".dxr", "application/x-director"); AddMimeMapping(".el", "text/x-script.elisp"); AddMimeMapping(".elc", "application/x-bytecode.elisp (compiled elisp)"); AddMimeMapping(".elc", "application/x-elc"); AddMimeMapping(".env", "application/x-envoy"); AddMimeMapping(".eps", "application/postscript"); AddMimeMapping(".es", "application/x-esrehber"); AddMimeMapping(".etx", "text/x-setext"); AddMimeMapping(".evy", "application/envoy"); AddMimeMapping(".evy", "application/x-envoy"); AddMimeMapping(".exe", "application/octet-stream"); AddMimeMapping(".f", "text/plain"); AddMimeMapping(".f", "text/x-fortran"); AddMimeMapping(".f77", "text/x-fortran"); AddMimeMapping(".f90", "text/plain"); AddMimeMapping(".f90", "text/x-fortran"); AddMimeMapping(".fdf", "application/vnd.fdf"); AddMimeMapping(".fif", "application/fractals"); AddMimeMapping(".fif", "image/fif"); AddMimeMapping(".fli", "video/fli"); AddMimeMapping(".fli", "video/x-fli"); AddMimeMapping(".flo", "image/florian"); AddMimeMapping(".flx", "text/vnd.fmi.flexstor"); AddMimeMapping(".fmf", "video/x-atomic3d-feature"); AddMimeMapping(".for", "text/plain"); AddMimeMapping(".for", "text/x-fortran"); AddMimeMapping(".fpx", "image/vnd.fpx"); AddMimeMapping(".fpx", "image/vnd.net-fpx"); AddMimeMapping(".frl", "application/freeloader"); AddMimeMapping(".funk", "audio/make"); AddMimeMapping(".g", "text/plain"); AddMimeMapping(".g3", "image/g3fax"); AddMimeMapping(".gif", "image/gif"); AddMimeMapping(".gl", "video/gl"); AddMimeMapping(".gl", "video/x-gl"); AddMimeMapping(".gsd", "audio/x-gsm"); AddMimeMapping(".gsm", "audio/x-gsm"); AddMimeMapping(".gsp", "application/x-gsp"); AddMimeMapping(".gss", "application/x-gss"); AddMimeMapping(".gtar", "application/x-gtar"); AddMimeMapping(".gz", "application/x-gzip"); AddMimeMapping(".gz", "application/x-compressed"); AddMimeMapping(".gzip", "application/x-gzip"); AddMimeMapping(".gzip", "multipart/x-gzip"); AddMimeMapping(".h", "text/plain"); AddMimeMapping(".h", "text/x-h"); AddMimeMapping(".hdf", "application/x-hdf"); AddMimeMapping(".help", "application/x-helpfile"); AddMimeMapping(".hgl", "application/vnd.hp-hpgl"); AddMimeMapping(".hh", "text/plain"); AddMimeMapping(".hh", "text/x-h"); AddMimeMapping(".hlb", "text/x-script"); AddMimeMapping(".hlp", "application/hlp"); AddMimeMapping(".hlp", "application/x-helpfile"); AddMimeMapping(".hlp", "application/x-winhelp"); AddMimeMapping(".hpg", "application/vnd.hp-hpgl"); AddMimeMapping(".hpgl", "application/vnd.hp-hpgl"); AddMimeMapping(".hqx", "application/binhex"); AddMimeMapping(".hqx", "application/binhex4"); AddMimeMapping(".hqx", "application/mac-binhex"); AddMimeMapping(".hqx", "application/mac-binhex40"); AddMimeMapping(".hqx", "application/x-binhex40"); AddMimeMapping(".hqx", "application/x-mac-binhex40"); AddMimeMapping(".hta", "application/hta"); AddMimeMapping(".htc", "text/x-component"); AddMimeMapping(".htm", "text/html"); AddMimeMapping(".html", "text/html"); AddMimeMapping(".htmls", "text/html"); AddMimeMapping(".htt", "text/webviewhtml"); AddMimeMapping(".htx", "text/html"); AddMimeMapping(".ice", "x-conference/x-cooltalk"); AddMimeMapping(".ico", "image/x-icon"); AddMimeMapping(".idc", "text/plain"); AddMimeMapping(".ief", "image/ief"); AddMimeMapping(".iefs", "image/ief"); AddMimeMapping(".iges", "application/iges"); AddMimeMapping(".iges", "model/iges"); AddMimeMapping(".igs", "application/iges"); AddMimeMapping(".igs", "model/iges"); AddMimeMapping(".ima", "application/x-ima"); AddMimeMapping(".imap", "application/x-httpd-imap"); AddMimeMapping(".inf", "application/inf"); AddMimeMapping(".ins", "application/x-internett-signup"); AddMimeMapping(".ip", "application/x-ip2"); AddMimeMapping(".isu", "video/x-isvideo"); AddMimeMapping(".it", "audio/it"); AddMimeMapping(".iv", "application/x-inventor"); AddMimeMapping(".ivr", "i-world/i-vrml"); AddMimeMapping(".ivy", "application/x-livescreen"); AddMimeMapping(".jam", "audio/x-jam"); AddMimeMapping(".jav", "text/plain"); AddMimeMapping(".jav", "text/x-java-source"); AddMimeMapping(".java", "text/plain"); AddMimeMapping(".java", "text/x-java-source"); AddMimeMapping(".jcm", "application/x-java-commerce"); AddMimeMapping(".jfif", "image/jpeg"); AddMimeMapping(".jfif", "image/pjpeg"); AddMimeMapping(".jfif-tbnl", "image/jpeg"); AddMimeMapping(".jpeg", "image/jpeg"); AddMimeMapping(".jpe", "image/jpeg"); AddMimeMapping(".jpe", "image/pjpeg"); AddMimeMapping(".jpeg", "image/pjpeg"); AddMimeMapping(".jpg", "image/jpeg"); AddMimeMapping(".jpg", "image/pjpeg"); AddMimeMapping(".jps", "image/x-jps"); AddMimeMapping(".json", "application/json"); AddMimeMapping(".js", "text/javascript"); AddMimeMapping(".js", "application/javascript"); AddMimeMapping(".js", "application/x-javascript"); AddMimeMapping(".js", "application/ecmascript"); AddMimeMapping(".js", "text/ecmascript"); AddMimeMapping(".jut", "image/jutvision"); AddMimeMapping(".kar", "audio/midi"); AddMimeMapping(".kar", "music/x-karaoke"); AddMimeMapping(".ksh", "application/x-ksh"); AddMimeMapping(".ksh", "text/x-script.ksh"); AddMimeMapping(".la", "audio/nspaudio"); AddMimeMapping(".la", "audio/x-nspaudio"); AddMimeMapping(".lam", "audio/x-liveaudio"); AddMimeMapping(".latex", "application/x-latex"); AddMimeMapping(".less", "text/css"); AddMimeMapping(".lha", "application/lha"); AddMimeMapping(".lha", "application/octet-stream"); AddMimeMapping(".lha", "application/x-lha"); AddMimeMapping(".lhx", "application/octet-stream"); AddMimeMapping(".list", "text/plain"); AddMimeMapping(".lma", "audio/nspaudio"); AddMimeMapping(".lma", "audio/x-nspaudio"); AddMimeMapping(".log", "text/plain"); AddMimeMapping(".lsp", "application/x-lisp"); AddMimeMapping(".lsp", "text/x-script.lisp"); AddMimeMapping(".lst", "text/plain"); AddMimeMapping(".lsx", "text/x-la-asf"); AddMimeMapping(".ltx", "application/x-latex"); AddMimeMapping(".lzh", "application/octet-stream"); AddMimeMapping(".lzh", "application/x-lzh"); AddMimeMapping(".lzx", "application/lzx"); AddMimeMapping(".lzx", "application/octet-stream"); AddMimeMapping(".lzx", "application/x-lzx"); AddMimeMapping(".m", "text/plain"); AddMimeMapping(".m", "text/x-m"); AddMimeMapping(".m1v", "video/mpeg"); AddMimeMapping(".m2a", "audio/mpeg"); AddMimeMapping(".m2v", "video/mpeg"); AddMimeMapping(".m3u", "audio/x-mpequrl"); AddMimeMapping(".man", "application/x-troff-man"); AddMimeMapping(".map", "application/x-navimap"); AddMimeMapping(".mar", "text/plain"); AddMimeMapping(".mbd", "application/mbedlet"); AddMimeMapping(".mc$", "application/x-magic-cap-package-1.0"); AddMimeMapping(".mcd", "application/mcad"); AddMimeMapping(".mcd", "application/x-mathcad"); AddMimeMapping(".mcf", "image/vasa"); AddMimeMapping(".mcf", "text/mcf"); AddMimeMapping(".mcp", "application/netmc"); AddMimeMapping(".me", "application/x-troff-me"); AddMimeMapping(".mht", "message/rfc822"); AddMimeMapping(".mhtml", "message/rfc822"); AddMimeMapping(".mid", "application/x-midi"); AddMimeMapping(".mid", "audio/midi"); AddMimeMapping(".mid", "audio/x-mid"); AddMimeMapping(".mid", "audio/x-midi"); AddMimeMapping(".mid", "music/crescendo"); AddMimeMapping(".mid", "x-music/x-midi"); AddMimeMapping(".midi", "application/x-midi"); AddMimeMapping(".midi", "audio/midi"); AddMimeMapping(".midi", "audio/x-mid"); AddMimeMapping(".midi", "audio/x-midi"); AddMimeMapping(".midi", "music/crescendo"); AddMimeMapping(".midi", "x-music/x-midi"); AddMimeMapping(".mif", "application/x-frame"); AddMimeMapping(".mif", "application/x-mif"); AddMimeMapping(".mime", "message/rfc822"); AddMimeMapping(".mime", "www/mime"); AddMimeMapping(".mjf", "audio/x-vnd.audioexplosion.mjuicemediafile"); AddMimeMapping(".mjpg", "video/x-motion-jpeg"); AddMimeMapping(".mm", "application/base64"); AddMimeMapping(".mm", "application/x-meme"); AddMimeMapping(".mme", "application/base64"); AddMimeMapping(".mod", "audio/mod"); AddMimeMapping(".mod", "audio/x-mod"); AddMimeMapping(".moov", "video/quicktime"); AddMimeMapping(".mov", "video/quicktime"); AddMimeMapping(".movie", "video/x-sgi-movie"); AddMimeMapping(".mp2", "audio/mpeg"); AddMimeMapping(".mp2", "audio/x-mpeg"); AddMimeMapping(".mp2", "video/mpeg"); AddMimeMapping(".mp2", "video/x-mpeg"); AddMimeMapping(".mp2", "video/x-mpeq2a"); AddMimeMapping(".mp3", "audio/mpeg3"); AddMimeMapping(".mp3", "audio/x-mpeg-3"); AddMimeMapping(".mp3", "video/mpeg"); AddMimeMapping(".mp3", "video/x-mpeg"); AddMimeMapping(".mpa", "audio/mpeg"); AddMimeMapping(".mpa", "video/mpeg"); AddMimeMapping(".mpc", "application/x-project"); AddMimeMapping(".mpe", "video/mpeg"); AddMimeMapping(".mpeg", "video/mpeg"); AddMimeMapping(".mpg", "audio/mpeg"); AddMimeMapping(".mpg", "video/mpeg"); AddMimeMapping(".mpga", "audio/mpeg"); AddMimeMapping(".mpp", "application/vnd.ms-project"); AddMimeMapping(".mpt", "application/x-project"); AddMimeMapping(".mpv", "application/x-project"); AddMimeMapping(".mpx", "application/x-project"); AddMimeMapping(".mrc", "application/marc"); AddMimeMapping(".ms", "application/x-troff-ms"); AddMimeMapping(".mv", "video/x-sgi-movie"); AddMimeMapping(".my", "audio/make"); AddMimeMapping(".mzz", "application/x-vnd.audioexplosion.mzz"); AddMimeMapping(".nap", "image/naplps"); AddMimeMapping(".naplps", "image/naplps"); AddMimeMapping(".nc", "application/x-netcdf"); AddMimeMapping(".ncm", "application/vnd.nokia.configuration-message"); AddMimeMapping(".nif", "image/x-niff"); AddMimeMapping(".niff", "image/x-niff"); AddMimeMapping(".nix", "application/x-mix-transfer"); AddMimeMapping(".nsc", "application/x-conference"); AddMimeMapping(".nvd", "application/x-navidoc"); AddMimeMapping(".o", "application/octet-stream"); AddMimeMapping(".oda", "application/oda"); AddMimeMapping(".omc", "application/x-omc"); AddMimeMapping(".omcd", "application/x-omcdatamaker"); AddMimeMapping(".omcr", "application/x-omcregerator"); AddMimeMapping(".p", "text/x-pascal"); AddMimeMapping(".p10", "application/pkcs10"); AddMimeMapping(".p10", "application/x-pkcs10"); AddMimeMapping(".p12", "application/pkcs-12"); AddMimeMapping(".p12", "application/x-pkcs12"); AddMimeMapping(".p7a", "application/x-pkcs7-signature"); AddMimeMapping(".p7c", "application/pkcs7-mime"); AddMimeMapping(".p7c", "application/x-pkcs7-mime"); AddMimeMapping(".p7m", "application/pkcs7-mime"); AddMimeMapping(".p7m", "application/x-pkcs7-mime"); AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp"); AddMimeMapping(".p7s", "application/pkcs7-signature"); AddMimeMapping(".part", "application/pro_eng"); AddMimeMapping(".pas", "text/pascal"); AddMimeMapping(".pbm", "image/x-portable-bitmap"); AddMimeMapping(".pcl", "application/vnd.hp-pcl"); AddMimeMapping(".pcl", "application/x-pcl"); AddMimeMapping(".pct", "image/x-pict"); AddMimeMapping(".pcx", "image/x-pcx"); AddMimeMapping(".pdb", "chemical/x-pdb"); AddMimeMapping(".pdf", "application/pdf"); AddMimeMapping(".pfunk", "audio/make"); AddMimeMapping(".pfunk", "audio/make.my.funk"); AddMimeMapping(".pgm", "image/x-portable-graymap"); AddMimeMapping(".pgm", "image/x-portable-greymap"); AddMimeMapping(".pic", "image/pict"); AddMimeMapping(".pict", "image/pict"); AddMimeMapping(".pkg", "application/x-newton-compatible-pkg"); AddMimeMapping(".pko", "application/vnd.ms-pki.pko"); AddMimeMapping(".pl", "text/plain"); AddMimeMapping(".pl", "text/x-script.perl"); AddMimeMapping(".plx", "application/x-pixclscript"); AddMimeMapping(".pm", "image/x-xpixmap"); AddMimeMapping(".pm", "text/x-script.perl-module"); AddMimeMapping(".pm4", "application/x-pagemaker"); AddMimeMapping(".pm5", "application/x-pagemaker"); AddMimeMapping(".png", "image/png"); AddMimeMapping(".pnm", "application/x-portable-anymap"); AddMimeMapping(".pnm", "image/x-portable-anymap"); AddMimeMapping(".pot", "application/mspowerpoint"); AddMimeMapping(".pot", "application/vnd.ms-powerpoint"); AddMimeMapping(".pov", "model/x-pov"); AddMimeMapping(".ppa", "application/vnd.ms-powerpoint"); AddMimeMapping(".ppm", "image/x-portable-pixmap"); AddMimeMapping(".pps", "application/mspowerpoint"); AddMimeMapping(".pps", "application/vnd.ms-powerpoint"); AddMimeMapping(".ppt", "application/vnd.ms-powerpoint"); AddMimeMapping(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); AddMimeMapping(".ppz", "application/mspowerpoint"); AddMimeMapping(".pre", "application/x-freelance"); AddMimeMapping(".prt", "application/pro_eng"); AddMimeMapping(".ps", "application/postscript"); AddMimeMapping(".psd", "application/octet-stream"); AddMimeMapping(".pvu", "paleovu/x-pv"); AddMimeMapping(".pwz", "application/vnd.ms-powerpoint"); AddMimeMapping(".py", "text/x-script.phyton"); AddMimeMapping(".pyc", "applicaiton/x-bytecode.python"); AddMimeMapping(".qcp", "audio/vnd.qcelp"); AddMimeMapping(".qd3", "x-world/x-3dmf"); AddMimeMapping(".qd3d", "x-world/x-3dmf"); AddMimeMapping(".qif", "image/x-quicktime"); AddMimeMapping(".qt", "video/quicktime"); AddMimeMapping(".qtc", "video/x-qtc"); AddMimeMapping(".qti", "image/x-quicktime"); AddMimeMapping(".qtif", "image/x-quicktime"); AddMimeMapping(".ra", "audio/x-pn-realaudio"); AddMimeMapping(".ra", "audio/x-pn-realaudio-plugin"); AddMimeMapping(".ra", "audio/x-realaudio"); AddMimeMapping(".ram", "audio/x-pn-realaudio"); AddMimeMapping(".ras", "application/x-cmu-raster"); AddMimeMapping(".ras", "image/cmu-raster"); AddMimeMapping(".ras", "image/x-cmu-raster"); AddMimeMapping(".rast", "image/cmu-raster"); AddMimeMapping(".rexx", "text/x-script.rexx"); AddMimeMapping(".rf", "image/vnd.rn-realflash"); AddMimeMapping(".rgb", "image/x-rgb"); AddMimeMapping(".rm", "application/vnd.rn-realmedia"); AddMimeMapping(".rm", "audio/x-pn-realaudio"); AddMimeMapping(".rmi", "audio/mid"); AddMimeMapping(".rmm", "audio/x-pn-realaudio"); AddMimeMapping(".rmp", "audio/x-pn-realaudio"); AddMimeMapping(".rmp", "audio/x-pn-realaudio-plugin"); AddMimeMapping(".rng", "application/ringing-tones"); AddMimeMapping(".rng", "application/vnd.nokia.ringing-tone"); AddMimeMapping(".rnx", "application/vnd.rn-realplayer"); AddMimeMapping(".roff", "application/x-troff"); AddMimeMapping(".rp", "image/vnd.rn-realpix"); AddMimeMapping(".rpm", "audio/x-pn-realaudio-plugin"); AddMimeMapping(".rt", "text/richtext"); AddMimeMapping(".rt", "text/vnd.rn-realtext"); AddMimeMapping(".rtf", "application/rtf"); AddMimeMapping(".rtf", "application/x-rtf"); AddMimeMapping(".rtf", "text/richtext"); AddMimeMapping(".rtx", "application/rtf"); AddMimeMapping(".rtx", "text/richtext"); AddMimeMapping(".rv", "video/vnd.rn-realvideo"); AddMimeMapping(".s", "text/x-asm"); AddMimeMapping(".s3m", "audio/s3m"); AddMimeMapping(".saveme", "application/octet-stream"); AddMimeMapping(".sbk", "application/x-tbook"); AddMimeMapping(".scm", "application/x-lotusscreencam"); AddMimeMapping(".scm", "text/x-script.guile"); AddMimeMapping(".scm", "text/x-script.scheme"); AddMimeMapping(".scm", "video/x-scm"); AddMimeMapping(".sdml", "text/plain"); AddMimeMapping(".sdp", "application/sdp"); AddMimeMapping(".sdp", "application/x-sdp"); AddMimeMapping(".sdr", "application/sounder"); AddMimeMapping(".sea", "application/sea"); AddMimeMapping(".sea", "application/x-sea"); AddMimeMapping(".set", "application/set"); AddMimeMapping(".sgm", "text/sgml"); AddMimeMapping(".sgm", "text/x-sgml"); AddMimeMapping(".sgml", "text/sgml"); AddMimeMapping(".sgml", "text/x-sgml"); AddMimeMapping(".sh", "application/x-bsh"); AddMimeMapping(".sh", "application/x-sh"); AddMimeMapping(".sh", "application/x-shar"); AddMimeMapping(".sh", "text/x-script.sh"); AddMimeMapping(".shar", "application/x-bsh"); AddMimeMapping(".shar", "application/x-shar"); AddMimeMapping(".shtml", "text/html"); AddMimeMapping(".shtml", "text/x-server-parsed-html"); AddMimeMapping(".sid", "audio/x-psid"); AddMimeMapping(".sit", "application/x-sit"); AddMimeMapping(".sit", "application/x-stuffit"); AddMimeMapping(".skd", "application/x-koan"); AddMimeMapping(".skm", "application/x-koan"); AddMimeMapping(".skp", "application/x-koan"); AddMimeMapping(".skt", "application/x-koan"); AddMimeMapping(".sl", "application/x-seelogo"); AddMimeMapping(".smi", "application/smil"); AddMimeMapping(".smil", "application/smil"); AddMimeMapping(".snd", "audio/basic"); AddMimeMapping(".snd", "audio/x-adpcm"); AddMimeMapping(".sol", "application/solids"); AddMimeMapping(".spc", "application/x-pkcs7-certificates"); AddMimeMapping(".spc", "text/x-speech"); AddMimeMapping(".spl", "application/futuresplash"); AddMimeMapping(".spr", "application/x-sprite"); AddMimeMapping(".sprite", "application/x-sprite"); AddMimeMapping(".src", "application/x-wais-source"); AddMimeMapping(".ssi", "text/x-server-parsed-html"); AddMimeMapping(".ssm", "application/streamingmedia"); AddMimeMapping(".sst", "application/vnd.ms-pki.certstore"); AddMimeMapping(".step", "application/step"); AddMimeMapping(".stl", "application/sla"); AddMimeMapping(".stl", "application/vnd.ms-pki.stl"); AddMimeMapping(".stl", "application/x-navistyle"); AddMimeMapping(".stp", "application/step"); AddMimeMapping(".sv4cpio", "application/x-sv4cpio"); AddMimeMapping(".sv4crc", "application/x-sv4crc"); AddMimeMapping(".svf", "image/vnd.dwg"); AddMimeMapping(".svf", "image/x-dwg"); AddMimeMapping(".svr", "application/x-world"); AddMimeMapping(".svr", "x-world/x-svr"); AddMimeMapping(".swf", "application/x-shockwave-flash"); AddMimeMapping(".t", "application/x-troff"); AddMimeMapping(".talk", "text/x-speech"); AddMimeMapping(".tar", "application/x-tar"); AddMimeMapping(".tbk", "application/toolbook"); AddMimeMapping(".tbk", "application/x-tbook"); AddMimeMapping(".tcl", "application/x-tcl"); AddMimeMapping(".tcl", "text/x-script.tcl"); AddMimeMapping(".tcsh", "text/x-script.tcsh"); AddMimeMapping(".tex", "application/x-tex"); AddMimeMapping(".texi", "application/x-texinfo"); AddMimeMapping(".texinfo", "application/x-texinfo"); AddMimeMapping(".text", "application/plain"); AddMimeMapping(".text", "text/plain"); AddMimeMapping(".tgz", "application/x-compressed"); AddMimeMapping(".tgz", "application/gnutar"); AddMimeMapping(".tif", "image/tiff"); AddMimeMapping(".tif", "image/x-tiff"); AddMimeMapping(".tiff", "image/tiff"); AddMimeMapping(".tiff", "image/x-tiff"); AddMimeMapping(".tr", "application/x-troff"); AddMimeMapping(".tsi", "audio/tsp-audio"); AddMimeMapping(".tsp", "application/dsptype"); AddMimeMapping(".tsp", "audio/tsplayer"); AddMimeMapping(".tsv", "text/tab-separated-values"); AddMimeMapping(".turbot", "image/florian"); AddMimeMapping(".txt", "text/plain"); AddMimeMapping(".uil", "text/x-uil"); AddMimeMapping(".uni", "text/uri-list"); AddMimeMapping(".unis", "text/uri-list"); AddMimeMapping(".unv", "application/i-deas"); AddMimeMapping(".uri", "text/uri-list"); AddMimeMapping(".uris", "text/uri-list"); AddMimeMapping(".ustar", "application/x-ustar"); AddMimeMapping(".ustar", "multipart/x-ustar"); AddMimeMapping(".uu", "application/octet-stream"); AddMimeMapping(".uu", "text/x-uuencode"); AddMimeMapping(".uue", "text/x-uuencode"); AddMimeMapping(".vcd", "application/x-cdlink"); AddMimeMapping(".vcs", "text/x-vcalendar"); AddMimeMapping(".vda", "application/vda"); AddMimeMapping(".vdo", "video/vdo"); AddMimeMapping(".vew", "application/groupwise"); AddMimeMapping(".viv", "video/vivo"); AddMimeMapping(".viv", "video/vnd.vivo"); AddMimeMapping(".vivo", "video/vivo"); AddMimeMapping(".vivo", "video/vnd.vivo"); AddMimeMapping(".vmd", "application/vocaltec-media-desc"); AddMimeMapping(".vmf", "application/vocaltec-media-file"); AddMimeMapping(".voc", "audio/voc"); AddMimeMapping(".voc", "audio/x-voc"); AddMimeMapping(".vos", "video/vosaic"); AddMimeMapping(".vox", "audio/voxware"); AddMimeMapping(".vqe", "audio/x-twinvq-plugin"); AddMimeMapping(".vqf", "audio/x-twinvq"); AddMimeMapping(".vql", "audio/x-twinvq-plugin"); AddMimeMapping(".vrml", "application/x-vrml"); AddMimeMapping(".vrml", "model/vrml"); AddMimeMapping(".vrml", "x-world/x-vrml"); AddMimeMapping(".vrt", "x-world/x-vrt"); AddMimeMapping(".vsd", "application/x-visio"); AddMimeMapping(".vst", "application/x-visio"); AddMimeMapping(".vsw", "application/x-visio"); AddMimeMapping(".w60", "application/wordperfect6.0"); AddMimeMapping(".w61", "application/wordperfect6.1"); AddMimeMapping(".w6w", "application/msword"); AddMimeMapping(".wav", "audio/wav"); AddMimeMapping(".wav", "audio/x-wav"); AddMimeMapping(".wb1", "application/x-qpro"); AddMimeMapping(".wbmp", "image/vnd.wap.wbmp"); AddMimeMapping(".web", "application/vnd.xara"); AddMimeMapping(".wiz", "application/msword"); AddMimeMapping(".wk1", "application/x-123"); AddMimeMapping(".wmf", "windows/metafile"); AddMimeMapping(".wml", "text/vnd.wap.wml"); AddMimeMapping(".wmlc", "application/vnd.wap.wmlc"); AddMimeMapping(".wmls", "text/vnd.wap.wmlscript"); AddMimeMapping(".wmlsc", "application/vnd.wap.wmlscriptc"); AddMimeMapping(".word", "application/msword"); AddMimeMapping(".wp", "application/wordperfect"); AddMimeMapping(".wp5", "application/wordperfect"); AddMimeMapping(".wp5", "application/wordperfect6.0"); AddMimeMapping(".wp6", "application/wordperfect"); AddMimeMapping(".wpd", "application/wordperfect"); AddMimeMapping(".wpd", "application/x-wpwin"); AddMimeMapping(".wq1", "application/x-lotus"); AddMimeMapping(".wri", "application/mswrite"); AddMimeMapping(".wri", "application/x-wri"); AddMimeMapping(".wrl", "application/x-world"); AddMimeMapping(".wrl", "model/vrml"); AddMimeMapping(".wrl", "x-world/x-vrml"); AddMimeMapping(".wrz", "model/vrml"); AddMimeMapping(".wrz", "x-world/x-vrml"); AddMimeMapping(".wsc", "text/scriplet"); AddMimeMapping(".wsrc", "application/x-wais-source"); AddMimeMapping(".wtk", "application/x-wintalk"); AddMimeMapping(".xbm", "image/x-xbitmap"); AddMimeMapping(".xbm", "image/x-xbm"); AddMimeMapping(".xbm", "image/xbm"); AddMimeMapping(".xdr", "video/x-amt-demorun"); AddMimeMapping(".xgz", "xgl/drawing"); AddMimeMapping(".xif", "image/vnd.xiff"); AddMimeMapping(".xl", "application/excel"); AddMimeMapping(".xla", "application/excel"); AddMimeMapping(".xla", "application/x-excel"); AddMimeMapping(".xla", "application/x-msexcel"); AddMimeMapping(".xlb", "application/excel"); AddMimeMapping(".xlb", "application/vnd.ms-excel"); AddMimeMapping(".xlb", "application/x-excel"); AddMimeMapping(".xlc", "application/excel"); AddMimeMapping(".xlc", "application/vnd.ms-excel"); AddMimeMapping(".xlc", "application/x-excel"); AddMimeMapping(".xld", "application/excel"); AddMimeMapping(".xld", "application/x-excel"); AddMimeMapping(".xlk", "application/excel"); AddMimeMapping(".xlk", "application/x-excel"); AddMimeMapping(".xll", "application/excel"); AddMimeMapping(".xll", "application/vnd.ms-excel"); AddMimeMapping(".xll", "application/x-excel"); AddMimeMapping(".xlm", "application/excel"); AddMimeMapping(".xlm", "application/vnd.ms-excel"); AddMimeMapping(".xlm", "application/x-excel"); AddMimeMapping(".xls", "application/vnd.ms-excel"); AddMimeMapping(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); AddMimeMapping(".xlt", "application/excel"); AddMimeMapping(".xlt", "application/x-excel"); AddMimeMapping(".xlv", "application/excel"); AddMimeMapping(".xlv", "application/x-excel"); AddMimeMapping(".xlw", "application/excel"); AddMimeMapping(".xlw", "application/vnd.ms-excel"); AddMimeMapping(".xlw", "application/x-excel"); AddMimeMapping(".xlw", "application/x-msexcel"); AddMimeMapping(".xm", "audio/xm"); AddMimeMapping(".xml", "application/xml"); AddMimeMapping(".xml", "text/xml"); AddMimeMapping(".xmz", "xgl/movie"); AddMimeMapping(".xpix", "application/x-vnd.ls-xpix"); AddMimeMapping(".xpm", "image/x-xpixmap"); AddMimeMapping(".xpm", "image/xpm"); AddMimeMapping(".x-png", "image/png"); AddMimeMapping(".xsr", "video/x-amt-showrun"); AddMimeMapping(".xwd", "image/x-xwd"); AddMimeMapping(".xwd", "image/x-xwindowdump"); AddMimeMapping(".xyz", "chemical/x-pdb"); AddMimeMapping(".z", "application/x-compress"); AddMimeMapping(".z", "application/x-compressed"); AddMimeMapping(".zip", "application/zip"); AddMimeMapping(".zip", "application/x-compressed"); AddMimeMapping(".zip", "application/x-zip-compressed"); AddMimeMapping(".zip", "multipart/x-zip"); AddMimeMapping(".zoo", "application/octet-stream"); AddMimeMapping(".zsh", "text/x-script.zsh"); AddMimeMapping(".323", "text/h323"); AddMimeMapping(".asx", "video/x-ms-asf"); AddMimeMapping(".acx", "application/internet-property-stream"); AddMimeMapping(".ai", "application/postscript"); AddMimeMapping(".aif", "audio/x-aiff"); AddMimeMapping(".aiff", "audio/aiff"); AddMimeMapping(".axs", "application/olescript"); AddMimeMapping(".aifc", "audio/aiff"); AddMimeMapping(".asr", "video/x-ms-asf"); AddMimeMapping(".avi", "video/x-msvideo"); AddMimeMapping(".asf", "video/x-ms-asf"); AddMimeMapping(".au", "audio/basic"); AddMimeMapping(".application", "application/x-ms-application"); AddMimeMapping(".bin", "application/octet-stream"); AddMimeMapping(".bas", "text/plain"); AddMimeMapping(".bcpio", "application/x-bcpio"); AddMimeMapping(".bmp", "image/bmp"); AddMimeMapping(".cdf", "application/x-cdf"); AddMimeMapping(".cat", "application/vndms-pkiseccat"); AddMimeMapping(".crt", "application/x-x509-ca-cert"); AddMimeMapping(".c", "text/plain"); AddMimeMapping(".css", "text/css"); AddMimeMapping(".cer", "application/x-x509-ca-cert"); AddMimeMapping(".crl", "application/pkix-crl"); AddMimeMapping(".cmx", "image/x-cmx"); AddMimeMapping(".csh", "application/x-csh"); AddMimeMapping(".cod", "image/cis-cod"); AddMimeMapping(".cpio", "application/x-cpio"); AddMimeMapping(".clp", "application/x-msclip"); AddMimeMapping(".crd", "application/x-mscardfile"); AddMimeMapping(".deploy", "application/octet-stream"); AddMimeMapping(".dll", "application/x-msdownload"); AddMimeMapping(".dot", "application/msword"); AddMimeMapping(".doc", "application/msword"); AddMimeMapping(".dvi", "application/x-dvi"); AddMimeMapping(".dir", "application/x-director"); AddMimeMapping(".dxr", "application/x-director"); AddMimeMapping(".der", "application/x-x509-ca-cert"); AddMimeMapping(".dib", "image/bmp"); AddMimeMapping(".dcr", "application/x-director"); AddMimeMapping(".disco", "text/xml"); AddMimeMapping(".exe", "application/octet-stream"); AddMimeMapping(".etx", "text/x-setext"); AddMimeMapping(".evy", "application/envoy"); AddMimeMapping(".eml", "message/rfc822"); AddMimeMapping(".eps", "application/postscript"); AddMimeMapping(".flr", "x-world/x-vrml"); AddMimeMapping(".fif", "application/fractals"); AddMimeMapping(".gtar", "application/x-gtar"); AddMimeMapping(".gif", "image/gif"); AddMimeMapping(".gz", "application/x-gzip"); AddMimeMapping(".hta", "application/hta"); AddMimeMapping(".htc", "text/x-component"); AddMimeMapping(".htt", "text/webviewhtml"); AddMimeMapping(".h", "text/plain"); AddMimeMapping(".hdf", "application/x-hdf"); AddMimeMapping(".hlp", "application/winhlp"); AddMimeMapping(".html", "text/html"); AddMimeMapping(".htm", "text/html"); AddMimeMapping(".hqx", "application/mac-binhex40"); AddMimeMapping(".isp", "application/x-internet-signup"); AddMimeMapping(".iii", "application/x-iphone"); AddMimeMapping(".ief", "image/ief"); AddMimeMapping(".ivf", "video/x-ivf"); AddMimeMapping(".ins", "application/x-internet-signup"); AddMimeMapping(".ico", "image/x-icon"); AddMimeMapping(".jpg", "image/jpeg"); AddMimeMapping(".jfif", "image/pjpeg"); AddMimeMapping(".jpe", "image/jpeg"); AddMimeMapping(".jpeg", "image/jpeg"); AddMimeMapping(".png", "image/png"); AddMimeMapping(".js", "application/x-javascript"); AddMimeMapping(".lsx", "video/x-la-asf"); AddMimeMapping(".latex", "application/x-latex"); AddMimeMapping(".lsf", "video/x-la-asf"); AddMimeMapping(".manifest", "application/x-ms-manifest"); AddMimeMapping(".mhtml", "message/rfc822"); AddMimeMapping(".mny", "application/x-msmoney"); AddMimeMapping(".mht", "message/rfc822"); AddMimeMapping(".mid", "audio/mid"); AddMimeMapping(".mpv2", "video/mpeg"); AddMimeMapping(".man", "application/x-troff-man"); AddMimeMapping(".mvb", "application/x-msmediaview"); AddMimeMapping(".mpeg", "video/mpeg"); AddMimeMapping(".m3u", "audio/x-mpegurl"); AddMimeMapping(".mdb", "application/x-msaccess"); AddMimeMapping(".mpp", "application/vnd.ms-project"); AddMimeMapping(".m1v", "video/mpeg"); AddMimeMapping(".mpa", "video/mpeg"); AddMimeMapping(".me", "application/x-troff-me"); AddMimeMapping(".m13", "application/x-msmediaview"); AddMimeMapping(".movie", "video/x-sgi-movie"); AddMimeMapping(".m14", "application/x-msmediaview"); AddMimeMapping(".mpe", "video/mpeg"); AddMimeMapping(".mp2", "video/mpeg"); AddMimeMapping(".mov", "video/quicktime"); AddMimeMapping(".mp3", "audio/mpeg"); AddMimeMapping(".mpg", "video/mpeg"); AddMimeMapping(".ms", "application/x-troff-ms"); AddMimeMapping(".nc", "application/x-netcdf"); AddMimeMapping(".nws", "message/rfc822"); AddMimeMapping(".oda", "application/oda"); AddMimeMapping(".ods", "application/oleobject"); AddMimeMapping(".pmc", "application/x-perfmon"); AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp"); AddMimeMapping(".p7b", "application/x-pkcs7-certificates"); AddMimeMapping(".p7s", "application/pkcs7-signature"); AddMimeMapping(".pmw", "application/x-perfmon"); AddMimeMapping(".ps", "application/postscript"); AddMimeMapping(".p7c", "application/pkcs7-mime"); AddMimeMapping(".pbm", "image/x-portable-bitmap"); AddMimeMapping(".ppm", "image/x-portable-pixmap"); AddMimeMapping(".pub", "application/x-mspublisher"); AddMimeMapping(".pnm", "image/x-portable-anymap"); AddMimeMapping(".pml", "application/x-perfmon"); AddMimeMapping(".p10", "application/pkcs10"); AddMimeMapping(".pfx", "application/x-pkcs12"); AddMimeMapping(".p12", "application/x-pkcs12"); AddMimeMapping(".pdf", "application/pdf"); AddMimeMapping(".pps", "application/vnd.ms-powerpoint"); AddMimeMapping(".p7m", "application/pkcs7-mime"); AddMimeMapping(".pko", "application/vndms-pkipko"); AddMimeMapping(".pmr", "application/x-perfmon"); AddMimeMapping(".pma", "application/x-perfmon"); AddMimeMapping(".pot", "application/vnd.ms-powerpoint"); AddMimeMapping(".prf", "application/pics-rules"); AddMimeMapping(".pgm", "image/x-portable-graymap"); AddMimeMapping(".qt", "video/quicktime"); AddMimeMapping(".ra", "audio/x-pn-realaudio"); AddMimeMapping(".rgb", "image/x-rgb"); AddMimeMapping(".ram", "audio/x-pn-realaudio"); AddMimeMapping(".rmi", "audio/mid"); AddMimeMapping(".ras", "image/x-cmu-raster"); AddMimeMapping(".roff", "application/x-troff"); AddMimeMapping(".rtf", "application/rtf"); AddMimeMapping(".rtx", "text/richtext"); AddMimeMapping(".sv4crc", "application/x-sv4crc"); AddMimeMapping(".spc", "application/x-pkcs7-certificates"); AddMimeMapping(".setreg", "application/set-registration-initiation"); AddMimeMapping(".snd", "audio/basic"); AddMimeMapping(".stl", "application/vndms-pkistl"); AddMimeMapping(".setpay", "application/set-payment-initiation"); AddMimeMapping(".stm", "text/html"); AddMimeMapping(".shar", "application/x-shar"); AddMimeMapping(".sh", "application/x-sh"); AddMimeMapping(".sit", "application/x-stuffit"); AddMimeMapping(".spl", "application/futuresplash"); AddMimeMapping(".sct", "text/scriptlet"); AddMimeMapping(".scd", "application/x-msschedule"); AddMimeMapping(".sst", "application/vndms-pkicertstore"); AddMimeMapping(".src", "application/x-wais-source"); AddMimeMapping(".sv4cpio", "application/x-sv4cpio"); AddMimeMapping(".tex", "application/x-tex"); AddMimeMapping(".tgz", "application/x-compressed"); AddMimeMapping(".t", "application/x-troff"); AddMimeMapping(".tar", "application/x-tar"); AddMimeMapping(".tr", "application/x-troff"); AddMimeMapping(".tif", "image/tiff"); AddMimeMapping(".txt", "text/plain"); AddMimeMapping(".texinfo", "application/x-texinfo"); AddMimeMapping(".trm", "application/x-msterminal"); AddMimeMapping(".tiff", "image/tiff"); AddMimeMapping(".tcl", "application/x-tcl"); AddMimeMapping(".texi", "application/x-texinfo"); AddMimeMapping(".tsv", "text/tab-separated-values"); AddMimeMapping(".ustar", "application/x-ustar"); AddMimeMapping(".uls", "text/iuls"); AddMimeMapping(".vcf", "text/x-vcard"); AddMimeMapping(".wps", "application/vnd.ms-works"); AddMimeMapping(".wav", "audio/wav"); AddMimeMapping(".wrz", "x-world/x-vrml"); AddMimeMapping(".wri", "application/x-mswrite"); AddMimeMapping(".wks", "application/vnd.ms-works"); AddMimeMapping(".wmf", "application/x-msmetafile"); AddMimeMapping(".wcm", "application/vnd.ms-works"); AddMimeMapping(".wrl", "x-world/x-vrml"); AddMimeMapping(".wdb", "application/vnd.ms-works"); AddMimeMapping(".wsdl", "text/xml"); AddMimeMapping(".xml", "text/xml"); AddMimeMapping(".xlm", "application/vnd.ms-excel"); AddMimeMapping(".xaf", "x-world/x-vrml"); AddMimeMapping(".xla", "application/vnd.ms-excel"); AddMimeMapping(".xof", "x-world/x-vrml"); AddMimeMapping(".xlt", "application/vnd.ms-excel"); AddMimeMapping(".xlc", "application/vnd.ms-excel"); AddMimeMapping(".xsl", "text/xml"); AddMimeMapping(".xbm", "image/x-xbitmap"); AddMimeMapping(".xlw", "application/vnd.ms-excel"); AddMimeMapping(".xpm", "image/x-xpixmap"); AddMimeMapping(".xwd", "image/x-xwindowdump"); AddMimeMapping(".xsd", "text/xml"); AddMimeMapping(".z", "application/x-compress"); AddMimeMapping(".zip", "application/x-zip-compressed"); AddMimeSynonym("application/x-zip-compressed", "application/zip"); AddMimeMapping(".*", "application/octet-stream"); } private static void AddMimeMapping(string extension, string mimeType) { if (ExtensionToMimeMappingTable.ContainsKey(extension)) { AddMimeSynonym((string)ExtensionToMimeMappingTable[extension], mimeType); } else { ExtensionToMimeMappingTable.Add(extension, mimeType); } } private static void AddMimeSynonym(string mime, string synonym) { if (!MimeSynonyms.ContainsKey(mime)) { MimeSynonyms[mime] = new List<string>(); } if (!MimeSynonyms[mime].Contains(synonym)) { MimeSynonyms[mime].Add(synonym); } } public static string GetMimeMapping(string fileName) { string str = null; int startIndex = fileName.LastIndexOf('.'); if (0 < startIndex && fileName.LastIndexOf('\\') < startIndex) { str = (string)ExtensionToMimeMappingTable[fileName.Substring(startIndex)]; } if (str == null) { str = (string)ExtensionToMimeMappingTable[".*"]; } return str; } public static string GetExtention(string mimeMapping) { if (string.IsNullOrEmpty(mimeMapping)) return null; foreach (DictionaryEntry entry in ExtensionToMimeMappingTable) { var mime = (string)entry.Value; if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; if (MimeSynonyms.ContainsKey(mime)) { if (MimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; } } return null; } } }
using System; using Discord.API.Rest; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Discord.Rest { internal static class ClientHelper { //Applications public static async Task<RestApplication> GetApplicationInfoAsync(BaseDiscordClient client, RequestOptions options) { var model = await client.ApiClient.GetMyApplicationAsync(options).ConfigureAwait(false); return RestApplication.Create(client, model); } public static async Task<RestChannel> GetChannelAsync(BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetChannelAsync(id, options).ConfigureAwait(false); if (model != null) return RestChannel.Create(client, model); return null; } /// <exception cref="InvalidOperationException">Unexpected channel type.</exception> public static async Task<IReadOnlyCollection<IRestPrivateChannel>> GetPrivateChannelsAsync(BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetMyPrivateChannelsAsync(options).ConfigureAwait(false); return models.Select(x => RestChannel.CreatePrivate(client, x)).ToImmutableArray(); } public static async Task<IReadOnlyCollection<RestDMChannel>> GetDMChannelsAsync(BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetMyPrivateChannelsAsync(options).ConfigureAwait(false); return models .Where(x => x.Type == ChannelType.DM) .Select(x => RestDMChannel.Create(client, x)).ToImmutableArray(); } public static async Task<IReadOnlyCollection<RestGroupChannel>> GetGroupChannelsAsync(BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetMyPrivateChannelsAsync(options).ConfigureAwait(false); return models .Where(x => x.Type == ChannelType.Group) .Select(x => RestGroupChannel.Create(client, x)).ToImmutableArray(); } public static async Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync(BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetMyConnectionsAsync(options).ConfigureAwait(false); return models.Select(RestConnection.Create).ToImmutableArray(); } public static async Task<RestInviteMetadata> GetInviteAsync(BaseDiscordClient client, string inviteId, RequestOptions options) { var model = await client.ApiClient.GetInviteAsync(inviteId, options).ConfigureAwait(false); if (model != null) return RestInviteMetadata.Create(client, null, null, model); return null; } public static async Task<RestGuild> GetGuildAsync(BaseDiscordClient client, ulong id, bool withCounts, RequestOptions options) { var model = await client.ApiClient.GetGuildAsync(id, withCounts, options).ConfigureAwait(false); if (model != null) return RestGuild.Create(client, model); return null; } public static async Task<RestGuildEmbed?> GetGuildEmbedAsync(BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetGuildEmbedAsync(id, options).ConfigureAwait(false); if (model != null) return RestGuildEmbed.Create(model); return null; } public static async Task<RestGuildWidget?> GetGuildWidgetAsync(BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetGuildWidgetAsync(id, options).ConfigureAwait(false); if (model != null) return RestGuildWidget.Create(model); return null; } public static IAsyncEnumerable<IReadOnlyCollection<RestUserGuild>> GetGuildSummariesAsync(BaseDiscordClient client, ulong? fromGuildId, int? limit, RequestOptions options) { return new PagedAsyncEnumerable<RestUserGuild>( DiscordConfig.MaxGuildsPerBatch, async (info, ct) => { var args = new GetGuildSummariesParams { Limit = info.PageSize }; if (info.Position != null) args.AfterGuildId = info.Position.Value; var models = await client.ApiClient.GetMyGuildsAsync(args, options).ConfigureAwait(false); return models .Select(x => RestUserGuild.Create(client, x)) .ToImmutableArray(); }, nextPage: (info, lastPage) => { if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch) return false; info.Position = lastPage.Max(x => x.Id); return true; }, start: fromGuildId, count: limit ); } public static async Task<IReadOnlyCollection<RestGuild>> GetGuildsAsync(BaseDiscordClient client, bool withCounts, RequestOptions options) { var summaryModels = await GetGuildSummariesAsync(client, null, null, options).FlattenAsync().ConfigureAwait(false); var guilds = ImmutableArray.CreateBuilder<RestGuild>(); foreach (var summaryModel in summaryModels) { var guildModel = await client.ApiClient.GetGuildAsync(summaryModel.Id, withCounts).ConfigureAwait(false); if (guildModel != null) guilds.Add(RestGuild.Create(client, guildModel)); } return guilds.ToImmutable(); } public static async Task<RestGuild> CreateGuildAsync(BaseDiscordClient client, string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options) { var args = new CreateGuildParams(name, region.Id); if (jpegIcon != null) args.Icon = new API.Image(jpegIcon); var model = await client.ApiClient.CreateGuildAsync(args, options).ConfigureAwait(false); return RestGuild.Create(client, model); } public static async Task<RestUser> GetUserAsync(BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetUserAsync(id, options).ConfigureAwait(false); if (model != null) return RestUser.Create(client, model); return null; } public static async Task<RestGuildUser> GetGuildUserAsync(BaseDiscordClient client, ulong guildId, ulong id, RequestOptions options) { var guild = await GetGuildAsync(client, guildId, false, options).ConfigureAwait(false); if (guild == null) return null; var model = await client.ApiClient.GetGuildMemberAsync(guildId, id, options).ConfigureAwait(false); if (model != null) return RestGuildUser.Create(client, guild, model); return null; } public static async Task<RestWebhook> GetWebhookAsync(BaseDiscordClient client, ulong id, RequestOptions options) { var model = await client.ApiClient.GetWebhookAsync(id).ConfigureAwait(false); if (model != null) return RestWebhook.Create(client, (IGuild)null, model); return null; } public static async Task<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(BaseDiscordClient client, RequestOptions options) { var models = await client.ApiClient.GetVoiceRegionsAsync(options).ConfigureAwait(false); return models.Select(x => RestVoiceRegion.Create(client, x)).ToImmutableArray(); } public static async Task<RestVoiceRegion> GetVoiceRegionAsync(BaseDiscordClient client, string id, RequestOptions options) { var models = await client.ApiClient.GetVoiceRegionsAsync(options).ConfigureAwait(false); return models.Select(x => RestVoiceRegion.Create(client, x)).FirstOrDefault(x => x.Id == id); } public static async Task<int> GetRecommendShardCountAsync(BaseDiscordClient client, RequestOptions options) { var response = await client.ApiClient.GetBotGatewayAsync(options).ConfigureAwait(false); return response.Shards; } public static async Task<BotGateway> GetBotGatewayAsync(BaseDiscordClient client, RequestOptions options) { var response = await client.ApiClient.GetBotGatewayAsync(options).ConfigureAwait(false); return new BotGateway { Url = response.Url, Shards = response.Shards, SessionStartLimit = new SessionStartLimit { Total = response.SessionStartLimit.Total, Remaining = response.SessionStartLimit.Remaining, ResetAfter = response.SessionStartLimit.ResetAfter, MaxConcurrency = response.SessionStartLimit.MaxConcurrency } }; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace TestWebAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider => _documentationProvider.Value; public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) 2018 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.IO; using System.Text; using SIL.Code; namespace SIL.IO { /// <summary> /// Provides a more robust version of System.IO.File methods. /// The original intent of this class is to attempt to mitigate issues /// where we attempt IO but the file is locked by another application. /// Our theory is that some anti-virus software locks files while it scans them. /// /// Later (BL-4340) we encountered problems of corrupted files suspected to be caused /// by power failures or similar disasters before the disk write cache was flushed. /// In an attempt to fix this we made as many methods as possible use FileOptions.WriteThrough, /// which may slow things down but is supposed to guarantee the data is really written /// all the way to something persistent. /// /// The reason some methods are included here but not implemented differently from /// System.IO.File is that this class is intended as a full replacement for System.IO.File. /// The decision of which to provide a special implementation for is based on the /// initial attempt to resolve locked file problems, and the later problems /// with cached writes. /// /// These functions may not throw exactly the same exceptions in the same circumstances /// as the File methods with the same names. /// </summary> public static class RobustFile { private const int FileStreamBufferSize = 4096; // FileStream.DefaultBufferSize, unfortunately not public. // This is just a guess at a buffer size that should make copying reasonably efficient without // being too hard to allocate. internal static int BufferSize = FileStreamBufferSize; // internal so we can tweak in unit tests public static void Copy(string sourceFileName, string destFileName, bool overwrite = false) { RetryUtility.Retry(() => { // This is my own implementation; the .NET library uses a native windows function. var buffer = new byte[BufferSize]; using (var input = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read)) { using ( // We don't need WriteThrough here, it would just slow things down to force // each write to commit. The final Flush(true) guarantees everything is // written before the method returns. var output = new FileStream(destFileName, (overwrite ? FileMode.Create : FileMode.CreateNew), FileAccess.Write, FileShare.None, BufferSize, FileOptions.SequentialScan)) { int count; while ((count = input.Read(buffer, 0, BufferSize)) > 0) { output.Write(buffer, 0, count); } // This is the whole point of replacing File.Copy(); forces a real write all the // way to disk. output.Flush(true); } } // original //File.Copy(sourceFileName, destFileName, overwrite); }); } /// <summary> /// Creates a stream that will write to disk on every write. /// For most purposes (except perhaps logging when crashes are likely), /// calling Flush(true) on the stream when finished would probaby suffice. /// </summary> public static FileStream Create(string path) { // Make it based on a WriteThrough file. // This is based on the .Net implementation of Create (flattened somewhat) // File.Create calls File.Create(path, FileStream.DefaultBufferSize) // which returns new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize) // which calls another constructor adding FileOptions.None, Path.GetFileName(path), false // That constructor is unfortunately internal. But the simplest public constructor that takes a FileOptions // calls the same thing, passing the same extra two options. So the following gives the exact same // effect, except that unfortunately we can't get at the internal constant for FileStream.DefaultBufferSize // and just have to insert its value. return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, FileStreamBufferSize, FileOptions.WriteThrough); // original //return File.Create(path); } /// <summary> /// Creates a streamwriter that will write to disk on every write. /// For most purposes (except perhaps logging when crashes are likely), /// calling Flush(true) on the stream when finished would probaby suffice. /// </summary> public static StreamWriter CreateText(string path) { // Make it based on a WriteThrough file. // This is based on the .Net implementation of CreateText (flattened somewhat) // Various methods in the call chain check these things: if (path == null) throw new ArgumentNullException("path"); // TeamCity builds do not handle nameof() if (path.Length == 0) throw new ArgumentException("Argument_EmptyPath"); // File.CreateText uses the FileStream constructor, passing path, false[not append]. // that uses another FileStream constructor, passing path, false[not append], UTF8NoBOM, DefaultBufferSize[=1024] // that uses another constructor, with the same arguments plus true[checkHost] // apart from error checking, the 5-argument FileStream constructor does: // Stream stream = CreateFile(path, append, checkHost); // Init(stream, encoding, bufferSize, false); // The call to CreateFile expands to a call to an internal constructor, equivalent to: // Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, // 4096, FileOptions.SequentialScan, Path.GetFileName(path), false, false, true) // The fileStream constructor call below is equivalent with two exceptions: // - we're adding in FileOptions.WriteThrough (as desired) // - we end up passing false instead of true for an obscure internal option called checkHost, // which does nothing in the version of .NET that VS thinks we're using. Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, FileStreamBufferSize, FileOptions.SequentialScan | FileOptions.WriteThrough); // The call to Init works out to Init(path, UTF8NoBOM, DefaultBufferSize, false), but // we can't call that private method from here. // However it is also called by the StreamWriter constructor which takes a stream. // In fact, that constructor provides the same values for the other default arguments. // So we can just call the simple constructor. return new StreamWriter(stream); // This is the original (not write-through) implementation. //return File.CreateText(path); } public static void Delete(string path) { RetryUtility.Retry(() => File.Delete(path)); } public static bool Exists(string path) { // Nothing different from File for now return File.Exists(path); } public static FileAttributes GetAttributes(string path) { return RetryUtility.Retry(() => File.GetAttributes(path)); } public static DateTime GetLastWriteTime(string path) { // Nothing different from File for now return File.GetLastWriteTime(path); } public static DateTime GetLastWriteTimeUtc(string path) { // Nothing different from File for now return File.GetLastWriteTimeUtc(path); } public static void Move(string sourceFileName, string destFileName) { RetryUtility.Retry(() => File.Move(sourceFileName, destFileName)); } public static FileStream OpenRead(string path) { return RetryUtility.Retry(() => File.OpenRead(path)); } public static StreamReader OpenText(string path) { return RetryUtility.Retry(() => File.OpenText(path)); } public static byte[] ReadAllBytes(string path) { return RetryUtility.Retry(() => File.ReadAllBytes(path)); } public static string[] ReadAllLines(string path) { return RetryUtility.Retry(() => File.ReadAllLines(path)); } public static string[] ReadAllLines(string path, Encoding encoding) { return RetryUtility.Retry(() => File.ReadAllLines(path, encoding)); } public static string ReadAllText(string path) { return RetryUtility.Retry(() => File.ReadAllText(path)); } public static string ReadAllText(string path, Encoding encoding) { return RetryUtility.Retry(() => File.ReadAllText(path, encoding)); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { // I haven't tried to make this WriteThrough; not sure how to do that while keeping all the // clever properties Replace has. RetryUtility.Retry(() => { try { File.Replace(sourceFileName, destinationFileName, destinationBackupFileName); } catch (UnauthorizedAccessException uae) { // We were getting this while trying to Replace on a JAARS network drive. // The network drive is U:\ which maps to \\waxhaw\users\{username}. // Both files were in the same directory and there were no permissions issues, // but the Replace command was failing with "Access to the path is denied." anyway. // I never could figure out why. See http://issues.bloomlibrary.org/youtrack/issue/BL-4436. // There is very similar code in FileUtils.ReplaceFileWithUserInteractionIfNeeded. try { ReplaceByCopyDelete(sourceFileName, destinationFileName, destinationBackupFileName); } catch { // Though it probably doesn't matter, report the original exception since we prefer Replace to CopyDelete. throw uae; } } }); } public static void ReplaceByCopyDelete(string sourcePath, string destinationPath, string backupPath) { if (!string.IsNullOrEmpty(backupPath) && File.Exists(destinationPath)) { File.Copy(destinationPath, backupPath, true); } File.Copy(sourcePath, destinationPath, true); File.Delete(sourcePath); } public static void SetAttributes(string path, FileAttributes fileAttributes) { RetryUtility.Retry(() => File.SetAttributes(path, fileAttributes)); } public static void WriteAllBytes(string path, byte[] bytes) { RetryUtility.Retry(() => { // This forces it to block until the data is really safely on disk. using (var f = File.Create(path, FileStreamBufferSize, FileOptions.WriteThrough)) { f.Write(bytes, 0, bytes.Length); f.Close(); } }); } public static void WriteAllText(string path, string contents) { // Note that we can't just call WriteAllText(path, contents, Encoding.Utf8). // That would insert an unwanted BOM. var content = Encoding.UTF8.GetBytes(contents); WriteAllBytes(path, content); } /// <summary> /// As in Windows, this version inserts a BOM at the start of the file. Thus, /// in particular, the file produced by WriteString(x,y, Encoding.UTF8) is not /// the same as that produced by WriteString(x, y), though both are encoded /// using UTF8. /// On Windows, the BOM is inserted even if contents is an empty string. /// As of Mono 3.4, Linux instead writes an empty file. We think this is a bug. /// Accordingly, this version is consistent and writes a BOM on both platforms, /// even for empty strings. /// </summary> /// <param name="path"></param> /// <param name="contents"></param> /// <param name="encoding"></param> public static void WriteAllText(string path, string contents, Encoding encoding) { // It's helpful to check for these first so we don't actaully create the file. if (contents == null) throw new ArgumentNullException(@"contents", @"contents must not be null"); if (encoding == null) throw new ArgumentNullException(@"encoding", @"encoding must not be null"); RetryUtility.Retry(() => { // This forces it to block until the data is really safely on disk. using (var f = File.Create(path, FileStreamBufferSize, FileOptions.WriteThrough)) { var preamble = encoding.GetPreamble(); f.Write(preamble, 0, preamble.Length); var content = encoding.GetBytes(contents); f.Write(content, 0, content.Length); f.Close(); } }); } } }
// 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.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Text; using Xunit; namespace System.Collections.Immutable.Tests { public abstract class ImmutablesTestBase { /// <summary> /// Gets the number of operations to perform in randomized tests. /// </summary> protected int RandomOperationsCount { get { return 100; } } internal static void AssertAreSame<T>(T expected, T actual, string message = null, params object[] formattingArgs) { if (typeof(T).GetTypeInfo().IsValueType) { Assert.Equal(expected, actual); //, message, formattingArgs); } else { Assert.Same(expected, actual); //, message, formattingArgs); } } internal static void CollectionAssertAreEquivalent<T>(ICollection<T> expected, ICollection<T> actual) { Assert.Equal(expected.Count, actual.Count); foreach (var value in expected) { Assert.Contains(value, actual); } } protected static string ToString(System.Collections.IEnumerable sequence) { var sb = new StringBuilder(); sb.Append('{'); int count = 0; foreach (object item in sequence) { if (count > 0) { sb.Append(','); } if (count == 10) { sb.Append("..."); break; } sb.Append(item); count++; } sb.Append('}'); return sb.ToString(); } protected static object ToStringDeferred(System.Collections.IEnumerable sequence) { return new DeferredToString(() => ToString(sequence)); } protected static void ManuallyEnumerateTest<T>(IList<T> expectedResults, IEnumerator<T> enumerator) { T[] manualArray = new T[expectedResults.Count]; int i = 0; Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) { manualArray[i++] = enumerator.Current; } enumerator.MoveNext(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.MoveNext(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Equal(expectedResults.Count, i); //, "Enumeration did not produce enough elements."); Assert.Equal<T>(expectedResults, manualArray); } /// <summary> /// Generates an array of unique values. /// </summary> /// <param name="length">The desired length of the array.</param> /// <returns>An array of doubles.</returns> protected double[] GenerateDummyFillData(int length = 1000) { Contract.Requires(length >= 0); Contract.Ensures(Contract.Result<double[]>() != null); Contract.Ensures(Contract.Result<double[]>().Length == length); int seed = unchecked((int)DateTime.Now.Ticks); Debug.WriteLine("Random seed {0}", seed); var random = new Random(seed); var inputs = new double[length]; var ensureUniqueness = new HashSet<double>(); for (int i = 0; i < inputs.Length; i++) { double input; do { input = random.NextDouble(); } while (!ensureUniqueness.Add(input)); inputs[i] = input; } return inputs; } /// <summary> /// Tests the EqualsStructurally public method and the IStructuralEquatable.Equals method. /// </summary> /// <typeparam name="TCollection">The type of tested collection.</typeparam> /// <typeparam name="TElement">The type of element stored in the collection.</typeparam> /// <param name="objectUnderTest">An instance of the collection to test, which must have at least two elements.</param> /// <param name="additionalItem">A unique item that does not already exist in <paramref name="objectUnderTest" />.</param> /// <param name="equalsStructurally">A delegate that invokes the EqualsStructurally method.</param> protected static void StructuralEqualityHelper<TCollection, TElement>(TCollection objectUnderTest, TElement additionalItem, Func<TCollection, IEnumerable<TElement>, bool> equalsStructurally) where TCollection : class, IEnumerable<TElement> { Requires.NotNull(objectUnderTest, "objectUnderTest"); Requires.Argument(objectUnderTest.Count() >= 2, "objectUnderTest", "Collection must contain at least two elements."); Requires.NotNull(equalsStructurally, "equalsStructurally"); var structuralEquatableUnderTest = objectUnderTest as IStructuralEquatable; var enumerableUnderTest = (IEnumerable<TElement>)objectUnderTest; var equivalentSequence = objectUnderTest.ToList(); var shorterSequence = equivalentSequence.Take(equivalentSequence.Count() - 1); var longerSequence = equivalentSequence.Concat(new[] { additionalItem }); var differentSequence = shorterSequence.Concat(new[] { additionalItem }); var nonUniqueSubsetSequenceOfSameLength = shorterSequence.Concat(shorterSequence.Take(1)); var testValues = new IEnumerable<TElement>[] { objectUnderTest, null, Enumerable.Empty<TElement>(), equivalentSequence, longerSequence, shorterSequence, nonUniqueSubsetSequenceOfSameLength, }; foreach (var value in testValues) { bool expectedResult = value != null && Enumerable.SequenceEqual(objectUnderTest, value); if (structuralEquatableUnderTest != null) { Assert.Equal(expectedResult, structuralEquatableUnderTest.Equals(value, null)); if (value != null) { Assert.Equal( expectedResult, structuralEquatableUnderTest.Equals(new NonGenericEnumerableWrapper(value), null)); } } Assert.Equal(expectedResult, equalsStructurally(objectUnderTest, value)); } } private class DeferredToString { private readonly Func<string> _generator; internal DeferredToString(Func<string> generator) { Contract.Requires(generator != null); _generator = generator; } public override string ToString() { return _generator(); } } private class NonGenericEnumerableWrapper : IEnumerable { private readonly IEnumerable _enumerable; internal NonGenericEnumerableWrapper(IEnumerable enumerable) { Requires.NotNull(enumerable, "enumerable"); _enumerable = enumerable; } public IEnumerator GetEnumerator() { return _enumerable.GetEnumerator(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Globalization; using MICore; using System.Threading.Tasks; using System.Linq; namespace Microsoft.MIDebugEngine { public static class EngineUtils { internal static string AsAddr(ulong addr, bool is64bit) { string addrFormat = is64bit ? "x16" : "x8"; return "0x" + addr.ToString(addrFormat, CultureInfo.InvariantCulture); } internal static string GetAddressDescription(DebuggedProcess proc, ulong ip) { string description = null; proc.WorkerThread.RunOperation(async () => { description = await EngineUtils.GetAddressDescriptionAsync(proc, ip); } ); return description; } internal static async Task<string> GetAddressDescriptionAsync(DebuggedProcess proc, ulong ip) { string location = null; IEnumerable<DisasmInstruction> instructions = await proc.Disassembly.FetchInstructions(ip, 1); if (instructions != null) { foreach (DisasmInstruction instruction in instructions) { if (location == null && !String.IsNullOrEmpty(instruction.Symbol)) { location = instruction.Symbol; break; } } } if (location == null) { string addrFormat = proc.Is64BitArch ? "x16" : "x8"; location = ip.ToString(addrFormat, CultureInfo.InvariantCulture); } return location; } public static void CheckOk(int hr) { if (hr != 0) { throw new MIException(hr); } } public static void RequireOk(int hr) { if (hr != 0) { throw new InvalidOperationException(); } } public static AD_PROCESS_ID GetProcessId(IDebugProcess2 process) { AD_PROCESS_ID[] pid = new AD_PROCESS_ID[1]; EngineUtils.RequireOk(process.GetPhysicalProcessId(pid)); return pid[0]; } public static AD_PROCESS_ID GetProcessId(IDebugProgram2 program) { IDebugProcess2 process; RequireOk(program.GetProcess(out process)); return GetProcessId(process); } public static int UnexpectedException(Exception e) { Debug.Fail("Unexpected exception during Attach"); return Constants.RPC_E_SERVERFAULT; } internal static bool IsFlagSet(uint value, int flagValue) { return (value & flagValue) != 0; } internal static bool ProcIdEquals(AD_PROCESS_ID pid1, AD_PROCESS_ID pid2) { if (pid1.ProcessIdType != pid2.ProcessIdType) { return false; } else if (pid1.ProcessIdType == (int)enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM) { return pid1.dwProcessId == pid2.dwProcessId; } else { return pid1.guidProcessId == pid2.guidProcessId; } } // // The RegisterNameMap maps register names to logical group names. The architecture of // the platform is described with all its varients. Any particular target may only contains a subset // of the available registers. public class RegisterNameMap { private Entry[] _map; private struct Entry { public readonly string Name; public readonly bool IsRegex; public readonly string Group; public Entry(string name, bool isRegex, string group) { Name = name; IsRegex = isRegex; Group = group; } }; private static readonly Entry[] s_arm32Registers = new Entry[] { new Entry( "sp", false, "CPU"), new Entry( "lr", false, "CPU"), new Entry( "pc", false, "CPU"), new Entry( "cpsr", false, "CPU"), new Entry( "r[0-9]+", true, "CPU"), new Entry( "fpscr", false, "FPU"), new Entry( "f[0-9]+", true, "FPU"), new Entry( "s[0-9]+", true, "IEEE Single"), new Entry( "d[0-9]+", true, "IEEE Double"), new Entry( "q[0-9]+", true, "Vector"), }; private static readonly Entry[] s_X86Registers = new Entry[] { new Entry( "eax", false, "CPU" ), new Entry( "ecx", false, "CPU" ), new Entry( "edx", false, "CPU" ), new Entry( "ebx", false, "CPU" ), new Entry( "esp", false, "CPU" ), new Entry( "ebp", false, "CPU" ), new Entry( "esi", false, "CPU" ), new Entry( "edi", false, "CPU" ), new Entry( "eip", false, "CPU" ), new Entry( "eflags", false, "CPU" ), new Entry( "cs", false, "CPU" ), new Entry( "ss", false, "CPU" ), new Entry( "ds", false, "CPU" ), new Entry( "es", false, "CPU" ), new Entry( "fs", false, "CPU" ), new Entry( "gs", false, "CPU" ), new Entry( "st", true, "CPU" ), new Entry( "fctrl", false, "CPU" ), new Entry( "fstat", false, "CPU" ), new Entry( "ftag", false, "CPU" ), new Entry( "fiseg", false, "CPU" ), new Entry( "fioff", false, "CPU" ), new Entry( "foseg", false, "CPU" ), new Entry( "fooff", false, "CPU" ), new Entry( "fop", false, "CPU" ), new Entry( "mxcsr", false, "CPU" ), new Entry( "orig_eax", false, "CPU" ), new Entry( "al", false, "CPU" ), new Entry( "cl", false, "CPU" ), new Entry( "dl", false, "CPU" ), new Entry( "bl", false, "CPU" ), new Entry( "ah", false, "CPU" ), new Entry( "ch", false, "CPU" ), new Entry( "dh", false, "CPU" ), new Entry( "bh", false, "CPU" ), new Entry( "ax", false, "CPU" ), new Entry( "cx", false, "CPU" ), new Entry( "dx", false, "CPU" ), new Entry( "bx", false, "CPU" ), new Entry( "bp", false, "CPU" ), new Entry( "si", false, "CPU" ), new Entry( "di", false, "CPU" ), new Entry( "mm[0-7]", true, "MMX" ), new Entry( "xmm[0-7]ih", true, "SSE2" ), new Entry( "xmm[0-7]il", true, "SSE2" ), new Entry( "xmm[0-7]dh", true, "SSE2" ), new Entry( "xmm[0-7]dl", true, "SSE2" ), new Entry( "xmm[0-7][0-7]", true, "SSE" ), new Entry( "ymm.+", true, "AVX" ), new Entry( "mm[0-7][0-7]", true, "AMD3DNow" ), }; private static readonly Entry[] s_allRegisters = new Entry[] { new Entry( ".+", true, "CPU"), }; public static RegisterNameMap Create(string[] registerNames) { // TODO: more robust mechanism for determining processor architecture RegisterNameMap map = new RegisterNameMap(); if (registerNames[0][0] == 'r') // registers are prefixed with 'r', assume ARM and initialize its register sets { map._map = s_arm32Registers; } else if (registerNames[0][0] == 'e') // x86 register set { map._map = s_X86Registers; } else { // report one global register set map._map = s_allRegisters; } return map; } public string GetGroupName(string regName) { foreach (var e in _map) { if (e.IsRegex) { if (System.Text.RegularExpressions.Regex.IsMatch(regName, e.Name)) { return e.Group; } } else if (e.Name == regName) { return e.Group; } } return "Other Registers"; } }; internal static string GetExceptionDescription(Exception exception) { if (!ExceptionHelper.IsCorruptingException(exception)) { return exception.Message; } else { return string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_CorruptingException, exception.GetType().FullName, exception.StackTrace); } } internal class SignalMap : Dictionary<string, uint> { private static SignalMap s_instance; private SignalMap() { this["SIGHUP"] = 1; this["SIGINT"] = 2; this["SIGQUIT"] = 3; this["SIGILL"] = 4; this["SIGTRAP"] = 5; this["SIGABRT"] = 6; this["SIGIOT"] = 6; this["SIGBUS"] = 7; this["SIGFPE"] = 8; this["SIGKILL"] = 9; this["SIGUSR1"] = 10; this["SIGSEGV"] = 11; this["SIGUSR2"] = 12; this["SIGPIPE"] = 13; this["SIGALRM"] = 14; this["SIGTERM"] = 15; this["SIGSTKFLT"] = 16; this["SIGCHLD"] = 17; this["SIGCONT"] = 18; this["SIGSTOP"] = 19; this["SIGTSTP"] = 20; this["SIGTTIN"] = 21; this["SIGTTOU"] = 22; this["SIGURG"] = 23; this["SIGXCPU"] = 24; this["SIGXFSZ"] = 25; this["SIGVTALRM"] = 26; this["SIGPROF"] = 27; this["SIGWINCH"] = 28; this["SIGIO"] = 29; this["SIGPOLL"] = 29; this["SIGPWR"] = 30; this["SIGSYS"] = 31; this["SIGUNUSED"] = 31; } public static SignalMap Instance { get { if (s_instance == null) { s_instance = new SignalMap(); } return s_instance; } } } } }
/* * 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 log4net; using log4net.Appender; using log4net.Core; using log4net.Repository; using Nini.Config; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace OpenSim.Framework.Servers { public class ServerBase { /// <summary> /// Console to be used for any command line output. Can be null, in which case there should be no output. /// </summary> protected ICommandConsole m_console; protected OpenSimAppender m_consoleAppender; protected FileAppender m_logFileAppender; protected string m_pidFile = String.Empty; protected ServerStatsCollector m_serverStatsCollector; protected string m_startupDirectory = Environment.CurrentDirectory; protected DateTime m_startuptime; /// <summary> /// Server version information. Usually VersionInfo + information about git commit, operating system, etc. /// </summary> protected string m_version; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public ServerBase() { m_startuptime = DateTime.Now; m_version = VersionInfo.Version; EnhanceVersionInformation(); } public IConfigSource Config { get; protected set; } /// <summary> /// Get a thread pool report. /// </summary> /// <returns></returns> public static string GetThreadPoolReport() { string threadPoolUsed = null; int maxThreads = 0; int minThreads = 0; int allocatedThreads = 0; int inUseThreads = 0; int waitingCallbacks = 0; int completionPortThreads = 0; StringBuilder sb = new StringBuilder(); if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) { STPInfo stpi = Util.GetSmartThreadPoolInfo(); // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool. if (stpi != null) { threadPoolUsed = "SmartThreadPool"; maxThreads = stpi.MaxThreads; minThreads = stpi.MinThreads; inUseThreads = stpi.InUseThreads; allocatedThreads = stpi.ActiveThreads; waitingCallbacks = stpi.WaitingCallbacks; } } else if ( Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem) { threadPoolUsed = "BuiltInThreadPool"; ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads); ThreadPool.GetMinThreads(out minThreads, out completionPortThreads); int availableThreads; ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads); inUseThreads = maxThreads - availableThreads; allocatedThreads = -1; waitingCallbacks = -1; } if (threadPoolUsed != null) { sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed); sb.AppendFormat("Max threads : {0}\n", maxThreads); sb.AppendFormat("Min threads : {0}\n", minThreads); sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString()); sb.AppendFormat("In use threads : {0}\n", inUseThreads); sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString()); } else { sb.AppendFormat("Thread pool not used\n"); } return sb.ToString(); } public virtual void HandleShow(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "info": ShowInfo(); break; case "version": Notice(GetVersionText()); break; case "uptime": Notice(GetUptimeReport()); break; case "threads": Notice(GetThreadsReport()); break; } } public virtual void HandleThreadsAbort(string module, string[] cmd) { if (cmd.Length != 3) { MainConsole.Instance.Output("Usage: threads abort <thread-id>"); return; } int threadId; if (!int.TryParse(cmd[2], out threadId)) { MainConsole.Instance.Output("ERROR: Thread id must be an integer"); return; } if (Watchdog.AbortThread(threadId)) MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId); else MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId); } /// <summary> /// Log information about the circumstances in which we're running (OpenSimulator version number, CLR details, /// etc.). /// </summary> public void LogEnvironmentInformation() { // FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net // XmlConfigurator calls first accross servers. m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory); m_log.InfoFormat("[SERVER BASE]: OpenSimulator version: {0}", m_version); // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and // the clr version number doesn't match the project version number under Mono. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine); m_log.InfoFormat( "[SERVER BASE]: Operating system version: {0}, .NET platform {1}, {2}-bit", Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32"); } public void RegisterCommonAppenders(IConfig startupConfig) { ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "Console") { m_consoleAppender = (OpenSimAppender)appender; } else if (appender.Name == "LogFileAppender") { m_logFileAppender = (FileAppender)appender; } } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); } else { // FIXME: This should be done through an interface rather than casting. m_consoleAppender.Console = (ConsoleBase)m_console; // If there is no threshold set then the threshold is effectively everything. if (null == m_consoleAppender.Threshold) m_consoleAppender.Threshold = Level.All; Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } if (m_logFileAppender != null && startupConfig != null) { string cfgFileName = startupConfig.GetString("LogFile", null); if (cfgFileName != null) { m_logFileAppender.File = cfgFileName; m_logFileAppender.ActivateOptions(); } m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File); } } /// <summary> /// Register common commands once m_console has been set if it is going to be set /// </summary> public void RegisterCommonCommands() { if (m_console == null) return; m_console.Commands.AddCommand( "General", false, "show info", "show info", "Show general information about the server", HandleShow); m_console.Commands.AddCommand( "General", false, "show version", "show version", "Show server version", HandleShow); m_console.Commands.AddCommand( "General", false, "show uptime", "show uptime", "Show server uptime", HandleShow); m_console.Commands.AddCommand( "General", false, "get log level", "get log level", "Get the current console logging level", (mod, cmd) => ShowLogLevel()); m_console.Commands.AddCommand( "General", false, "set log level", "set log level <level>", "Set the console logging level for this session.", HandleSetLogLevel); m_console.Commands.AddCommand( "General", false, "config set", "config set <section> <key> <value>", "Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.", HandleConfig); m_console.Commands.AddCommand( "General", false, "config get", "config get [<section>] [<key>]", "Synonym for config show", HandleConfig); m_console.Commands.AddCommand( "General", false, "config show", "config show [<section>] [<key>]", "Show config information", "If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine + "If a section is given but not a field, then all fields in that section are printed.", HandleConfig); m_console.Commands.AddCommand( "General", false, "config save", "config save <path>", "Save current configuration to a file at the given path", HandleConfig); m_console.Commands.AddCommand( "General", false, "command-script", "command-script <script>", "Run a command script from file", HandleScript); m_console.Commands.AddCommand( "General", false, "show threads", "show threads", "Show thread status", HandleShow); m_console.Commands.AddCommand( "Debug", false, "threads abort", "threads abort <thread-id>", "Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort); m_console.Commands.AddCommand( "General", false, "threads show", "threads show", "Show thread status. Synonym for \"show threads\"", (string module, string[] args) => Notice(GetThreadsReport())); m_console.Commands.AddCommand( "Debug", false, "debug comms set", "debug comms set serialosdreq true|false", "Set comms parameters. For debug purposes.", HandleDebugCommsSet); m_console.Commands.AddCommand( "Debug", false, "debug comms status", "debug comms status", "Show current debug comms parameters.", HandleDebugCommsStatus); m_console.Commands.AddCommand( "Debug", false, "debug threadpool set", "debug threadpool set worker|iocp min|max <n>", "Set threadpool parameters. For debug purposes.", HandleDebugThreadpoolSet); m_console.Commands.AddCommand( "Debug", false, "debug threadpool status", "debug threadpool status", "Show current debug threadpool parameters.", HandleDebugThreadpoolStatus); m_console.Commands.AddCommand( "Debug", false, "debug threadpool level", "debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL, "Turn on logging of activity in the main thread pool.", "Log levels:\n" + " 0 = no logging\n" + " 1 = only first line of stack trace; don't log common threads\n" + " 2 = full stack trace; don't log common threads\n" + " 3 = full stack trace, including common threads\n", HandleDebugThreadpoolLevel); m_console.Commands.AddCommand( "Debug", false, "force gc", "force gc", "Manually invoke runtime garbage collection. For debugging purposes", HandleForceGc); m_console.Commands.AddCommand( "General", false, "quit", "quit", "Quit the application", (mod, args) => Shutdown()); m_console.Commands.AddCommand( "General", false, "shutdown", "shutdown", "Quit the application", (mod, args) => Shutdown()); ChecksManager.RegisterConsoleCommands(m_console); StatsManager.RegisterConsoleCommands(m_console); } public void RegisterCommonComponents(IConfigSource configSource) { IConfig networkConfig = configSource.Configs["Network"]; if (networkConfig != null) { WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false); } m_serverStatsCollector = new ServerStatsCollector(); m_serverStatsCollector.Initialise(configSource); m_serverStatsCollector.Start(); } public virtual void Shutdown() { m_serverStatsCollector.Close(); ShutdownSpecific(); } protected void CreatePIDFile(string path) { if (File.Exists(path)) m_log.ErrorFormat( "[SERVER BASE]: Previous pid file {0} still exists on startup. Possibly previously unclean shutdown.", path); try { string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); using (FileStream fs = File.Create(path)) { Byte[] buf = Encoding.ASCII.GetBytes(pidstring); fs.Write(buf, 0, buf.Length); } m_pidFile = path; m_log.InfoFormat("[SERVER BASE]: Created pid file {0}", m_pidFile); } catch (Exception e) { m_log.Warn(string.Format("[SERVER BASE]: Could not create PID file at {0} ", path), e); } } /// <summary> /// Enhance the version string with extra information if it's available. /// </summary> protected void EnhanceVersionInformation() { string buildVersion = string.Empty; // The subversion information is deprecated and will be removed at a later date // Add subversion revision information if available // Try file "svn_revision" in the current directory first, then the .svn info. // This allows to make the revision available in simulators not running from the source tree. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place // elsewhere as well string gitDir = "../.git/"; string gitRefPointerPath = gitDir + "HEAD"; string svnRevisionFileName = "svn_revision"; string svnFileName = ".svn/entries"; string manualVersionFileName = ".version"; string inputLine; int strcmp; if (File.Exists(manualVersionFileName)) { using (StreamReader CommitFile = File.OpenText(manualVersionFileName)) buildVersion = CommitFile.ReadLine(); m_version += buildVersion ?? ""; } else if (File.Exists(gitRefPointerPath)) { // m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath); string rawPointer = ""; using (StreamReader pointerFile = File.OpenText(gitRefPointerPath)) rawPointer = pointerFile.ReadLine(); // m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer); Match m = Regex.Match(rawPointer, "^ref: (.+)$"); if (m.Success) { // m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value); string gitRef = m.Groups[1].Value; string gitRefPath = gitDir + gitRef; if (File.Exists(gitRefPath)) { // m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath); using (StreamReader refFile = File.OpenText(gitRefPath)) { string gitHash = refFile.ReadLine(); m_version += gitHash.Substring(0, 7); } } } } else { // Remove the else logic when subversion mirror is no longer used if (File.Exists(svnRevisionFileName)) { StreamReader RevisionFile = File.OpenText(svnRevisionFileName); buildVersion = RevisionFile.ReadLine(); buildVersion.Trim(); RevisionFile.Close(); } if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName)) { StreamReader EntriesFile = File.OpenText(svnFileName); inputLine = EntriesFile.ReadLine(); while (inputLine != null) { // using the dir svn revision at the top of entries file strcmp = String.Compare(inputLine, "dir"); if (strcmp == 0) { buildVersion = EntriesFile.ReadLine(); break; } else { inputLine = EntriesFile.ReadLine(); } } EntriesFile.Close(); } m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6); } } /// <summary> /// Get a report about the registered threads in this server. /// </summary> protected string GetThreadsReport() { // This should be a constant field. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}"; StringBuilder sb = new StringBuilder(); Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo(); sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine); int timeNow = Environment.TickCount & Int32.MaxValue; sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE"); sb.Append(Environment.NewLine); foreach (Watchdog.ThreadWatchdogInfo twi in threads) { Thread t = twi.Thread; sb.AppendFormat( reportFormat, t.ManagedThreadId, t.Name, timeNow - twi.LastTick, timeNow - twi.FirstTick, t.Priority, t.ThreadState); sb.Append("\n"); } sb.Append("\n"); // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting // zero active threads. int totalThreads = Process.GetCurrentProcess().Threads.Count; if (totalThreads > 0) sb.AppendFormat("Total threads active: {0}\n\n", totalThreads); sb.Append("Main threadpool (excluding script engine pools)\n"); sb.Append(GetThreadPoolReport()); return sb.ToString(); } /// <summary> /// Return a report about the uptime of this server /// </summary> /// <returns></returns> protected string GetUptimeReport() { StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now)); sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime)); sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime)); return sb.ToString(); } protected string GetVersionText() { return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion); } protected virtual void HandleScript(string module, string[] parms) { if (parms.Length != 2) { Notice("Usage: command-script <path-to-script"); return; } RunCommandScript(parms[1]); } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> /// <param name="msg"></param> protected void Notice(string msg) { if (m_console != null) { m_console.Output(msg); } } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> /// <param name="format"></param> /// <param name="components"></param> protected void Notice(string format, params object[] components) { if (m_console != null) m_console.OutputFormat(format, components); } protected void RemovePIDFile() { if (m_pidFile != String.Empty) { try { File.Delete(m_pidFile); } catch (Exception e) { m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e); } m_pidFile = String.Empty; } } /// <summary> /// Run an optional startup list of commands /// </summary> /// <param name="fileName"></param> protected void RunCommandScript(string fileName) { if (m_console == null) return; if (File.Exists(fileName)) { m_log.Info("[SERVER BASE]: Running " + fileName); using (StreamReader readFile = File.OpenText(fileName)) { string currentCommand; while ((currentCommand = readFile.ReadLine()) != null) { currentCommand = currentCommand.Trim(); if (!(currentCommand == "" || currentCommand.StartsWith(";") || currentCommand.StartsWith("//") || currentCommand.StartsWith("#"))) { m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'"); m_console.RunCommand(currentCommand); } } } } } protected void ShowInfo() { Notice(GetVersionText()); Notice("Startup directory: " + m_startupDirectory); if (null != m_consoleAppender) Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold)); } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> protected virtual void ShutdownSpecific() { } private static void HandleDebugThreadpoolLevel(string module, string[] cmdparams) { if (cmdparams.Length < 4) { MainConsole.Instance.Output("Usage: debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL); return; } string rawLevel = cmdparams[3]; int newLevel; if (!int.TryParse(rawLevel, out newLevel)) { MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawLevel); return; } if (newLevel < 0 || newLevel > Util.MAX_THREADPOOL_LEVEL) { MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0.." + Util.MAX_THREADPOOL_LEVEL, newLevel); return; } Util.LogThreadPool = newLevel; MainConsole.Instance.OutputFormat("LogThreadPool set to {0}", newLevel); } /// <summary> /// Change and load configuration file data. /// </summary> /// <param name="module"></param> /// <param name="cmd"></param> private void HandleConfig(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] cmdparams = args.ToArray(); if (cmdparams.Length > 0) { string firstParam = cmdparams[0].ToLower(); switch (firstParam) { case "set": if (cmdparams.Length < 4) { Notice("Syntax: config set <section> <key> <value>"); Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5"); } else { IConfig c; IConfigSource source = new IniConfigSource(); c = source.AddConfig(cmdparams[1]); if (c != null) { string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3); c.Set(cmdparams[2], _value); Config.Merge(source); Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value); } } break; case "get": case "show": if (cmdparams.Length == 1) { foreach (IConfig config in Config.Configs) { Notice("[{0}]", config.Name); string[] keys = config.GetKeys(); foreach (string key in keys) Notice(" {0} = {1}", key, config.GetString(key)); } } else if (cmdparams.Length == 2 || cmdparams.Length == 3) { IConfig config = Config.Configs[cmdparams[1]]; if (config == null) { Notice("Section \"{0}\" does not exist.", cmdparams[1]); break; } else { if (cmdparams.Length == 2) { Notice("[{0}]", config.Name); foreach (string key in config.GetKeys()) Notice(" {0} = {1}", key, config.GetString(key)); } else { Notice( "config get {0} {1} : {2}", cmdparams[1], cmdparams[2], config.GetString(cmdparams[2])); } } } else { Notice("Syntax: config {0} [<section>] [<key>]", firstParam); Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam); } break; case "save": if (cmdparams.Length < 2) { Notice("Syntax: config save <path>"); return; } string path = cmdparams[1]; Notice("Saving configuration file: {0}", path); if (Config is IniConfigSource) { IniConfigSource iniCon = (IniConfigSource)Config; iniCon.Save(path); } else if (Config is XmlConfigSource) { XmlConfigSource xmlCon = (XmlConfigSource)Config; xmlCon.Save(path); } break; } } } private void HandleDebugCommsSet(string module, string[] args) { if (args.Length != 5) { Notice("Usage: debug comms set serialosdreq true|false"); return; } if (args[3] != "serialosdreq") { Notice("Usage: debug comms set serialosdreq true|false"); return; } bool setSerializeOsdRequests; if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests)) return; WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests; Notice("serialosdreq is now {0}", setSerializeOsdRequests); } private void HandleDebugCommsStatus(string module, string[] args) { Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint); } private void HandleDebugThreadpoolSet(string module, string[] args) { if (args.Length != 6) { Notice("Usage: debug threadpool set worker|iocp min|max <n>"); return; } int newThreads; if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads)) return; string poolType = args[3]; string bound = args[4]; bool fail = false; int workerThreads, iocpThreads; if (poolType == "worker") { if (bound == "min") { ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMinThreads(newThreads, iocpThreads)) fail = true; } else { ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads)) fail = true; } } else { if (bound == "min") { ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMinThreads(workerThreads, newThreads)) fail = true; } else { ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMaxThreads(workerThreads, newThreads)) fail = true; } } if (fail) { Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads); } else { int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads; ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads); ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads); Notice("Min worker threads now {0}", minWorkerThreads); Notice("Min IOCP threads now {0}", minIocpThreads); Notice("Max worker threads now {0}", maxWorkerThreads); Notice("Max IOCP threads now {0}", maxIocpThreads); } } private void HandleDebugThreadpoolStatus(string module, string[] args) { int workerThreads, iocpThreads; ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); Notice("Min worker threads: {0}", workerThreads); Notice("Min IOCP threads: {0}", iocpThreads); ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); Notice("Max worker threads: {0}", workerThreads); Notice("Max IOCP threads: {0}", iocpThreads); ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads); Notice("Available worker threads: {0}", workerThreads); Notice("Available IOCP threads: {0}", iocpThreads); } private void HandleForceGc(string module, string[] args) { Notice("Manually invoking runtime garbage collection"); GC.Collect(); } private void HandleSetLogLevel(string module, string[] cmd) { if (cmd.Length != 4) { Notice("Usage: set log level <level>"); return; } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); return; } string rawLevel = cmd[3]; ILoggerRepository repository = LogManager.GetRepository(); Level consoleLevel = repository.LevelMap[rawLevel]; if (consoleLevel != null) m_consoleAppender.Threshold = consoleLevel; else Notice( "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", rawLevel); ShowLogLevel(); } private void ShowLogLevel() { Notice("Console log level is {0}", m_consoleAppender.Threshold); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; using Axiom.Core; using Axiom.Graphics; using Axiom.MathLib; using Multiverse.ToolBox; namespace Multiverse.Tools.WorldEditor { /// <summary> /// Summary description for Waypoint /// </summary> public class Waypoint : IWorldObject, IWorldContainer, IObjectPosition, IObjectOrientation, IObjectDrag, IObjectChangeCollection, IObjectDelete, IObjectCutCopy, IObjectCameraLockable { protected IWorldContainer parent; protected WorldEditor app; protected string name; protected Quaternion orientation; protected DisplayObject disp; protected NameValueObject nameValuePairs; protected bool highlight = false; protected Vector3 position; protected WorldTreeNode node = null; protected WorldTreeNode parentNode = null; protected List<IWorldObject> children; protected Vector3 direction; protected Vector3 rotation; protected float azimuth; protected float zenith; protected float terrainOffset; protected bool allowAdjustHeightOffTerrain = true; protected bool offsetFound = false; protected bool updating = false; protected bool inScene = false; protected bool inTree = false; protected bool worldViewSelectable = true; protected bool customColor = false; protected string customMaterialName; protected ColorEx color = ColorEx.Black; const float defaultScale = 4f; const float defaultRot = 0f; //protected string soundAssetName = null; protected List<ToolStripButton> buttonBar; public Waypoint(string name, IWorldContainer parent, WorldEditor app, Vector3 location, Vector3 rotation) { this.parent = parent; this.app = app; this.position = location; this.name = name; this.nameValuePairs = new NameValueObject(); this.children = new List<IWorldObject>(); this.orientation = new Quaternion(0, 0, 0, 0); // this.orientation = Quaternion.FromAngleAxis(defaultRot * MathUtil.RADIANS_PER_DEGREE, Vector3.UnitY); SetDirection(rotation.y,90); } public Waypoint(string name, IWorldContainer parent, WorldEditor app, Vector3 location, Quaternion orientation) { this.azimuth = 0f; this.zenith = 0f; this.name = name; this.app = app; this.orientation = new Quaternion(orientation.w, orientation.x, orientation.y, orientation.z); this.position = location; this.parent = parent; this.nameValuePairs = new NameValueObject(); this.children = new List<IWorldObject>(); } public Waypoint(XmlReader r, IWorldContainer parent, WorldEditor app) { this.parent = parent; this.app = app; this.children = new List<IWorldObject>(); FromXml(r); if (nameValuePairs == null) { nameValuePairs = new NameValueObject(); } } protected void FromXml(XmlReader r) { // first parse the attributes bool adjustHeightFound = false; for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read switch (r.Name) { case "Name": this.name = r.Value; break; //case "Sound": // this.soundAssetName = r.Value; // break; case "TerrainOffset": offsetFound = true; terrainOffset = float.Parse(r.Value); break; case "AllowHeightAdjustment": adjustHeightFound = true; if (String.Equals(r.Value.ToLower(), "false")) { allowAdjustHeightOffTerrain = false; } break; case "Azimuth": azimuth = float.Parse(r.Value); break; case "Zenith": zenith = float.Parse(r.Value); break; case "WorldViewSelect": worldViewSelectable = bool.Parse(r.Value); break; } } // this.nameValuePairs = new NameValueObject(); r.Read(); do { if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "Position": this.position = XmlHelperClass.ParseVectorAttributes(r); break; case "Orientation": orientation = XmlHelperClass.ParseQuaternion(r); break; case "NameValuePairs": this.nameValuePairs = new NameValueObject(r); break; case "ParticleEffect": ParticleEffect particle = new ParticleEffect(r, this, app); Add(particle); break; case "SpawnGen": SpawnGen mob = new SpawnGen(r, app, this); Add(mob); break; case "Sound": Sound sound = new Sound(r, this, app); Add(sound); break; case "Color": Color = XmlHelperClass.ParseColorAttributes(r); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } while (r.Read()); if (!adjustHeightFound) { allowAdjustHeightOffTerrain = true; } if (!offsetFound) { terrainOffset = this.Position.y - app.GetTerrainHeight(position.x, position.z); } if (orientation != null && disp != null) { disp.SetOrientation(orientation); foreach (IWorldObject obj in children) { if (obj is ParticleEffect) { (obj as ParticleEffect).Orientation = this.orientation; } } } } public void AddToScene() { if (app.DisplayMarkerPoints) { if (!offsetFound) { float terrainHeight = app.GetTerrainHeight(Position.x, Position.z); terrainOffset = position.y - terrainHeight; } Vector3 scaleVec = new Vector3(app.Config.MarkerPointScale, app.Config.MarkerPointScale, app.Config.MarkerPointScale); this.disp = new DisplayObject(this, name, app, "waypoint", app.Scene, app.Config.MarkerPointMeshName, position, scaleVec, this.orientation, null); this.disp.TerrainOffset = this.terrainOffset; if (customColor) { this.disp.MaterialName = customMaterialName; } else { this.disp.MaterialName = app.Config.MarkerPointMaterial; } foreach (IWorldObject child in children) { child.AddToScene(); if (child is ParticleEffect) { (child as ParticleEffect).Orientation = orientation; } } if (disp.Entity.Mesh.TriangleIntersector == null) disp.Entity.Mesh.CreateTriangleIntersector(); inScene = true; } else { foreach (IWorldObject child in children) { if (app.DisplayParticleEffects && child is ParticleEffect && app.WorldRoot != null) { child.AddToScene(); (child as ParticleEffect).Orientation = orientation; } } } } public void UpdateScene(UpdateTypes type, UpdateHint hint) { foreach (IWorldObject child in children) { child.UpdateScene(type, hint); } if ((type == UpdateTypes.Markers || type == UpdateTypes.All) && hint == UpdateHint.DisplayMarker) { if (inScene == app.DisplayMarkerPoints) { return; } else { if (inScene) { this.updating = true; this.RemoveFromScene(); this.updating = false; } else { this.AddToScene(); } } } if ((type == UpdateTypes.All || type == UpdateTypes.Markers) && hint == UpdateHint.TerrainUpdate && allowAdjustHeightOffTerrain) { this.position.y = app.GetTerrainHeight(position.x, position.z) + terrainOffset; } } public void RemoveFromScene() { if (inScene) { inScene = false; disp.Dispose(); disp = null; } foreach (IWorldObject child in children) { if (child is ParticleEffect && app.DisplayParticleEffects && updating && (parent as WorldObjectCollection).InScene) { continue; } child.RemoveFromScene(); } } [DescriptionAttribute("The name of this marker."), CategoryAttribute("Miscellaneous")] public string Name { get { return this.name; } set { this.name = value; UpdateNode(); } } protected void UpdateNode() { if (inTree) { node.Text = NodeName; } } [BrowsableAttribute(false)] public bool AcceptObjectPlacement { get { return false; } set { //not implemented for this type of object } } protected string NodeName { get { string ret; if (app.Config.ShowTypeLabelsInTreeView) { ret = string.Format("{0}: {1}", ObjectType, name); } else { ret = name; } return ret; } } [DescriptionAttribute("The Rotation around the Y Axis(runs verticle) of this marker in the world")] [BrowsableAttribute(false)] public float Rotation { get { return rotation.y; } set { rotation = new Vector3(0, value, 0); if (inScene) { disp.SetRotation(value); } } } #region IObjectPosition [BrowsableAttribute(false)] public bool AllowYChange { get { return true; } } [BrowsableAttribute(false)] public Vector3 Position { get { return position; } set { position = value; terrainOffset = position.y - app.GetTerrainHeight(position.x, position.z); if (inScene) { disp.Position = position; disp.TerrainOffset = terrainOffset; } foreach (IWorldObject child in children) { if (child is ParticleEffect) { ParticleEffect particle = child as ParticleEffect; particle.PositionUpdate(); } } } } [BrowsableAttribute(false)] public float TerrainOffset { get { return terrainOffset; } set { terrainOffset = value; if (inScene) { disp.TerrainOffset = terrainOffset; } } } #endregion IObjectPosition [BrowsableAttribute(false)] public Vector3 FocusLocation { get { return Position; } } [BrowsableAttribute(false)] public bool Highlight { get { return highlight; } set { highlight = value; if (disp != null) { disp.Highlight = highlight; } } } [BrowsableAttribute(false)] public WorldTreeNode Node { get { return node; } } [EditorAttribute(typeof(NameValueUITypeEditorMarker), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Arbitrary Name/Value pair used to pass information about an object to server scripts and plug-ins. Click [...] to add or edit name/value pairs."), CategoryAttribute("Miscellaneous")] public NameValueObject NameValue { get { return nameValuePairs; } set { nameValuePairs = value; } } [EditorAttribute(typeof(ColorValueUITypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Color of this Marker Point. (click [...] to use the color picker dialog to select a color)."), CategoryAttribute("Colors")] public ColorEx Color { get { return color; } set { color = value; Material eMat; if (!customColor) { customColor = true; Material mat = MaterialManager.Instance.GetByName(app.Config.MarkerPointCustomMaterial); customMaterialName = Guid.NewGuid().ToString(); eMat = mat.Clone(customMaterialName); eMat.Load(); } else { eMat = MaterialManager.Instance.GetByName(customMaterialName); } eMat.GetBestTechnique().GetPass(0).GetTextureUnitState(0).SetColorOperationEx( LayerBlendOperationEx.Modulate, LayerBlendSource.Manual, LayerBlendSource.Diffuse, color); if (InScene) { disp.MaterialName = customMaterialName; } } } public void AddToTree(WorldTreeNode parentNode) { if (parentNode != null && !inTree) { this.parentNode = parentNode; inTree = true; // create a node for the collection and add it to the parent node = app.MakeTreeNode(this, NodeName); parentNode.Nodes.Add(node); // build the menu CommandMenuBuilder menuBuilder = new CommandMenuBuilder(); menuBuilder.Add("Attach Particle Effect", new AddWaypointParticleEffectCommandFactory(app, this), app.DefaultCommandClickHandler); menuBuilder.Add("Add Spawn Generator", new AddSpawnGenToMarkerCommandFactory(app, this), app.DefaultCommandClickHandler); menuBuilder.Add("Add Sound", new AddSoundCommandFactory(app, this), app.DefaultCommandClickHandler); menuBuilder.AddDropDown("View From"); menuBuilder.Add("Above", new DirectionAndMarker(CameraDirection.Above, this), app.CameraMarkerDirClickHandler); menuBuilder.Add("North", new DirectionAndMarker(CameraDirection.North, this), app.CameraMarkerDirClickHandler); menuBuilder.Add("South", new DirectionAndMarker(CameraDirection.South, this), app.CameraMarkerDirClickHandler); menuBuilder.Add("West", new DirectionAndMarker(CameraDirection.West, this), app.CameraMarkerDirClickHandler); menuBuilder.Add("East", new DirectionAndMarker(CameraDirection.East, this), app.CameraMarkerDirClickHandler); menuBuilder.FinishDropDown(); menuBuilder.Add("Drag Marker", new DragObjectsFromMenuCommandFactory(app), app.DefaultCommandClickHandler); menuBuilder.AddDropDown("Move to Collection", menuBuilder.ObjectCollectionDropDown_Opening); menuBuilder.FinishDropDown(); menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click); menuBuilder.Add("Help", "Marker", app.HelpClickHandler); menuBuilder.Add("Delete", new DeleteObjectCommandFactory(app, parent, this), app.DefaultCommandClickHandler); node.ContextMenuStrip = menuBuilder.Menu; foreach (IWorldObject child in children) { child.AddToTree(node); } buttonBar = menuBuilder.ButtonBar; } else { inTree = false; } } [CategoryAttribute("Miscellaneous"), DescriptionAttribute("Sets if the marker may be selected in the world view")] public bool WorldViewSelectable { get { return worldViewSelectable; } set { worldViewSelectable = value; } } [BrowsableAttribute(false)] public bool IsGlobal { get { return false; } } [BrowsableAttribute(false)] public bool IsTopLevel { get { return true; } } public void Clone(IWorldContainer copyParent) { Waypoint clone = new Waypoint(name, copyParent, app, position, rotation); clone.Azimuth = azimuth; clone.Zenith = zenith; clone.TerrainOffset = terrainOffset; clone.AllowAdjustHeightOffTerrain = allowAdjustHeightOffTerrain; clone.NameValue = new NameValueObject(this.NameValue); foreach (IWorldObject child in children) { child.Clone(clone); } copyParent.Add(clone); } [BrowsableAttribute(false)] public string ObjectAsString { get { string objString = String.Format("Name:{0}\r\n", NodeName); objString += String.Format("\tAllowAdjustHeightOffTerrain={0}\r\n", AllowAdjustHeightOffTerrain); objString += String.Format("\tWorldViewSelectable={0}", worldViewSelectable); objString += String.Format("\tPosition=({0},{1},{2})\r\n", position.x, position.y, position.z); objString += String.Format("\tOrientation=({0},{1},{2},{3})\r\n", orientation.w, orientation.x, orientation.y, orientation.z); objString += "\r\n"; return objString; } } [BrowsableAttribute(false)] public List<ToolStripButton> ButtonBar { get { return buttonBar; } } [BrowsableAttribute(false)] public bool InScene { get { return inScene; } } [CategoryAttribute("Miscellaneous"), BrowsableAttribute(true), DescriptionAttribute("Whether the object preserves the height above terrain when the terrain is changed or the object is dragged or pasted to another location.")] public bool AllowAdjustHeightOffTerrain { get { return allowAdjustHeightOffTerrain; } set { allowAdjustHeightOffTerrain = value; } } public void RemoveFromTree() { if (node != null && inTree) { if (node.IsSelected) { node.UnSelect(); } foreach (IWorldObject child in children) { child.RemoveFromTree(); } parentNode.Nodes.Remove(node); node = null; parentNode = null; inTree = false; } } public void CheckAssets() { if (!app.CheckAssetFileExists(app.Config.MarkerPointMeshName)) { app.AddMissingAsset(app.Config.MarkerPointMeshName); } string textureFile = "directional_marker_orange.dds"; if (!app.CheckAssetFileExists(textureFile)) { app.AddMissingAsset(textureFile); } string materialFile = "directional_marker.material"; if (!app.CheckAssetFileExists(materialFile)) { app.AddMissingAsset(materialFile); } foreach (IWorldObject child in children) { child.CheckAssets(); } } public void ToXml(XmlWriter w) { w.WriteStartElement("Waypoint"); w.WriteAttributeString("Name", name); //w.WriteAttributeString("Sound", soundAssetName); w.WriteAttributeString("TerrainOffset", terrainOffset.ToString()); w.WriteAttributeString("AllowHeightAdjustment", this.AllowAdjustHeightOffTerrain.ToString()); w.WriteAttributeString("WorldViewSelect", worldViewSelectable.ToString()); w.WriteAttributeString("Azimuth", azimuth.ToString()); w.WriteAttributeString("Zenith", zenith.ToString()); w.WriteStartElement("Position"); w.WriteAttributeString("x", Position.x.ToString()); w.WriteAttributeString("y", Position.y.ToString()); w.WriteAttributeString("z", Position.z.ToString()); w.WriteEndElement(); // Position end w.WriteStartElement("Orientation"); w.WriteAttributeString("x", Orientation.x.ToString()); w.WriteAttributeString("y", Orientation.y.ToString()); w.WriteAttributeString("z", Orientation.z.ToString()); w.WriteAttributeString("w", Orientation.w.ToString()); w.WriteEndElement(); // Orientation end if (customColor) { w.WriteStartElement("Color"); w.WriteAttributeString("R", this.color.r.ToString()); w.WriteAttributeString("G", this.color.g.ToString()); w.WriteAttributeString("B", this.color.b.ToString()); w.WriteEndElement(); // End Color } if (this.nameValuePairs != null && this.nameValuePairs.Count > 0) { nameValuePairs.ToXml(w); } foreach (IWorldObject child in children) { child.ToXml(w); } w.WriteEndElement(); // Waypoint end } public void ToManifest(System.IO.StreamWriter w) { if (children != null) { foreach (IWorldObject child in children) { child.ToManifest(w); } } } public void Dispose() { if (disp != null) { disp.Dispose(); disp = null; } } #region ICollection<IWorldObject> Members public void Add(IWorldObject item) { children.Add(item); if (inTree) { item.AddToTree(node); } if (item is ParticleEffect && app.DisplayParticleEffects && app.WorldRoot != null && !(parent is PasteFromClipboardCommand) && !(parent is ClipboardObject) && (parent as WorldObjectCollection).InScene) { item.AddToScene(); } else { if (inScene) { item.AddToScene(); } } } public void Clear() { children.Clear(); } public bool Contains(IWorldObject item) { return children.Contains(item as ParticleEffect); } public void CopyTo(IWorldObject[] array, int arrayIndex) { children.CopyTo(array, arrayIndex); } [BrowsableAttribute(false)] public int Count { get { return children.Count; } } [BrowsableAttribute(false)] public bool IsReadOnly { get { return false; } } public bool Remove(IWorldObject item) { if (inTree) { item.RemoveFromTree(); } if (inScene || (item is ParticleEffect && app.DisplayParticleEffects)) { item.RemoveFromScene(); } return children.Remove(item); } #endregion #region IEnumerable<IWorldObject> Members public IEnumerator<IWorldObject> GetEnumerator() { return children.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IOjbectDrag Members [BrowsableAttribute(false)] public DisplayObject Display { get { return disp; } } [DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")] public string ObjectType { get { return "Marker"; } } [BrowsableAttribute(false)] public float Radius { get { if (inScene && disp != null) { return disp.Radius; } else { return 0f; } } } [BrowsableAttribute(false)] public Vector3 Center { get { if (inScene && disp != null) { return Display.Center; } else { return Vector3.Zero; } } } [BrowsableAttribute(false)] public IWorldContainer Parent { get { return parent; } set { parent = value; } } #endregion IOjbectDrag Members #region IObjectOrientation Members [DescriptionAttribute("The Orientation of this marker in the world"), BrowsableAttribute(false)] public Quaternion Orientation { get { return orientation; } } public void SetDirection(float lightAzimuth, float lightZenith) { this.azimuth = lightAzimuth; this.zenith = lightZenith; UpdateOrientation(); } [BrowsableAttribute(false)] public float Azimuth { get { return azimuth; } set { azimuth = value; UpdateOrientation(); } } [BrowsableAttribute(false)] public float Zenith { get { return zenith; } set { zenith = value; UpdateOrientation(); } } protected void UpdateOrientation() { Quaternion azimuthRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(azimuth), Vector3.UnitY); Quaternion zenithRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(-zenith), Vector3.UnitX); Quaternion displayZenithRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(-Zenith + 90), Vector3.UnitX); orientation = azimuthRotation * displayZenithRotation; if (inScene) { this.disp.SetOrientation(orientation); } foreach (IWorldObject child in children) { if (child is ParticleEffect) { (child as ParticleEffect).Orientation = this.orientation; } } } #endregion IObjectOrientation Members public void SetCamera(Camera cam, CameraDirection dir) { AxisAlignedBox boundingBox = disp.BoundingBox; // find the size along the largest axis float size = Math.Max(Math.Max(boundingBox.Size.x, boundingBox.Size.y), boundingBox.Size.z); Vector3 dirVec; switch (dir) { default: case CameraDirection.Above: // for some reason axiom messes up the camera matrix when you point // the camera directly down, so this vector is ever so slightly off // from negative Y. dirVec = new Vector3(0.0001f, -1f, 0f); dirVec.Normalize(); break; case CameraDirection.North: dirVec = Vector3.UnitZ; break; case CameraDirection.South: dirVec = Vector3.NegativeUnitZ; break; case CameraDirection.West: dirVec = Vector3.UnitX; break; case CameraDirection.East: dirVec = Vector3.NegativeUnitX; break; } cam.Position = boundingBox.Center + (size * 2 * (-dirVec)); cam.Direction = dirVec; } } /// <summary> /// This class is used to hold a direction and object, and set a camera based on them. /// </summary> public class DirectionAndMarker { CameraDirection dir; Waypoint obj; public DirectionAndMarker(CameraDirection dir, Waypoint obj) { this.dir = dir; this.obj = obj; } public void SetCamera(Camera cam) { obj.SetCamera(cam, dir); } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.IO; using System.Reflection; using System.Text.RegularExpressions; [InitializeOnLoad] public class AkWwisePostImportCallbackSetup { static AkWwisePostImportCallbackSetup() { string[] arguments = Environment.GetCommandLineArgs(); if (Array.IndexOf(arguments, "-nographics") != -1 && Array.IndexOf(arguments, "-wwiseEnableWithNoGraphics") == -1) { return; } EditorApplication.delayCall += CheckMigrationStatus; } private static void CheckMigrationStatus() { try { int migrationStart; int migrationStop; bool returnToLauncher; if (IsMigrationPending(out migrationStart, out migrationStop, out returnToLauncher)) { m_scheduledMigrationStart = migrationStart; m_scheduledMigrationStop = migrationStop; m_scheduledReturnToLauncher = returnToLauncher; ScheduleMigration(); } else { RefreshCallback(); } } catch (Exception e) { Debug.LogError("WwiseUnity: Error during migration: " + e); } } private static int m_scheduledMigrationStart; private static int m_scheduledMigrationStop; private static bool m_scheduledReturnToLauncher; private static void ScheduleMigration() { // TODO: Is delayCall wiped out during a script reload? // If not, guard against having a delayCall from a previously loaded code being run after the new loading. if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling) { // Skip if not in the right mode, wait for the next callback to see if we can proceed then. EditorApplication.delayCall += ScheduleMigration; return; } try { WwiseSetupWizard.PerformMigration(m_scheduledMigrationStart, m_scheduledMigrationStop); // Force the user to return to the launcher to perform the post-installation process if necessary if (m_scheduledReturnToLauncher) { if (EditorUtility.DisplayDialog("Wwise Migration Successful!", "Please close Unity and go back to the Wwise Launcher to complete the installation.", "Quit")) { EditorApplication.Exit(0); } } else { EditorApplication.delayCall += RefreshCallback; } } catch (Exception e) { Debug.LogError("WwiseUnity: Error during migration: " + e); } } private static bool IsMigrationPending(out int migrationStart, out int migrationStop, out bool returnToLauncher) { migrationStart = 0; migrationStop = 0; returnToLauncher = false; string filename = Application.dataPath + "/../.WwiseLauncherLockFile"; if (!File.Exists(filename)) { return false; } string fileContent = File.ReadAllText(filename); // Instantiate the regular expression object. Regex r = new Regex("{\"migrateStart\":(\\d+),\"migrateStop\":(\\d+)(,\"returnToLauncher\":(true|false))?,.*}", RegexOptions.IgnoreCase); // Match the regular expression pattern against a text string. Match m = r.Match(fileContent); if (!m.Success || m.Groups.Count < 2 || m.Groups[1].Captures.Count < 1 || m.Groups[2].Captures.Count < 1 || !int.TryParse(m.Groups[1].Captures[0].ToString(), out migrationStart) || !int.TryParse(m.Groups[2].Captures[0].ToString(), out migrationStop)) { throw new Exception("Error in the file format of .WwiseLauncherLockFile."); } else { // Handle optional properties if (m.Groups.Count > 3 && m.Groups[4].Captures.Count > 0) { bool.TryParse(m.Groups[4].Captures[0].ToString(), out returnToLauncher); } } return true; } private static void RefreshCallback() { PostImportFunction(); if (File.Exists(Path.Combine(Application.dataPath, WwiseSettings.WwiseSettingsFilename))) { AkPluginActivator.Update(); AkPluginActivator.RefreshPlugins(); // Check if platform is supported and installed. PluginImporter might contain // erroneous data when application is compiling or updating, so skip this if // that is the case. if (!EditorApplication.isCompiling && !EditorApplication.isUpdating) { string Msg; if (!CheckPlatform(out Msg)) { EditorUtility.DisplayDialog("Warning", Msg, "OK"); } } } } private static void PostImportFunction() { EditorApplication.hierarchyWindowChanged += CheckWwiseGlobalExistance; EditorApplication.delayCall += CheckPicker; if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling) { return; } try { if (File.Exists(Application.dataPath + Path.DirectorySeparatorChar + WwiseSettings.WwiseSettingsFilename)) { WwiseSetupWizard.Settings = WwiseSettings.LoadSettings(); AkWwiseProjectInfo.GetData(); } if (!string.IsNullOrEmpty(WwiseSetupWizard.Settings.WwiseProjectPath)) { AkWwisePicker.PopulateTreeview(); if (AkWwiseProjectInfo.GetData().autoPopulateEnabled) { AkWwiseWWUBuilder.StartWWUWatcher(); } } } catch (Exception e) { Debug.Log(e.ToString()); } //Check if a WwiseGlobal object exists in the current scene CheckWwiseGlobalExistance(); } private static bool CheckPlatform(out string Msg) { Msg = string.Empty; #if UNITY_WSA_8_0 Msg = "The Wwise Unity integration does not support the Windows Store 8.0 SDK."; return false; #else // Start by checking if the integration supports the platform switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.PSM: case BuildTarget.SamsungTV: case BuildTarget.Tizen: case BuildTarget.WebGL: Msg = "The Wwise Unity integration does not support this platform."; return false; } // Then check if the integration is installed for this platform PluginImporter[] importers = PluginImporter.GetImporters(EditorUserBuildSettings.activeBuildTarget); bool found = false; foreach (PluginImporter imp in importers) { if (imp.assetPath.Contains("AkSoundEngine")) { found = true; break; } } if (!found) { Msg = "The Wwise Unity integration for the " + EditorUserBuildSettings.activeBuildTarget.ToString() + " platform is currently not installed."; return false; } return true; #endif } private static void RefreshPlugins() { if (string.IsNullOrEmpty(AkWwiseProjectInfo.GetData().CurrentPluginConfig)) { AkWwiseProjectInfo.GetData().CurrentPluginConfig = AkPluginActivator.CONFIG_PROFILE; } AkPluginActivator.RefreshPlugins(); } private static void ClearConsole() { #if UNITY_2017_1_OR_NEWER var logEntries = System.Type.GetType("UnityEditor.LogEntries,UnityEditor.dll"); #else var logEntries = System.Type.GetType("UnityEditorInternal.LogEntries,UnityEditor.dll"); #endif var clearMethod = logEntries.GetMethod("Clear", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); clearMethod.Invoke(null, null); } public static void CheckPicker() { if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling) { // Skip if not in the right mode, wait for the next callback to see if we can proceed then. EditorApplication.delayCall += CheckPicker; return; } WwiseSettings settings = WwiseSettings.LoadSettings(); if (!settings.CreatedPicker) { // Delete all the ghost tabs (Failed to load). EditorWindow[] windows = Resources.FindObjectsOfTypeAll<EditorWindow>(); if (windows != null && windows.Length > 0) { foreach (EditorWindow window in windows) { string windowTitle = window.titleContent.text; if (windowTitle.Equals("Failed to load") || windowTitle.Equals("AkWwisePicker")) { try { window.Close(); } catch (Exception) { // Do nothing here, this shoudn't cause any problem, however there has been // occurences of Unity crashing on a null reference inside that method. } } } } ClearConsole(); // TODO: If no scene is loaded and we are using the demo scene, automatically load it to display it. // Populate the picker AkWwiseProjectInfo.GetData(); // Load data if (!String.IsNullOrEmpty(settings.WwiseProjectPath)) { AkWwiseProjectInfo.Populate(); AkWwisePicker.init(); if (AkWwiseProjectInfo.GetData().autoPopulateEnabled) { AkWwiseWWUBuilder.StartWWUWatcher(); } settings.CreatedPicker = true; WwiseSettings.SaveSettings(settings); } } EditorApplication.delayCall += CheckPendingExecuteMethod; } // TODO: Put this in AkUtilities? private static void ExecuteMethod(string method) { string className = null; string methodName = null; Regex r = new Regex("(.+)\\.(.+)", RegexOptions.IgnoreCase); Match m = r.Match(method); if (!m.Success || m.Groups.Count < 3 || m.Groups[1].Captures.Count < 1 || m.Groups[2].Captures.Count < 1) { Debug.LogError("WwiseUnity: Error parsing wwiseExecuteMethod parameter: " + method); return; } className = m.Groups[1].Captures[0].ToString(); methodName = m.Groups[2].Captures[0].ToString(); try { Type type = System.Type.GetType(className); MethodInfo clearMethod = type.GetMethod(methodName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); clearMethod.Invoke(null, null); } catch (Exception e) { Debug.LogError("WwiseUnity: Exception caught when calling " + method + ": " + e.ToString()); } } private static bool m_pendingExecuteMethodCalled = false; private static void CheckPendingExecuteMethod() { string[] arguments = Environment.GetCommandLineArgs(); int indexOfCommand = Array.IndexOf(arguments, "-wwiseExecuteMethod"); if (!m_pendingExecuteMethodCalled && indexOfCommand != -1 && arguments.Length > (indexOfCommand + 1)) { string methodToExecute = arguments[indexOfCommand + 1]; ExecuteMethod(methodToExecute); m_pendingExecuteMethodCalled = true; } } private static string s_CurrentScene = null; // Called when changes are made to the scene and when a new scene is created. public static void CheckWwiseGlobalExistance() { WwiseSettings settings = WwiseSettings.LoadSettings(); string activeSceneName = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name; if (String.IsNullOrEmpty(s_CurrentScene) || !s_CurrentScene.Equals(activeSceneName)) { // Look for a game object which has the initializer component AkInitializer[] AkInitializers = UnityEngine.Object.FindObjectsOfType(typeof(AkInitializer)) as AkInitializer[]; if (AkInitializers.Length == 0) { if (settings.CreateWwiseGlobal == true) { //No Wwise object in this scene, create one so that the sound engine is initialized and terminated properly even if the scenes are loaded //in the wrong order. GameObject objWwise = new GameObject("WwiseGlobal"); //Attach initializer and terminator components AkInitializer init = objWwise.AddComponent<AkInitializer>(); AkWwiseProjectInfo.GetData().CopyInitSettings(init); } } else { if (settings.CreateWwiseGlobal == false && AkInitializers[0].gameObject.name == "WwiseGlobal") { GameObject.DestroyImmediate(AkInitializers[0].gameObject); } //All scenes will share the same initializer. So expose the init settings consistently across scenes. AkWwiseProjectInfo.GetData().CopyInitSettings(AkInitializers[0]); } if (Camera.main != null) { GameObject mainCameraGameObject = Camera.main.gameObject; AkAudioListener akListener = mainCameraGameObject.GetComponent<AkAudioListener>(); if (settings.CreateWwiseListener == true) { AudioListener listener = mainCameraGameObject.GetComponent<AudioListener>(); if (listener != null) Component.DestroyImmediate(listener); // Add the AkAudioListener script if (akListener == null) { akListener = mainCameraGameObject.AddComponent<AkAudioListener>(); AkGameObj akGameObj = akListener.GetComponent<AkGameObj>(); akGameObj.isEnvironmentAware = false; Debug.LogWarning("Automatically added AkAudioListener to Main Camera. Go to \"Edit > Wwise Settings...\" to disable this functionality."); } } } s_CurrentScene = activeSceneName; } } } #endif // UNITY_EDITOR
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; 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 Vevo; using Vevo.Domain.Shipping; using Vevo.Domain; using Vevo.Domain.DataInterfaces; using Vevo.Shared.Utilities; using Vevo.WebUI.Ajax; using Vevo.Base.Domain; public partial class AdminAdvanced_MainControls_ShippingOrderTotalRate : AdminAdvancedBaseUserControl { private string ShippingID { get { if (!String.IsNullOrEmpty( MainContext.QueryString["ShippingID"] )) return MainContext.QueryString["ShippingID"]; else return "0"; } } private GridViewHelper GridHelper { get { if (ViewState["GridHelper"] == null) ViewState["GridHelper"] = new GridViewHelper( uxGrid, "ToOrderTotal" ); return (GridViewHelper) ViewState["GridHelper"]; } } private void RefreshGrid() { int totalItems = 0; IList<ShippingOrderTotalRate> shippingOrderTotalRateList = DataAccessContext.ShippingOrderTotalRateRepository.SearchShippingOrderTotalRateItem( ShippingID, GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, uxPagingControl.StartIndex, uxPagingControl.EndIndex, out totalItems ); if (shippingOrderTotalRateList == null || shippingOrderTotalRateList.Count == 0) { shippingOrderTotalRateList = new List<ShippingOrderTotalRate>(); CreateDummyRow( shippingOrderTotalRateList ); } uxGrid.DataSource = shippingOrderTotalRateList; uxGrid.DataBind(); uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); } private void PopulateControls() { if (ShippingID == "0") MainContext.RedirectMainControl( "ShippingList.ascx" ); if (!MainContext.IsPostBack) { RefreshGrid(); } } private void ApplyPermissions() { if (!IsAdminModifiable()) { uxAddButton.Visible = false; DeleteVisible( false ); } else DeleteVisible( true ); } private void DeleteVisible( bool value ) { uxDeleteButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDeleteConfirmButton.TargetControlID = "uxDeleteButton"; uxConfirmModalPopup.TargetControlID = "uxDeleteButton"; } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void CreateDummyRow( IList<ShippingOrderTotalRate> list ) { ShippingOrderTotalRate shippingOrderTotalRate = new ShippingOrderTotalRate(); shippingOrderTotalRate.ShippingOrderTotalRateID = "-1"; shippingOrderTotalRate.ShippingID = ShippingID; shippingOrderTotalRate.ToOrderTotal = 0; shippingOrderTotalRate.OrderTotalRate = 0; list.Add( shippingOrderTotalRate ); } private bool IsContainingOnlyEmptyRow() { if (uxGrid.Rows.Count == 1 && ConvertUtilities.ToInt32( uxGrid.DataKeys[0]["ShippingOrderTotalRateID"] ) == -1) return true; else return false; } protected void Page_Load( object sender, EventArgs e ) { uxSearchFilter.BubbleEvent += new EventHandler( uxGrid_ResetHandler ); uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_RefreshHandler ); if (!MainContext.IsPostBack) { SetUpSearchFilter(); } } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); ApplyPermissions(); } private void uxGrid_ResetHandler( object sender, EventArgs e ) { uxPagingControl.CurrentPage = 1; RefreshGrid(); } private void uxPagingControl_RefreshHandler( object sender, EventArgs e ) { RefreshGrid(); } private void SetFooterRowFocus() { Control textBox = uxGrid.FooterRow.FindControl( "uxToOrderTotalText" ); AjaxUtilities.GetScriptManager( this ).SetFocus( textBox ); } protected void uxEditLinkButton_PreRender( object sender, EventArgs e ) { if (!IsAdminModifiable()) { LinkButton linkButton = (LinkButton) sender; linkButton.Visible = false; } } protected void uxGrid_DataBound( object sender, EventArgs e ) { if (IsContainingOnlyEmptyRow()) { uxGrid.Rows[0].Visible = false; } } protected void uxAddButton_Click( object sender, EventArgs e ) { uxGrid.EditIndex = -1; uxGrid.ShowFooter = true; RefreshGrid(); uxAddButton.Visible = false; SetFooterRowFocus(); uxStatusHidden.Value = "FooterShown"; } private void ClearData( GridViewRow row ) { ((TextBox) row.FindControl( "uxToOrderTotalText" )).Text = ""; ((TextBox) row.FindControl( "uxShippingOrderTotalRate" )).Text = ""; } private ShippingOrderTotalRate GetDetailsFromGrid( GridViewRow row, ShippingOrderTotalRate shippingOrderTotalRate ) { shippingOrderTotalRate.ShippingID = ShippingID; string toOrderTotalText = ((TextBox) row.FindControl( "uxToOrderTotalText" )).Text; shippingOrderTotalRate.ToOrderTotal = ConvertUtilities.ToDecimal ( toOrderTotalText ); string shippingOrderTotalRateText = ((TextBox) row.FindControl( "uxShippingOrderTotalRate" )).Text; shippingOrderTotalRate.OrderTotalRate = ConvertUtilities.ToDecimal( shippingOrderTotalRateText ); return shippingOrderTotalRate; } private bool IsCorrectFormatForShippingByOrderTotal( GridViewRow row ) { string toOrderTotalText = ((TextBox) row.FindControl( "uxToOrderTotalText" )).Text; Decimal ToOrderTotal = ConvertUtilities.ToDecimal( toOrderTotalText ); if (ToOrderTotal < 0) return false; string shippingOrderTotalRateText = ((TextBox) row.FindControl( "uxShippingOrderTotalRate" )).Text; Decimal OrderTotalRate = ConvertUtilities.ToDecimal( shippingOrderTotalRateText ); if (OrderTotalRate < 0) return false; return true; } private bool IsExisted( object addToOrderTotal ) { bool isExisted = false; IList<ShippingOrderTotalRate> shippingOrderTotalRateList = DataAccessContext.ShippingOrderTotalRateRepository.GetAllByShippingID( ShippingID, "ToOrderTotal" ); for (int i = 0; i < shippingOrderTotalRateList.Count; i++) { if (shippingOrderTotalRateList[i].ToOrderTotal == ConvertUtilities.ToDecimal( addToOrderTotal )) isExisted = true; } return isExisted; } protected void uxGrid_RowCommand( object sender, GridViewCommandEventArgs e ) { if (e.CommandName == "Add") { GridViewRow rowAdd = uxGrid.FooterRow; if (IsCorrectFormatForShippingByOrderTotal( rowAdd ) == false) { uxStatusHidden.Value = "Error"; uxMessage.DisplayError( Resources.ShippingOrderTotalRateMessage.TofewError ); return; } ShippingOrderTotalRate shippingOrderTotalRate = new ShippingOrderTotalRate(); shippingOrderTotalRate = GetDetailsFromGrid( rowAdd, shippingOrderTotalRate ); if (!IsExisted( shippingOrderTotalRate.ToOrderTotal )) { if (shippingOrderTotalRate.ToOrderTotal <= SystemConst.UnlimitedNumberDecimal) { DataAccessContext.ShippingOrderTotalRateRepository.Save( shippingOrderTotalRate ); ClearData( rowAdd ); RefreshGrid(); uxStatusHidden.Value = "Added"; uxMessage.DisplayMessage( Resources.ShippingOrderTotalRateMessage.ItemAddSuccess ); } else uxMessage.DisplayError( Resources.ShippingOrderTotalRateMessage.TomuchItemError ); } else { uxStatusHidden.Value = "Error"; uxMessage.DisplayError( Resources.ShippingOrderTotalRateMessage.ToOrderTotalError ); } } else if (e.CommandName == "Edit") { uxGrid.ShowFooter = false; uxAddButton.Visible = true; } } protected void uxGrid_RowEditing( object sender, GridViewEditEventArgs e ) { uxGrid.EditIndex = e.NewEditIndex; RefreshGrid(); } protected void uxGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e ) { uxGrid.EditIndex = -1; RefreshGrid(); } protected void uxDeleteButton_Click( object sender, EventArgs e ) { try { bool deleted = false; foreach (GridViewRow row in uxGrid.Rows) { CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" ); if (deleteCheck != null && deleteCheck.Checked) { string shippingOrderTotalRateID = uxGrid.DataKeys[row.RowIndex]["ShippingOrderTotalRateID"].ToString(); DataAccessContext.ShippingOrderTotalRateRepository.Delete( shippingOrderTotalRateID ); deleted = true; } } uxGrid.EditIndex = -1; if (deleted) uxMessage.DisplayMessage( Resources.ShippingOrderTotalRateMessage.ItemDeleteSuccess ); uxStatusHidden.Value = "Deleted"; } catch (Exception ex) { uxMessage.DisplayException( ex ); } RefreshGrid(); if (uxGrid.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages) { uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages; RefreshGrid(); } } protected void uxGrid_RowUpdating( object sender, GridViewUpdateEventArgs e ) { try { GridViewRow rowGrid = uxGrid.Rows[e.RowIndex]; if (IsCorrectFormatForShippingByOrderTotal( rowGrid ) == false) { uxStatusHidden.Value = "Error"; uxMessage.DisplayError( Resources.ShippingOrderTotalRateMessage.TofewError ); return; } string shippingOrderTotalRateID = uxGrid.DataKeys[e.RowIndex]["ShippingOrderTotalRateID"].ToString(); ShippingOrderTotalRate shippingOrderTotalRate = DataAccessContext.ShippingOrderTotalRateRepository.GetOne( shippingOrderTotalRateID ); shippingOrderTotalRate = GetDetailsFromGrid( rowGrid, shippingOrderTotalRate ); DataAccessContext.ShippingOrderTotalRateRepository.Save( shippingOrderTotalRate ); uxGrid.EditIndex = -1; RefreshGrid(); uxStatusHidden.Value = "Updated"; uxMessage.DisplayMessage( Resources.ShippingOrderTotalRateMessage.ItemUpdateSuccess ); } finally { e.Cancel = true; } } private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContext.ShippingOrderTotalRateRepository.GetTableSchema(); uxSearchFilter.SetUpSchema( list, "ShippingOrderTotalRateID", "ShippingID", "ToOrderTotal" ); } public string ShowFromOrderTotal( object toOrderTotal ) { decimal fromOrderTotal = 0; IList<ShippingOrderTotalRate> shippingOrderTotalRateList = DataAccessContext.ShippingOrderTotalRateRepository.GetAllByShippingID( ShippingID, "ToOrderTotal" ); for (int i = 0; i < shippingOrderTotalRateList.Count; i++) { if (shippingOrderTotalRateList[i].ToOrderTotal == ConvertUtilities.ToDecimal( toOrderTotal )) break; else fromOrderTotal = shippingOrderTotalRateList[i].ToOrderTotal; } if (fromOrderTotal == 0) return String.Format( "{0:f2}", fromOrderTotal ); else return String.Format( "> {0:f2}", fromOrderTotal ); } public bool CheckVisibleFromToOrderTotal( string toOrderTotal ) { if (toOrderTotal == SystemConst.UnlimitedNumberDecimal.ToString()) return false; else return true; } public string LastToOrderTotal( string toOrderTotal ) { if (toOrderTotal == SystemConst.UnlimitedNumberDecimal.ToString()) return "Above"; else return toOrderTotal; } protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e ) { GridHelper.SelectSorting( e.SortExpression ); RefreshGrid(); } }
using System; using System.Collections; using System.ComponentModel; using xmljr.math; namespace Demo { public enum Awe { a, b, c } public class EnumInt_Awe { public static int e2i(Awe x) { if(x==Awe.a) return 0; if(x==Awe.b) return 1; if(x==Awe.c) return 2; return 0; } public static Awe i2e(int x) { if(x==0) return Awe.a; if(x==1) return Awe.b; if(x==2) return Awe.c; return Awe.a; } } public enum Ness { x, y, z } public class EnumInt_Ness { public static int e2i(Ness x) { if(x==Ness.x) return 3; if(x==Ness.y) return 4; if(x==Ness.z) return 5; return 3; } public static Ness i2e(int x) { if(x==3) return Ness.x; if(x==4) return Ness.y; if(x==5) return Ness.z; return Ness.x; } } public class Store { public Int32 _h = 0; public Int32 h { get { return _h; } set { _h = value; } } public Awe _ho; public Awe ho { get { return _ho; } set { _ho = value; } } public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src) { int __idx = 0; int __size = 0; foreach(xmljr.XmlJrDom __C in __src._Children) { if(__C._Name.Equals("h")) { _h = __C.read_int(); } if(__C._Name.Equals("ho")) { _ho = EnumInt_Awe.i2e(__C.read_int()); } } } public virtual int WriteXML(xmljr.XmlJrWriter __XW) { int __idx = 0; int __testaddr = __XW.Exist(this); if(__testaddr > 0) return __testaddr; xmljr.XmlJrBuffer _XB = __XW.NewObject("Store",this); _XB.write_long("h",_h); _XB.write_int("ho",EnumInt_Awe.e2i(_ho)); _XB.finish(); return _XB._Addr; } } public class Kate : Store { public Int32 _z = 0; public Int32 z { get { return _z; } set { _z = value; } } public override void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src) { int __idx = 0; int __size = 0; foreach(xmljr.XmlJrDom __C in __src._Children) { if(__C._Name.Equals("h")) { _h = __C.read_int(); } if(__C._Name.Equals("ho")) { _ho = EnumInt_Awe.i2e(__C.read_int()); } if(__C._Name.Equals("z")) { _z = __C.read_int(); } } } public override int WriteXML(xmljr.XmlJrWriter __XW) { int __idx = 0; int __testaddr = __XW.Exist(this); if(__testaddr > 0) return __testaddr; xmljr.XmlJrBuffer _XB = __XW.NewObject("Kate",this); _XB.write_long("h",_h); _XB.write_int("ho",EnumInt_Awe.e2i(_ho)); _XB.write_long("z",_z); _XB.finish(); return _XB._Addr; } } public class Test { public Kate _S = null; public Kate S { get { return _S; } set { _S = value; } } public Int32[] _x = new Int32[0]; public Int32[] x { get { return _x; } set { _x = value; } } public void Resize_x(int __Size) { Int32[] __nx = new Int32[__Size]; if(_x==null) { _x=__nx;return; } for(uint __k = 0; __k < Math.Min(__Size,_x.Length);__k++) { __nx[__k]=_x[__k]; } _x=__nx; } public void Sort_x() { if(_x==null) { return; } ArrayList __L = new ArrayList(); for(int __k = 0; __k < _x.Length;__k++) __L.Add(_x[__k]); __L.Sort(); for(int __k = 0; __k < _x.Length;__k++) _x[__k] = (Int32)__L[__k]; } public float _a = 0.0f; public float a { get { return _a; } set { _a = value; } } public string _b = ""; public string b { get { return _b; } set { _b = value; } } public double _c = 0.0; public double c { get { return _c; } set { _c = value; } } public float[] _y = new float[0]; public float[] y { get { return _y; } set { _y = value; } } public void Resize_y(int __Size) { float[] __nx = new float[__Size]; if(_y==null) { _y=__nx;return; } for(uint __k = 0; __k < Math.Min(__Size,_y.Length);__k++) { __nx[__k]=_y[__k]; } _y=__nx; } public void Sort_y() { if(_y==null) { return; } ArrayList __L = new ArrayList(); for(int __k = 0; __k < _y.Length;__k++) __L.Add(_y[__k]); __L.Sort(); for(int __k = 0; __k < _y.Length;__k++) _y[__k] = (float)__L[__k]; } public char _d = '\0'; public char d { get { return _d; } set { _d = value; } } public Vector4 _v = new Vector4(); public Vector4 v { get { return _v; } set { _v = value; } } public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src) { int __idx = 0; int __size = 0; foreach(xmljr.XmlJrDom __C in __src._Children) { if(__C._Name.Equals("S")) { _S = (Kate) __table.LookUpObject(__C.read_int()); } if(__C._Name.Equals("x")) { _x = new Int32[__C.GetIntParam("size")]; __idx = 0; foreach(xmljr.XmlJrDom __SUB in __C._Children) { _x[__idx]=__SUB.read_int(); __idx++; } } if(__C._Name.Equals("a")) { _a = __C.read_float(); } if(__C._Name.Equals("b")) { _b = __C.read_string(); } if(__C._Name.Equals("c")) { _c = __C.read_double(); } if(__C._Name.Equals("y")) { _y = new float[__C.GetIntParam("size")]; __idx = 0; foreach(xmljr.XmlJrDom __SUB in __C._Children) { _y[__idx]=__SUB.read_float(); __idx++; } } if(__C._Name.Equals("d")) { _d = __C.read_char(); } if(__C._Name.Equals("v")) { _v = __C.read_Vector4(); } } } public virtual int WriteXML(xmljr.XmlJrWriter __XW) { int __idx = 0; int __testaddr = __XW.Exist(this); if(__testaddr > 0) return __testaddr; xmljr.XmlJrBuffer _XB = __XW.NewObject("Test",this); if(_S != null) _XB.write_addr("S",_S.WriteXML(__XW));; if(_x==null) { _XB.write_array("x",0); _XB.finish_array("x"); } else { _XB.write_array("x",_x.Length); for(__idx = 0 ; __idx < _x.Length; __idx++) { _XB.write_long("r",_x[__idx]); } _XB.finish_array("x"); } _XB.write_float("a",_a); _XB.write_string("b",_b); _XB.write_double("c",_c); if(_y==null) { _XB.write_array("y",0); _XB.finish_array("y"); } else { _XB.write_array("y",_y.Length); for(__idx = 0 ; __idx < _y.Length; __idx++) { _XB.write_float("r",_y[__idx]); } _XB.finish_array("y"); } _XB.write_char("d",_d); _XB.write_Vector4("v",_v); _XB.finish(); return _XB._Addr; } } public class Demo { public static xmljr.XmlJrObjectTable BuildObjectTable(xmljr.XmlJrDom root, xmljr.ProgressNotify note) { xmljr.XmlJrObjectTable __table = new xmljr.XmlJrObjectTable(); foreach(xmljr.XmlJrDom obj in root._Children) { int __addr = obj.GetAddr(); if(__addr >= 0) { Object __o = null; if(obj._Name.Equals("Store")) __o = new Store(); else if(obj._Name.Equals("Kate")) __o = new Kate(); else if(obj._Name.Equals("Test")) __o = new Test(); if(__o!=null) __table.Map(__addr,__o); } } foreach(xmljr.XmlJrDom obj in root._Children) { int __addr = obj.GetAddr(); if(__addr >= 0) { Object __o = __table.LookUpObject(__addr); if(obj._Name.Equals("Store")) ((Store) __o).ReadDetailsXML(__table, obj); else if(obj._Name.Equals("Kate")) ((Kate) __o).ReadDetailsXML(__table, obj); else if(obj._Name.Equals("Test")) ((Test) __o).ReadDetailsXML(__table, obj); } } return __table; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ServiceFabricManagedClusters.Tests { using System; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.ServiceFabricManagedClusters; using Microsoft.Azure.Management.ServiceFabricManagedClusters.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; public class ApplicationTests : ServiceFabricManagedTestBase { internal const string Location = "South Central US"; internal const string ResourceGroupPrefix = "sfmc-net-sdk-app-rg-"; internal const string ClusterNamePrefix = "sfmcnetsdk"; private const string AppName = "Voting"; private const string AppTypeVersionName = "1.0.0"; private const string AppTypeName = "VotingType"; private const string AppPackageUrl = "https://sfmconeboxst.blob.core.windows.net/managed-application-deployment/Voting.sfpkg"; private const string StatefulServiceName = "VotingData"; private const string StatefulServiceTypeName = "VotingDataType"; [Fact] public void AppCreateDeleteTest() { using (MockContext context = MockContext.Start(this.GetType())) { var serviceFabricMcClient = GetServiceFabricMcClient(context); var resourceClient = GetResourceManagementClient(context); var resourceGroupName = TestUtilities.GenerateName(ResourceGroupPrefix); var clusterName = TestUtilities.GenerateName(ClusterNamePrefix); var nodeTypeName = TestUtilities.GenerateName("nt"); var cluster = this.CreateManagedCluster(resourceClient, serviceFabricMcClient, resourceGroupName, Location, clusterName, sku: SkuName.Basic); cluster = serviceFabricMcClient.ManagedClusters.Get(resourceGroupName, clusterName); Assert.NotNull(cluster); var primaryNodeType = this.CreateNodeType(serviceFabricMcClient, resourceGroupName, clusterName, nodeTypeName, isPrimary: true, vmInstanceCount: 6); this.WaitForClusterReadyState(serviceFabricMcClient, resourceGroupName, clusterName); CreateAppType(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppTypeName); var appTypeVersion = CreateAppTypeVersion(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppTypeName, AppTypeVersionName, AppPackageUrl); CreateApplication(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppName, appTypeVersion.Id); CreateService(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppName, StatefulServiceTypeName, StatefulServiceName); DeleteApplication(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppName); DeleteAppType(serviceFabricMcClient, resourceGroupName, clusterName, cluster.ClusterId, AppTypeName); } } private void CreateAppType( ServiceFabricManagedClustersManagementClient serviceFabricMcClient, string resourceGroup, string clusterName, string clusterId, string appTypeName) { var appTypeResourceId = $"{clusterId}/applicationTypes/{appTypeName}"; var appTypeParams = new ApplicationTypeResource( name: appTypeName, location: Location, id: appTypeResourceId); var appTypeResult = serviceFabricMcClient.ApplicationTypes.CreateOrUpdate( resourceGroup, clusterName, appTypeName, appTypeParams); Assert.Equal("Succeeded", appTypeResult.ProvisioningState); } private ApplicationTypeVersionResource CreateAppTypeVersion( ServiceFabricManagedClustersManagementClient serviceFabricMcClient, string resourceGroup, string clusterName, string clusterId, string appTypeName, string appTypeVersionName, string appPackageUrl) { var appTypeVersionResourceId = $"{clusterId}/applicationTypes/{appTypeName}/versions/{appTypeVersionName}"; var appTypeVersionParams = new ApplicationTypeVersionResource( name: AppTypeVersionName, location: Location, id: appTypeVersionResourceId, appPackageUrl: appPackageUrl); var appTypeVersionResult = serviceFabricMcClient.ApplicationTypeVersions.CreateOrUpdate( resourceGroup, clusterName, appTypeName, appTypeVersionName, appTypeVersionParams); Assert.Equal("Succeeded", appTypeVersionResult.ProvisioningState); Assert.Equal(appPackageUrl, appTypeVersionResult.AppPackageUrl); return appTypeVersionResult; } private void CreateApplication( ServiceFabricManagedClustersManagementClient serviceFabricMcClient, string resourceGroup, string clusterName, string clusterId, string appName, string versionResourceId) { var applicationResourceId = $"{clusterId}/applications/{appName}"; var applicationParams = new ApplicationResource( name: appName, location: Location, id: applicationResourceId, version: versionResourceId, upgradePolicy: new ApplicationUpgradePolicy(recreateApplication: true)); var applicationResult = serviceFabricMcClient.Applications.CreateOrUpdate( resourceGroup, clusterName, appName, applicationParams); Assert.Equal("Succeeded", applicationResult.ProvisioningState); Assert.True(applicationResult.UpgradePolicy.RecreateApplication); Assert.Equal(versionResourceId, applicationResult.Version); } private void CreateService( ServiceFabricManagedClustersManagementClient serviceFabricMcClient, string resourceGroup, string clusterName, string clusterId, string appName, string serviceTypeName, string serviceName) { var serviceResourceId = $"{clusterId}/applications/{appName}/services/{serviceName}"; var count = 1; var lowKey = 0; var highKey = 25; var targetReplicaSetSize = 5; var minReplicaSetSize = 3; var serviceParams = new ServiceResource( name: serviceName, location: Location, id: serviceResourceId, properties: new StatefulServiceProperties( serviceTypeName: serviceTypeName, partitionDescription: new UniformInt64RangePartitionScheme( count: count, lowKey: lowKey, highKey: highKey), hasPersistedState: true, targetReplicaSetSize: targetReplicaSetSize, minReplicaSetSize: minReplicaSetSize)); var serviceResult = serviceFabricMcClient.Services.CreateOrUpdate( resourceGroup, clusterName, appName, serviceName, serviceParams); Assert.Equal("Succeeded", serviceResult.Properties.ProvisioningState); Assert.IsAssignableFrom<StatefulServiceProperties>(serviceResult.Properties); var serviceProperties = serviceResult.Properties as StatefulServiceProperties; Assert.Equal("VotingDataType", serviceResult.Properties.ServiceTypeName); Assert.IsAssignableFrom<UniformInt64RangePartitionScheme>(serviceResult.Properties.PartitionDescription); var partitionDescription = serviceProperties.PartitionDescription as UniformInt64RangePartitionScheme; Assert.Equal(count, partitionDescription.Count); Assert.Equal(lowKey, partitionDescription.LowKey); Assert.Equal(highKey, partitionDescription.HighKey); Assert.True(serviceProperties.HasPersistedState); Assert.Equal(targetReplicaSetSize, serviceProperties.TargetReplicaSetSize); Assert.Equal(minReplicaSetSize, serviceProperties.MinReplicaSetSize); } private void DeleteApplication( ServiceFabricManagedClustersManagementClient serviceFabricMcClient, string resourceGroup, string clusterName, string clusterId, string appName) { var deleteStartTime = DateTime.UtcNow; var applicationResourceId = $"{clusterId}/applications/{appName}"; serviceFabricMcClient.Applications.Delete( resourceGroup, clusterName, appName); var ex = Assert.ThrowsAsync<ErrorModelException>( () => serviceFabricMcClient.Applications.GetAsync(resourceGroup, clusterName, appName)).Result; Assert.True(ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound); } private void DeleteAppType( ServiceFabricManagedClustersManagementClient serviceFabricMcClient, string resourceGroup, string clusterName, string clusterId, string appTypeName) { var appTypeResourceId = $"{clusterId}/applicationTypes/{appTypeName}"; serviceFabricMcClient.ApplicationTypes.Delete( resourceGroup, clusterName, appTypeName); var ex = Assert.ThrowsAsync<ErrorModelException>( () => serviceFabricMcClient.ApplicationTypes.GetAsync(resourceGroup, clusterName, appTypeName)).Result; Assert.True(ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound); } } }
// ------------------------------------- // Domain : IBT / Realtime.co // Author : Nicholas Ventimiglia // Product : Messaging and Storage // Published : 2014 // ------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Foundation.Debuging; using Realtime.Ortc; using Realtime.Ortc.Api; using UnityEngine; namespace Realtime.Demos { /// <summary> /// Demo Client using the Ortc CLient /// </summary> [AddComponentMenu("Realtime/Demos/OrtcExampleScene")] public class OrtcExampleScene : MonoBehaviour { protected const string OrtcDisconnected = "ortcClientDisconnected"; protected const string OrtcConnected = "ortcClientConnected"; protected const string OrtcSubscribed = "ortcClientSubscribed"; protected const string OrtcUnsubscribed = "ortcClientUnsubscribed"; /// <summary> /// /// </summary> public string URL = "http://ortc-developers.realtime.co/server/2.1"; /// <summary> /// /// </summary> public string URLSSL = "https://ortc-developers.realtime.co/server/ssl/2.1"; /// <summary> /// Identifies the client. /// </summary> public string ClientMetaData = "UnityClient1"; /// <summary> /// Identities your channel group /// </summary> public string ApplicationKey = ""; /// <summary> /// Send / Subscribe channel /// </summary> public string Channel = "myChannel"; /// <summary> /// Message Content /// </summary> public string Message = "This is my message"; /// <summary> /// 15 second inactivity check /// </summary> public bool Heartbeat = false; /// <summary> /// For dedicated servers /// </summary> public bool ClientIsCluster = true; /// <summary> /// Automatic reconnection /// </summary> public bool EnableReconnect = true; #region auth settings // Note : this section should really be handled on a webserver you control. It is here only as education. /// <summary> /// Important /// Dont publish your app with this. /// This will allow users to authenticate themselves. /// Authentication should take place on your authentication server /// </summary> public string PrivateKey = ""; /// <summary> /// Approved channels /// </summary> public string[] AuthChannels = { "myChannel" }; /// <summary> /// Permission /// </summary> public ChannelPermissions[] AuthPermission = { ChannelPermissions.Presence, ChannelPermissions.Read, ChannelPermissions.Write }; /// <summary> /// The token that the client uses to access the Pub/Sub network /// </summary> public string AuthToken = "UnityClient1"; /// <summary> /// Only one connection can use this token since it's private for each user /// </summary> public bool AuthTokenIsPrivate = false; /// <summary> /// Time to live. Expiration of the authentication token. /// </summary> public int AuthTTL = 1400; #endregion private IOrtcClient _ortc; void Awake() { UnityOrtcStartup.ConfigureOrtc(); } protected void Start() { LoadFactory(); LoadCommands(); } void ReadText(string text) { if (text.StartsWith(".")) { ClientMetaData = text.Replace(".", ""); _ortc.ConnectionMetadata = ClientMetaData; Terminal.LogImportant("Name set to " + ClientMetaData); } else { if (!_ortc.IsConnected) { Debug.LogError("Not Connected"); } else { Message = string.Format("{0} : {1}", ClientMetaData, text); Send(); } } } protected void OnApplicationPause(bool isPaused) { if (_ortc != null && _ortc.IsConnected) _ortc.Disconnect(); } void LoadCommands() { Terminal.Add(new TerminalInterpreter { Label = "Chat", Method = ReadText }); Terminal.Add(new TerminalCommand { Label = "Connect", Method = () => StartCoroutine(Connect()) }); Terminal.Add(new TerminalCommand { Label = "ConnectSSL", Method = () => StartCoroutine(ConnectSSL()) }); Terminal.Add(new TerminalCommand { Label = "Disconnect", Method = Disconnect }); // Terminal.Add(new TerminalCommand { Label = "Subscribe", Method = Subscribe }); Terminal.Add(new TerminalCommand { Label = "Unsubscribe", Method = Unsubscribe }); Terminal.Add(new TerminalCommand { Label = "Send", Method = Send }); Terminal.Add(new TerminalCommand { Label = "Subscribe SubChannels", Method = SubscribeeSubs }); Terminal.Add(new TerminalCommand { Label = "Unsubscribe SubChannels", Method = UnsubscribeSubs }); Terminal.Add(new TerminalCommand { Label = "Auth", Method = () => StartCoroutine(Auth()) }); // Terminal.Add(new TerminalCommand { Label = "EnablePresence", Method = () => StartCoroutine(EnablePresence()) }); Terminal.Add(new TerminalCommand { Label = "DisablePresense", Method = () => StartCoroutine(DisablePresence()) }); Terminal.Add(new TerminalCommand { Label = "Presence", Method = () => StartCoroutine(RequestPresence()) }); // } private void LoadFactory() { try { // Construct object _ortc = OrtcFactory.Create(); if (_ortc != null) { //_ortc.ConnectionTimeout = 10000; // Handlers _ortc.OnConnected += ortc_OnConnected; _ortc.OnDisconnected += ortc_OnDisconnected; _ortc.OnReconnecting += ortc_OnReconnecting; _ortc.OnReconnected += ortc_OnReconnected; _ortc.OnSubscribed += ortc_OnSubscribed; _ortc.OnUnsubscribed += ortc_OnUnsubscribed; _ortc.OnException += ortc_OnException; Terminal.LogInput("Ortc Ready"); } } catch (Exception ex) { Debug.LogException(ex); Debug.LogException(ex.InnerException); } if (_ortc == null) { Terminal.LogError("ORTC object is null"); } } #region methods private void Log(string text) { var dt = DateTime.Now; const string datePatt = @"HH:mm:ss"; Terminal.Log(String.Format("{0}: {1}", dt.ToString(datePatt), text)); } IEnumerator Auth() { Log("Posting permissions..."); yield return 1; var perms = new Dictionary<string, List<ChannelPermissions>>(); foreach (var authChannel in AuthChannels) { perms.Add(authChannel, AuthPermission.ToList()); } AuthenticationClient.PostAuthentication(URLSSL, ClientIsCluster, AuthToken, AuthTokenIsPrivate, ApplicationKey, AuthTTL, PrivateKey, perms, (exception, s) => { if (exception) Terminal.LogError("Unable to post permissions"); else Log("Permissions posted"); }); } IEnumerator Connect() { yield return 1; // Update URL with user entered text if (ClientIsCluster) { _ortc.ClusterUrl = URL; } else { _ortc.Url = URL; } _ortc.ConnectionMetadata = ClientMetaData; _ortc.HeartbeatActive = Heartbeat; _ortc.EnableReconnect = EnableReconnect; Log(String.Format("Connecting to: {0}...", URL)); _ortc.Connect(ApplicationKey, AuthToken); } IEnumerator ConnectSSL() { yield return 1; // Update URL with user entered text if (ClientIsCluster) { _ortc.ClusterUrl = URLSSL; } else { _ortc.Url = URLSSL; } _ortc.ConnectionMetadata = ClientMetaData; _ortc.HeartbeatActive = Heartbeat; _ortc.EnableReconnect = EnableReconnect; Log(String.Format("Connecting to: {0}...", URLSSL)); _ortc.Connect(ApplicationKey, AuthToken); } void Disconnect() { Log("Disconnecting..."); _ortc.Disconnect(); } void Subscribe() { Log(String.Format("Subscribing to: {0}...", Channel)); _ortc.Subscribe(Channel, true, OnMessageCallback); } void Unsubscribe() { Log(String.Format("Unsubscribing from: {0}...", Channel)); _ortc.Unsubscribe(Channel); } void SubscribeeSubs() { Log(String.Format("Subscribing to: {0}...", "Subchannels")); _ortc.Subscribe(OrtcConnected, true, OnMessageCallback); _ortc.Subscribe(OrtcDisconnected, true, OnMessageCallback); _ortc.Subscribe(OrtcSubscribed, true, OnMessageCallback); _ortc.Subscribe(OrtcUnsubscribed, true, OnMessageCallback); } void UnsubscribeSubs() { Log(String.Format("Unsubscribing from: {0}...", "Subchannels")); _ortc.Unsubscribe(OrtcConnected); _ortc.Unsubscribe(OrtcDisconnected); _ortc.Unsubscribe(OrtcSubscribed); _ortc.Unsubscribe(OrtcUnsubscribed); } IEnumerator RequestPresence() { yield return 1; PresenceClient.GetPresence(URLSSL, ClientIsCluster, ApplicationKey, AuthToken, Channel, (exception, presence) => { if (exception) { Terminal.LogError(String.Format("Error: {0}", exception.Message)); } else { var result = presence; Log(String.Format("Subscriptions {0}", result.Subscriptions)); if (result.Metadata != null) { foreach (var metadata in result.Metadata) { Log(metadata.Key + " - " + metadata.Value); } } } }); } IEnumerator EnablePresence() { yield return 1; PresenceClient.EnablePresence(URLSSL, ClientIsCluster, ApplicationKey, PrivateKey, Channel, true, (exception, s) => { if (exception) Terminal.LogError(String.Format("Error: {0}", exception.Message)); else Log(s); }); } IEnumerator DisablePresence() { yield return 1; PresenceClient.DisablePresence(URLSSL, ClientIsCluster, ApplicationKey, PrivateKey, Channel, (exception, s) => { if (exception) Terminal.LogError(String.Format("Error: {0}", exception.Message)); else Log(s); } ); } void Send() { // Parallel Task: Send Log("Send:" + Message + " to " + Channel); _ortc.Send(Channel, Message); } #endregion #region Events private void OnMessageCallback(string channel, string message) { switch (channel) { case OrtcConnected: Log(String.Format("A client connected: {0}", message)); break; case OrtcDisconnected: Log(String.Format("A client disconnected: {0}", message)); break; case OrtcSubscribed: Log(String.Format("A client subscribed: {0}", message)); break; case OrtcUnsubscribed: Log(String.Format("A client unsubscribed: {0}", message)); break; default: Log(String.Format("[{0}] {1}", channel, message)); break; } } private void ortc_OnConnected() { Log(String.Format("Connected to: {0}", _ortc.Url)); Log(String.Format("Connection metadata: {0}", _ortc.ConnectionMetadata)); Log(String.Format("Session ID: {0}", _ortc.SessionId)); Log(String.Format("Heartbeat: {0}", _ortc.HeartbeatActive ? "active" : "inactive")); if (_ortc.HeartbeatActive) { Log(String.Format("Heartbeat time: {0} Heartbeat fails: {1}", _ortc.HeartbeatTime, _ortc.HeartbeatFails)); } } private void ortc_OnDisconnected() { Log("Disconnected"); } private void ortc_OnReconnecting() { // Update URL with user entered text if (ClientIsCluster) { Log(String.Format("Reconnecting to: {0}", _ortc.ClusterUrl)); } else { Log(String.Format("Reconnecting to: {0}", _ortc.Url)); } } private void ortc_OnReconnected() { Log(String.Format("Reconnected to: {0}", _ortc.Url)); } private void ortc_OnSubscribed(string channel) { Log(String.Format("Subscribed to: {0}", channel)); } private void ortc_OnUnsubscribed(string channel) { Log(String.Format("Unsubscribed from: {0}", channel)); } private void ortc_OnException(Exception ex) { Log(String.Format("Error: {0}", ex.Message)); } #endregion } }
using System; using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using EdjCase.JsonRpc.Router; using EdjCase.JsonRpc.Common; using EdjCase.JsonRpc.Router.Abstractions; using EdjCase.JsonRpc.Router.Utilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Caching.Memory; namespace EdjCase.JsonRpc.Router.Defaults { internal class RpcEndpointInfo { public Dictionary<RpcPath, List<MethodInfo>> Routes { get; } public RpcEndpointInfo(Dictionary<RpcPath, List<MethodInfo>> routes) { this.Routes = routes ?? throw new ArgumentNullException(nameof(routes)); } } internal class MethodInfoEqualityComparer : IEqualityComparer<MethodInfo> { public static MethodInfoEqualityComparer Instance = new MethodInfoEqualityComparer(); public bool Equals(MethodInfo? x, MethodInfo? y) { if (x == null || y == null) { return x == null && y == null; } if (object.ReferenceEquals(x, y)) { return true; } if (x.Name != y.Name) { return false; } if (x.DeclaringType != y.DeclaringType) { return false; } ParameterInfo[] xParameters = x.GetParameters(); ParameterInfo[] yParameters = y.GetParameters(); if (!xParameters.SequenceEqual(yParameters, ParameterInfoEqualityComparer.Instance)) { return false; } return true; } public int GetHashCode(MethodInfo obj) { return obj.Name.GetHashCode(); } } internal class ParameterInfoEqualityComparer : IEqualityComparer<ParameterInfo> { public static ParameterInfoEqualityComparer Instance = new ParameterInfoEqualityComparer(); public bool Equals(ParameterInfo? x, ParameterInfo? y) { if (x == null || y == null) { return x == null && y == null; } if (x.ParameterType != y.ParameterType) { return false; } if (x.Name != y.Name) { return false; } return true; } public int GetHashCode(ParameterInfo obj) { return obj.Name?.GetHashCode() ?? 0; } } internal class DefaultRequestMatcher : IRpcRequestMatcher { private static ConcurrentDictionary<RpcPath?, ConcurrentDictionary<RpcRequestSignature, IRpcMethodInfo[]>> requestToMethodCache { get; } = new ConcurrentDictionary<RpcPath?, ConcurrentDictionary<RpcRequestSignature, IRpcMethodInfo[]>>(); private ILogger<DefaultRequestMatcher> logger { get; } private IRpcMethodProvider methodProvider { get; } private IRpcContextAccessor contextAccessor { get; } public DefaultRequestMatcher(ILogger<DefaultRequestMatcher> logger, IRpcMethodProvider methodProvider, IRpcContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.logger = logger; this.methodProvider = methodProvider; this.contextAccessor = contextAccessor; } public IRpcMethodInfo GetMatchingMethod(RpcRequestSignature requestSignature) { this.logger.AttemptingToMatchMethod(new string(requestSignature.GetMethodName().Span)); RpcContext context = this.contextAccessor.Get(); IReadOnlyList<IRpcMethodInfo>? methods = this.methodProvider.GetByPath(context.Path); if (methods == null || !methods.Any()) { throw new RpcException(RpcErrorCode.MethodNotFound, $"No methods found for route"); } Span<IRpcMethodInfo> matches = this.FilterAndBuildMethodInfoByRequest(methods, requestSignature); if (matches.Length == 1) { this.logger.RequestMatchedMethod(); return matches[0]; } string errorMessage; if (matches.Length > 1) { var methodInfoList = new List<string>(); foreach (IRpcMethodInfo matchedMethod in matches) { var parameterTypeList = new List<string>(); foreach (IRpcParameterInfo parameterInfo in matchedMethod.Parameters) { string parameterType = parameterInfo.Name + ": " + parameterInfo.Type; if (parameterInfo.IsOptional) { parameterType += "(Optional)"; } parameterTypeList.Add(parameterType); } string parameterString = string.Join(", ", parameterTypeList); methodInfoList.Add($"{{Name: '{matchedMethod.Name}', Parameters: [{parameterString}]}}"); } errorMessage = "More than one method matched the rpc request. Unable to invoke due to ambiguity. Methods that matched the same name: " + string.Join(", ", methodInfoList); } else { //Log diagnostics this.logger.MethodsInRoute(methods); errorMessage = "No methods matched request."; } throw new RpcException(RpcErrorCode.MethodNotFound, errorMessage); } private IRpcMethodInfo[] FilterAndBuildMethodInfoByRequest(IReadOnlyList<IRpcMethodInfo> methods, RpcRequestSignature requestSignature) { //If the request signature is found, it means we have the methods cached already var rpcPath = this.contextAccessor.Get()?.Path; var rpcPathMethodsCache = DefaultRequestMatcher.requestToMethodCache.GetOrAdd(rpcPath, path => new ConcurrentDictionary<RpcRequestSignature, IRpcMethodInfo[]>()); return rpcPathMethodsCache.GetOrAdd(requestSignature, BuildMethodCache); IRpcMethodInfo[] BuildMethodCache(RpcRequestSignature s) { return this.GetMatchingMethods(s, methods); } } private IRpcMethodInfo[] GetMatchingMethods(RpcRequestSignature requestSignature, IReadOnlyList<IRpcMethodInfo> methods) { IRpcMethodInfo[] methodsWithSameName = ArrayPool<IRpcMethodInfo>.Shared.Rent(methods.Count); try { //Case insenstive check for hybrid approach. Will check for case sensitive if there is ambiguity int methodsWithSameNameCount = 0; for (int i = 0; i < methods.Count; i++) { IRpcMethodInfo methodInfo = methods[i]; if (RpcUtil.NamesMatch(methodInfo.Name.AsSpan(), requestSignature.GetMethodName().Span)) { methodsWithSameName[methodsWithSameNameCount++] = methodInfo; } } if (methodsWithSameNameCount < 1) { return Array.Empty<IRpcMethodInfo>(); } return this.FilterBySimilarParams(requestSignature, methodsWithSameName.AsSpan(0, methodsWithSameNameCount)); } finally { ArrayPool<IRpcMethodInfo>.Shared.Return(methodsWithSameName, clearArray: false); } } private IRpcMethodInfo[] FilterBySimilarParams(RpcRequestSignature requestSignature, Span<IRpcMethodInfo> methodsWithSameName) { IRpcMethodInfo[] potentialMatches = ArrayPool<IRpcMethodInfo>.Shared.Rent(methodsWithSameName.Length); try { int potentialMatchCount = 0; for (int i = 0; i < methodsWithSameName.Length; i++) { IRpcMethodInfo m = methodsWithSameName[i]; bool isMatch = this.ParametersMatch(requestSignature, m.Parameters); if (isMatch) { potentialMatches[potentialMatchCount++] = m; } } if (potentialMatchCount <= 1) { return potentialMatches.AsSpan(0, potentialMatchCount).ToArray(); } return this.FilterMatchesByCaseSensitiveMethod(requestSignature, potentialMatches.AsSpan(0, potentialMatchCount)); } finally { ArrayPool<IRpcMethodInfo>.Shared.Return(potentialMatches, clearArray: false); } } private IRpcMethodInfo[] FilterMatchesByCaseSensitiveMethod(RpcRequestSignature requestSignature, Span<IRpcMethodInfo> matches) { //Try to remove ambiguity with case sensitive check IRpcMethodInfo[] caseSensitiveMatches = ArrayPool<IRpcMethodInfo>.Shared.Rent(matches.Length); try { int caseSensitiveCount = 0; for (int i = 0; i < matches.Length; i++) { IRpcMethodInfo m = matches[i]; Memory<char> requestMethodName = requestSignature.GetMethodName(); if (m.Name.Length == requestMethodName.Length) { if (!RpcUtil.NamesMatch(m.Name.AsSpan(), requestMethodName.Span)) { //TODO do we care about the case where 2+ parameters have very similar names and types? continue; } caseSensitiveMatches[caseSensitiveCount++] = m; } } return caseSensitiveMatches.AsSpan(0, caseSensitiveCount).ToArray(); } finally { ArrayPool<IRpcMethodInfo>.Shared.Return(caseSensitiveMatches, clearArray: false); } } private bool ParametersMatch(RpcRequestSignature requestSignature, IReadOnlyList<IRpcParameterInfo> parameters) { if (!requestSignature.HasParameters) { return parameters == null || !parameters.Any(p => !p.IsOptional); } int parameterCount = 0; if (requestSignature.IsDictionary) { foreach ((Memory<char> name, RpcParameterType type) in requestSignature.ParametersAsDict) { bool found = false; for (int paramIndex = 0; paramIndex < parameters.Count; paramIndex++) { IRpcParameterInfo parameter = parameters[paramIndex]; if (!RpcUtil.NamesMatch(parameter.Name.AsSpan(), name.Span) || !RpcParameterUtil.TypesCompatible(parameter.Type, type)) { continue; } found = true; break; } if (!found) { return false; } parameterCount++; } } else { foreach (RpcParameterType parameterType in requestSignature.ParametersAsList) { if (parameters.Count <= parameterCount) { return false; } IRpcParameterInfo info = parameters[parameterCount]; if (!RpcParameterUtil.TypesCompatible(info.Type, parameterType)) { return false; } parameterCount++; } for (int i = parameterCount; i < parameters.Count; i++) { //Only if the last parameters in the method are optional does the request match //Will be skipped if they are equal length if (!parameters[i].IsOptional) { return false; } } } if (parameterCount != parameters.Count) { return false; } return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class ExtensionsTests { [Fact] public static void ReadExtensions() { using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection exts = c.Extensions; int count = exts.Count; Assert.Equal(6, count); X509Extension[] extensions = new X509Extension[count]; exts.CopyTo(extensions, 0); extensions = extensions.OrderBy(e => e.Oid.Value).ToArray(); // There are an awful lot of magic-looking values in this large test. // These values are embedded within the certificate, and the test is // just verifying the object interpretation. In the event the test data // (TestData.MsCertificate) is replaced, this whole body will need to be // redone. { // Authority Information Access X509Extension aia = extensions[0]; Assert.Equal("1.3.6.1.5.5.7.1.1", aia.Oid.Value); Assert.False(aia.Critical); byte[] expectedDer = ( "304c304a06082b06010505073002863e687474703a2f2f7777772e6d" + "6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f" + "645369675043415f30382d33312d323031302e637274").HexToByteArray(); Assert.Equal(expectedDer, aia.RawData); } { // Subject Key Identifier X509Extension skid = extensions[1]; Assert.Equal("2.5.29.14", skid.Oid.Value); Assert.False(skid.Critical); byte[] expected = "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(); Assert.Equal(expected, skid.RawData); Assert.True(skid is X509SubjectKeyIdentifierExtension); X509SubjectKeyIdentifierExtension rich = (X509SubjectKeyIdentifierExtension)skid; Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", rich.SubjectKeyIdentifier); } { // Subject Alternative Names X509Extension sans = extensions[2]; Assert.Equal("2.5.29.17", sans.Oid.Value); Assert.False(sans.Critical); byte[] expected = ( "3048a4463044310d300b060355040b13044d4f505231333031060355" + "0405132a33313539352b34666166306237312d616433372d34616133" + "2d613637312d373662633035323334346164").HexToByteArray(); Assert.Equal(expected, sans.RawData); } { // CRL Distribution Points X509Extension cdps = extensions[3]; Assert.Equal("2.5.29.31", cdps.Oid.Value); Assert.False(cdps.Critical); byte[] expected = ( "304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f" + "66742e636f6d2f706b692f63726c2f70726f64756374732f4d696343" + "6f645369675043415f30382d33312d323031302e63726c").HexToByteArray(); Assert.Equal(expected, cdps.RawData); } { // Authority Key Identifier X509Extension akid = extensions[4]; Assert.Equal("2.5.29.35", akid.Oid.Value); Assert.False(akid.Critical); byte[] expected = "30168014cb11e8cad2b4165801c9372e331616b94c9a0a1f".HexToByteArray(); Assert.Equal(expected, akid.RawData); } { // Extended Key Usage (X.509/2000 says Extended, Win32/NetFX say Enhanced) X509Extension eku = extensions[5]; Assert.Equal("2.5.29.37", eku.Oid.Value); Assert.False(eku.Critical); byte[] expected = "300a06082b06010505070303".HexToByteArray(); Assert.Equal(expected, eku.RawData); Assert.True(eku is X509EnhancedKeyUsageExtension); X509EnhancedKeyUsageExtension rich = (X509EnhancedKeyUsageExtension)eku; OidCollection usages = rich.EnhancedKeyUsages; Assert.Equal(1, usages.Count); Oid oid = usages[0]; // Code Signing Assert.Equal("1.3.6.1.5.5.7.3.3", oid.Value); } } } [Fact] public static void KeyUsageExtensionDefaultCtor() { X509KeyUsageExtension e = new X509KeyUsageExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.15", oidValue); byte[] r = e.RawData; Assert.Null(r); X509KeyUsageFlags keyUsages = e.KeyUsages; Assert.Equal(X509KeyUsageFlags.None, keyUsages); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_CrlSign() { TestKeyUsageExtension(X509KeyUsageFlags.CrlSign, false, "03020102".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_DataEncipherment() { TestKeyUsageExtension(X509KeyUsageFlags.DataEncipherment, false, "03020410".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_DecipherOnly() { TestKeyUsageExtension(X509KeyUsageFlags.DecipherOnly, false, "0303070080".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_DigitalSignature() { TestKeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false, "03020780".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_EncipherOnly() { TestKeyUsageExtension(X509KeyUsageFlags.EncipherOnly, false, "03020001".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_KeyAgreement() { TestKeyUsageExtension(X509KeyUsageFlags.KeyAgreement, false, "03020308".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_KeyCertSign() { TestKeyUsageExtension(X509KeyUsageFlags.KeyCertSign, false, "03020204".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_KeyEncipherment() { TestKeyUsageExtension(X509KeyUsageFlags.KeyEncipherment, false, "03020520".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_None() { TestKeyUsageExtension(X509KeyUsageFlags.None, false, "030100".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void KeyUsageExtension_NonRepudiation() { TestKeyUsageExtension(X509KeyUsageFlags.NonRepudiation, false, "03020640".HexToByteArray()); } [Fact] public static void BasicConstraintsExtensionDefault() { X509BasicConstraintsExtension e = new X509BasicConstraintsExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.19", oidValue); byte[] rawData = e.RawData; Assert.Null(rawData); Assert.False(e.CertificateAuthority); Assert.False(e.HasPathLengthConstraint); Assert.Equal(0, e.PathLengthConstraint); } [Theory] [MemberData("BasicConstraintsData")] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void BasicConstraintsExtensionEncode( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical, string expectedDerString) { X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension( certificateAuthority, hasPathLengthConstraint, pathLengthConstraint, critical); byte[] expectedDer = expectedDerString.HexToByteArray(); Assert.Equal(expectedDer, ext.RawData); } [Theory] [MemberData("BasicConstraintsData")] public static void BasicConstraintsExtensionDecode( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical, string rawDataString) { byte[] rawData = rawDataString.HexToByteArray(); X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension(new AsnEncodedData(rawData), critical); Assert.Equal(certificateAuthority, ext.CertificateAuthority); Assert.Equal(hasPathLengthConstraint, ext.HasPathLengthConstraint); Assert.Equal(pathLengthConstraint, ext.PathLengthConstraint); } public static object[][] BasicConstraintsData = new object[][] { new object[] { false, false, 0, false, "3000" }, new object[] { true, false, 0, false, "30030101ff" }, new object[] { false, true, 0, false, "3003020100" }, new object[] { false, true, 7654321, false, "3005020374cbb1" }, new object[] { true, true, 559, false, "30070101ff0202022f" }, }; [Fact] public static void EnhancedKeyUsageExtensionDefault() { X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.37", oidValue); byte[] rawData = e.RawData; Assert.Null(rawData); OidCollection usages = e.EnhancedKeyUsages; Assert.Equal(0, usages.Count); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void EnhancedKeyUsageExtension_Empty() { OidCollection usages = new OidCollection(); TestEnhancedKeyUsageExtension(usages, false, "3000".HexToByteArray()); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void EnhancedKeyUsageExtension_2Oids() { Oid oid1 = Oid.FromOidValue("1.3.6.1.5.5.7.3.1", OidGroup.EnhancedKeyUsage); Oid oid2 = Oid.FromOidValue("1.3.6.1.4.1.311.10.3.1", OidGroup.EnhancedKeyUsage); OidCollection usages = new OidCollection(); usages.Add(oid1); usages.Add(oid2); TestEnhancedKeyUsageExtension(usages, false, "301606082b06010505070301060a2b0601040182370a0301".HexToByteArray()); } [Fact] public static void SubjectKeyIdentifierExtensionDefault() { X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(); string oidValue = e.Oid.Value; Assert.Equal("2.5.29.14", oidValue); byte[] rawData = e.RawData; Assert.Null(rawData); string skid = e.SubjectKeyIdentifier; Assert.Null(skid); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void SubjectKeyIdentifierExtension_Bytes() { byte[] sk = { 1, 2, 3, 4 }; X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false); byte[] rawData = e.RawData; Assert.Equal("040401020304".HexToByteArray(), rawData); e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false); string skid = e.SubjectKeyIdentifier; Assert.Equal("01020304", skid); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void SubjectKeyIdentifierExtension_String() { string sk = "01ABcd"; X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false); byte[] rawData = e.RawData; Assert.Equal("040301abcd".HexToByteArray(), rawData); e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false); string skid = e.SubjectKeyIdentifier; Assert.Equal("01ABCD", skid); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void SubjectKeyIdentifierExtension_PublicKey() { PublicKey pk = new X509Certificate2(TestData.MsCertificate).PublicKey; X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(pk, false); byte[] rawData = e.RawData; Assert.Equal("04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(), rawData); e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false); string skid = e.SubjectKeyIdentifier; Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", skid); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void SubjectKeyIdentifierExtension_PublicKeySha1() { TestSubjectKeyIdentifierExtension( TestData.MsCertificate, X509SubjectKeyIdentifierHashAlgorithm.Sha1, false, "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(), "5971A65A334DDA980780FF841EBE87F9723241F2"); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void SubjectKeyIdentifierExtension_PublicKeyShortSha1() { TestSubjectKeyIdentifierExtension( TestData.MsCertificate, X509SubjectKeyIdentifierHashAlgorithm.ShortSha1, false, "04084ebe87f9723241f2".HexToByteArray(), "4EBE87F9723241F2"); } [Fact] [ActiveIssue(1993, PlatformID.AnyUnix)] public static void SubjectKeyIdentifierExtension_PublicKeyCapiSha1() { TestSubjectKeyIdentifierExtension( TestData.MsCertificate, X509SubjectKeyIdentifierHashAlgorithm.CapiSha1, false, "0414a260a870be1145ed71e2bb5aa19463a4fe9dcc41".HexToByteArray(), "A260A870BE1145ED71E2BB5AA19463A4FE9DCC41"); } private static void TestKeyUsageExtension(X509KeyUsageFlags flags, bool critical, byte[] expectedDer) { X509KeyUsageExtension ext = new X509KeyUsageExtension(flags, critical); byte[] rawData = ext.RawData; Assert.Equal(expectedDer, rawData); // Assert that format doesn't crash string s = ext.Format(false); // Rebuild it from the RawData. ext = new X509KeyUsageExtension(new AsnEncodedData(rawData), critical); Assert.Equal(flags, ext.KeyUsages); } private static void TestEnhancedKeyUsageExtension( OidCollection usages, bool critical, byte[] expectedDer) { X509EnhancedKeyUsageExtension ext = new X509EnhancedKeyUsageExtension(usages, critical); byte[] rawData = ext.RawData; Assert.Equal(expectedDer, rawData); ext = new X509EnhancedKeyUsageExtension(new AsnEncodedData(rawData), critical); OidCollection actualUsages = ext.EnhancedKeyUsages; Assert.Equal(usages.Count, actualUsages.Count); for (int i = 0; i < usages.Count; i++) { Assert.Equal(usages[i].Value, actualUsages[i].Value); } } private static void TestSubjectKeyIdentifierExtension( byte[] certBytes, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical, byte[] expectedDer, string expectedIdentifier) { PublicKey pk = new X509Certificate2(certBytes).PublicKey; X509SubjectKeyIdentifierExtension ext = new X509SubjectKeyIdentifierExtension(pk, algorithm, critical); byte[] rawData = ext.RawData; Assert.Equal(expectedDer, rawData); ext = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), critical); Assert.Equal(expectedIdentifier, ext.SubjectKeyIdentifier); } } }
#region "Copyright" /* FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER */ #endregion #region "References" using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using AjaxControlToolkit; using SageFrame.Framework; using System.Data; using SageFrame.Web; using SageFrame.PortalSetting; using System.Collections; using SageFrame.Web.Utilities; using SageFrame.SageFrameClass; using SageFrame.Utilities; using SageFrame.RolesManagement; using SageFrame.Shared; using System.IO; using System.Text; using SageFrame.Dashboard; using SageFrame.Templating; using System.Web.UI.HtmlControls; using SageFrame.ModuleMessage; using SageFrame.Security; using SageFrame.Common; using SageFrame.Core; #endregion namespace SageFrame { public partial class Sagin_Admin : PageBase, SageFrameRoute { #region "Public Variables" public string ControlPath = string.Empty, SageFrameAppPath, SageFrameUserName; public string appPath = string.Empty; public string Extension; public string templateFavicon = string.Empty; #endregion #region "Event Handlers" protected void Page_Init(object sender, EventArgs e) { SetPageInitPart(); } protected override void OnInit(EventArgs e) { ViewStateUserKey = Session.SessionID; base.OnInit(e); } protected void Page_Load(object sender, EventArgs e) { SetPageLoadPart(); //CoreJs.IncludeLanguageCoreJs(this.Page); // SagePageLoadPart(); } #endregion #region "Public methods" public void LoadMessageControl() { PlaceHolder phdPlaceHolder = Page.FindControl("message") as PlaceHolder; if (phdPlaceHolder != null) { LoadControl(phdPlaceHolder, "~/Controls/Message.ascx"); } } public override void ShowMessage(string MessageTitle, string Message, string CompleteMessage, bool isSageAsyncPostBack, SageMessageType MessageType) { string strCssClass = GetMessageCssClass(MessageType); int Cont = this.Page.Controls.Count; ControlCollection lstControls = Page.FindControl("form1").Controls; PlaceHolder phd = Page.FindControl("message") as PlaceHolder; if (phd != null) { foreach (Control c in phd.Controls) { if (c.GetType().FullName.ToLower() == "ASP.Controls_message_ascx".ToLower()) { SageUserControl tt = (SageUserControl)c; tt.Modules_Message_ShowMessage(tt, MessageTitle, Message, CompleteMessage, isSageAsyncPostBack, MessageType, strCssClass); } } } } #endregion #region "Private Methods" private void SetGlobalVariable() { appPath = Request.ApplicationPath; SageFrameAppPath = appPath; imgLogo.ImageUrl = ResolveUrl("~/") + "images/aspxcommerce.png"; lnkLoginCss.Href = ResolveUrl("~/") + "Administrator/Templates/Default/css/login.css"; RegisterSageGlobalVariable(); } private void SetPageInitPart() { ltrJQueryLibrary.Text = GetJqueryLibraryPath(); templateFavicon = SetFavIcon(GetActiveTemplate); Extension = SageFrameSettingKeys.PageExtension; ApplicationController objAppController = new ApplicationController(); if (!objAppController.CheckRequestExtension(Request)) { SageInitPart(); } SetGlobalVariable(); } private void SageInitPart() { ApplicationController objAppController = new ApplicationController(); if (objAppController.IsInstalled()) { if (!objAppController.CheckRequestExtension(Request)) { SetPortalCofig(); InitializePage(); LoadMessageControl(); BindModuleControls(); } } else { HttpContext.Current.Response.Redirect(ResolveUrl("~/Install/InstallWizard.aspx")); } } private void SetPortalCofig() { Hashtable hstPortals = GetPortals(); SageUserControl suc = new SageUserControl(); suc.PagePath = PagePath; int portalID = 1; #region "Get Portal SEO Name and PortalID" if (string.IsNullOrEmpty(Request.QueryString["ptSEO"])) { if (string.IsNullOrEmpty(PortalSEOName)) { PortalSEOName = GetDefaultPortalName(hstPortals, 1);// 1 is default parent PortalID } else if (!hstPortals.ContainsKey(PortalSEOName.ToLower().Trim())) { PortalSEOName = GetDefaultPortalName(hstPortals, 1); } else { portalID = int.Parse(hstPortals[PortalSEOName.ToLower().Trim()].ToString()); } } else { PortalSEOName = Request.QueryString["ptSEO"].ToString().ToLower().Trim(); portalID = Int32.Parse(Request.QueryString["ptlid"].ToString()); } #endregion suc.SetPortalSEOName(PortalSEOName.ToLower().Trim()); Session[SessionKeys.SageFrame_PortalSEOName] = PortalSEOName.ToLower().Trim(); Session[SessionKeys.SageFrame_PortalID] = portalID; Session[SessionKeys.SageFrame_AdminTheme] = ThemeHelper.GetAdminTheme(GetPortalID, GetUsername); Globals.sysHst[ApplicationKeys.ActiveTemplate + "_" + portalID] = TemplateController.GetActiveTemplate(GetPortalID).TemplateSeoName; Globals.sysHst[ApplicationKeys.ActivePagePreset + "_" + portalID] = PresetHelper.LoadActivePagePreset(GetActiveTemplate, GetPageSEOName(Request.Url.ToString())); suc.SetPortalID(portalID); SetPortalID(portalID); #region "Set user credentials for modules" SecurityPolicy objSecurity = new SecurityPolicy(); if (objSecurity.GetUser(GetPortalID) != string.Empty) { SettingProvider objSP = new SettingProvider(); SageFrameConfig sfConfig = new SageFrameConfig(); string strRoles = string.Empty; List<SageUserRole> sageUserRolles = objSP.RoleListGetByUsername(objSecurity.GetUser(GetPortalID), GetPortalID); if (sageUserRolles != null) { foreach (SageUserRole userRole in sageUserRolles) { strRoles += userRole.RoleId + ","; } } if (strRoles.Length > 1) { strRoles = strRoles.Substring(0, strRoles.Length - 1); } if (strRoles.Length > 0) { SetUserRoles(strRoles); } } #endregion } private void SetPageLoadPart() { ApplicationController objAppController = new ApplicationController(); if (!objAppController.CheckRequestExtension(Request)) { SagePageLoadPart(); StringBuilder sb = new StringBuilder(); } } private void SagePageLoadPart() { if (!IsPostBack) { string sageNavigateUrl = string.Empty; SageFrameConfig sfConfig = new SageFrameConfig(); if (!IsParent) { sageNavigateUrl = GetParentURL + "/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + Extension; } else { sageNavigateUrl = GetParentURL + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).Replace(" ", "-") + Extension; } hypPreview.NavigateUrl = sageNavigateUrl; Image imgProgress = (Image)UpdateProgress1.FindControl("imgPrgress"); if (imgProgress != null) { imgProgress.ImageUrl = GetAdminImageUrl("ajax-loader.gif", true); } } ////SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker]; //if (string.IsNullOrEmpty(sessionTracker.PortalID)) //{ // //sessionTracker.PortalID = GetPortalID.ToString(); // //sessionTracker.Username = GetUsername; // SageFrameConfig sfConfig = new SageFrameConfig(); // //sessionTracker.InsertSessionTrackerPages = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.InsertSessionTrackingPages); // SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog(); // SLog.SessionTrackerUpdateUsername(sessionTracker, GetUsername, GetPortalID.ToString()); // //Session[SessionKeys.Tracker] = sessionTracker; //} } private void BindModuleControls() { string preFix = string.Empty; string paneName = string.Empty; string ControlSrc = string.Empty; string phdContainer = string.Empty; string PageSEOName = string.Empty; SageUserControl suc = new SageUserControl(); string PageName = PagePath; if (PagePath == null) { string PageUrl = Request.RawUrl; PageName = Path.GetFileNameWithoutExtension(PageUrl); } else { PageName = PagePath; } suc.PagePath = PageName; if (Request.QueryString["pgnm"] != null) { PageSEOName = Request.QueryString["pgnm"].ToString(); } else { PageSEOName = GetPageSEOName(PageName); } //:TODO: Need to get controlType and pageID from the selected page from routing path //string controlType = "0"; //string pageID = "2"; StringBuilder redirecPath = new StringBuilder(); Uri url = HttpContext.Current.Request.Url; if (PageSEOName != string.Empty) { DataSet dsPageSettings = new DataSet(); SageFrameConfig sfConfig = new SageFrameConfig(); dsPageSettings = sfConfig.GetPageSettingsByPageSEONameForAdmin("1", PageSEOName, GetUsername); if (bool.Parse(dsPageSettings.Tables[0].Rows[0][0].ToString()) == true) { #region "Control Load Part" if (bool.Parse(dsPageSettings.Tables[0].Rows[0][1].ToString()) == true) { // Get ModuleControls data table DataTable dtPages = dsPageSettings.Tables[1]; if (dtPages != null && dtPages.Rows.Count > 0) { OverridePageInfo(dtPages); } List<string> moduleDefIDList = new List<string>(); // Get ModuleDefinitions data table DataTable dtPageModule = dsPageSettings.Tables[2]; if (dtPageModule != null && dtPageModule.Rows.Count > 0) { for (int i = 0; i < dtPageModule.Rows.Count; i++) { paneName = dtPageModule.Rows[i]["PaneName"].ToString(); if (string.IsNullOrEmpty(paneName)) paneName = "ContentPane"; string UserModuleID = dtPageModule.Rows[i]["UserModuleID"].ToString(); ControlSrc = "/" + dtPageModule.Rows[i]["ControlSrc"].ToString(); string SupportsPartialRendering = dtPageModule.Rows[i]["SupportsPartialRendering"].ToString(); PlaceHolder phdPlaceHolder = (PlaceHolder)this.FindControl(paneName); if (paneName.Equals("navigation")) { divNavigation.Attributes.Add("style", "display:block"); } if (phdPlaceHolder != null) { //bool status = LoadModuleInfo(phdPlaceHolder, int.Parse(UserModuleID), 0); LoadControl(phdPlaceHolder, ControlSrc, paneName, UserModuleID, "", "", false, new HtmlGenericControl("div"), new HtmlGenericControl("span"), false); //if (!status) //{ // LoadModuleInfo(phdPlaceHolder, int.Parse(UserModuleID), 1); //} moduleDefIDList.Add(dtPageModule.Rows[i]["ModuleDefID"].ToString()); } } } SetModuleDefList(moduleDefIDList); } #endregion else { if (!IsParent) { redirecPath.Append(url.Scheme); redirecPath.Append("://"); redirecPath.Append(url.Authority); redirecPath.Append(PortalAPI.GetApplicationName); redirecPath.Append("/portal/"); redirecPath.Append(GetPortalSEOName); redirecPath.Append("/"); redirecPath.Append(PortalAPI.LoginPageWithExtension); } else { redirecPath.Append(url.Scheme); redirecPath.Append("://"); redirecPath.Append(url.Authority); redirecPath.Append(PortalAPI.LoginURL); } string strCurrentURL = Request.Url.ToString(); if (redirecPath.ToString().Contains("?")) { redirecPath.Append("&ReturnUrl="); redirecPath.Append(strCurrentURL); } else { redirecPath.Append("?ReturnUrl="); redirecPath.Append(strCurrentURL); } Response.Redirect(redirecPath.ToString()); } } else { if (!IsParent) { redirecPath.Append(url.Scheme); redirecPath.Append("://"); redirecPath.Append(url.Authority); redirecPath.Append(PortalAPI.GetApplicationName); redirecPath.Append("/portal/"); redirecPath.Append(GetPortalSEOName); redirecPath.Append("/"); redirecPath.Append(PortalAPI.PageNotFoundPageWithExtension); } else { redirecPath.Append(url.Scheme); redirecPath.Append("://"); redirecPath.Append(url.Authority); redirecPath.Append(PortalAPI.PageNotFoundURL); } Response.Redirect(redirecPath.ToString()); } } } private void LoadControl(PlaceHolder ContainerControl, string controlSource) { UserControl ctl = this.Page.LoadControl(controlSource) as UserControl; ctl.EnableViewState = true; ContainerControl.Controls.Add(ctl); } private bool LoadModuleInfo(PlaceHolder Container, int UserModuleID, int position) { bool status = false; ModuleMessageInfo objMessage = ModuleMessageController.GetModuleMessageByUserModuleID(UserModuleID, GetCurrentCulture()); if (objMessage != null) { if (objMessage.IsActive) { if (objMessage.MessagePosition == position) { string modeStyle = "sfPersist"; switch (objMessage.MessageMode) { case 0: modeStyle = "sfPersist"; break; case 1: modeStyle = "sfSlideup"; break; case 2: modeStyle = "sfFadeout"; break; } string messageTypeStyle = "sfInfo"; switch (objMessage.MessageType) { case 0: messageTypeStyle = "sfInfo"; break; case 1: messageTypeStyle = "sfWarning"; break; } string totalStyle = string.Format("{0} {1} sfModuletext", modeStyle, messageTypeStyle); HtmlGenericControl moduleDiv = new HtmlGenericControl("div"); StringBuilder sb = new StringBuilder(); string CloseForEver = string.Format("close_{0}", UserModuleID); sb.Append("<div class='sfModuleInfo'><div class='" + totalStyle + "'><div class='sfLinks'><a class='sfClose' href='#'>Close</a> || <a class='sfNclose' id='" + CloseForEver + "' href='#'>Close and Never Show Again</a></div>"); sb.Append(objMessage.Message); sb.Append("</div></div>"); moduleDiv.InnerHtml = sb.ToString(); Container.Controls.Add(moduleDiv); status = true; } } } return status; } #endregion #region SageFrameRoute Members public string PagePath { get; set; } public string PortalSEOName { get; set; } public string UserModuleID { get; set; } public string ControlType { get; set; } public string ControlMode { get; set; } public string Key { get; set; } public string Param { get; set; } #endregion } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Web.Routing; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Web.Handlers; using Microsoft.Xrm.Portal.Web.Routing; namespace Microsoft.Xrm.Portal.Web.Modules { /// <summary> /// Manages the URL routing for a standard portal website. /// </summary> /// <remarks> /// <example> /// Example configuration. /// <code> /// <![CDATA[ /// <configuration> /// /// <configSections> /// <section name="microsoft.xrm.portal" type="Microsoft.Xrm.Portal.Configuration.PortalCrmSection, Microsoft.Xrm.Portal"/> /// </configSections> /// /// <system.webServer> /// <modules runAllManagedModulesForAllRequests="true"> /// <add name="PortalRouting" type="Microsoft.Xrm.Portal.Web.Modules.PortalRoutingModule, Microsoft.Xrm.Portal" preCondition="managedHandler"/> /// </modules> /// </system.webServer> /// /// <microsoft.xrm.portal rewriteVirtualPathEnabled="true" [false | true] /> /// /// </configuration> /// ]]> /// </code> /// </example> /// </remarks> /// <seealso cref="PortalCrmConfigurationManager"/> /// <seealso cref="PortalRouteHandler"/> /// <seealso cref="EmbeddedResourceRouteHandler"/> /// <seealso cref="CompositeEmbeddedResourceRouteHandler"/> /// <seealso cref="EntityRouteHandler"/> public class PortalRoutingModule : IHttpModule // MSBug #120030: Won't seal, inheritance is used extension point. { private const string _prefix = "xrm"; private static readonly string[] _paths = new[] { "js/xrm.js", "js/editable/utilities.js", "js/editable/data.js", "js/editable/ui.js", "js/editable/datetimepicker.js", "js/editable/attribute.js", "js/editable/attributes/text.js", "js/editable/attributes/html.js", "js/editable/entity.js", "js/editable/entity_form.js", "js/editable/entity_handler.js", "js/editable/entities/adx_webfile.js", "js/editable/entities/adx_weblinkset.js", "js/editable/entities/adx_webpage.js", "js/editable/entities/sitemapchildren.js", "js/editable/editable.js", "js/xrm-activate.js", }; private static RouteCollection _routes; /// <summary> /// The name of the <see cref="PortalContextElement"/> specifying the current portal. /// </summary> public string PortalName { get; set; } /// <summary> /// Enables routing to the <see cref="EmbeddedResourceRouteHandler"/> for serving embedded resources. /// </summary> public bool UseEmbeddedResourceVirtualPathProvider { get; set; } /// <summary> /// Enables routing to the <see cref="CacheInvalidationHandler"/> by specifying the path '/Cache.axd' followed by querystring parameters. /// </summary> public bool IncludeCacheInvalidationHandler { get; set; } /// <summary> /// Enables detection of incoming virtual paths (those prefixed by "~/") from the client. If found, the context URL is rewritten to the virtual path. /// </summary> protected virtual bool RewriteVirtualPathEnabled { get { return PortalCrmConfigurationManager.GetPortalCrmSection().RewriteVirtualPathEnabled; } } public void Dispose() { } public virtual void Init(HttpApplication application) { application.PostAuthenticateRequest += RewriteVirtualPath; LazyInitializer.EnsureInitialized(ref _routes, Register); } /// <summary> /// Detects the presence of a virtual path within the request URL. If found, the context URL is rewritten to the virtual path. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> protected virtual void RewriteVirtualPath(object sender, EventArgs args) { if (!RewriteVirtualPathEnabled) return; var application = sender as HttpApplication; var context = application.Context; var url = context.Request.Url.PathAndQuery; var match = Regex.Match(url, @"~/.*"); if (match.Success) { var rewritePath = match.Value; Tracing.FrameworkInformation("PortalRoutingModule", "RewriteVirtualPath", "Redirecting '{0}' to '{1}'", url, rewritePath); // perform a redirect to prevent ~/ from appearing in the client address as well as redundant URLs context.RedirectAndEndResponse(rewritePath); } } private RouteCollection Register() { var mappings = Utility.GetEmbeddedResourceMappingAttributes().ToList(); var paths = GetPaths().ToArray(); var routes = Register( RouteTable.Routes, new PortalRouteHandler(PortalName), new EmbeddedResourceRouteHandler(mappings), new CompositeEmbeddedResourceRouteHandler(mappings, paths)); Tracing.FrameworkInformation("PortalRoutingModule", "Init", "Added '{0}' route entries.", routes.Count); return routes; } protected virtual RouteCollection Register( RouteCollection routes, IRouteHandler portalRouteHandler, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { RegisterStaticRoutes(routes, portalRouteHandler, embeddedResourceRouteHandler, scriptHandler); RegisterEmbeddedResourceRoutes(routes, portalRouteHandler, embeddedResourceRouteHandler, scriptHandler); RegisterIgnoreRoutes(routes, portalRouteHandler, embeddedResourceRouteHandler, scriptHandler); RegisterCustomRoutes(routes, portalRouteHandler, embeddedResourceRouteHandler, scriptHandler); RegisterDefaultRoutes(routes, portalRouteHandler, embeddedResourceRouteHandler, scriptHandler); return routes; } protected virtual void Register( RouteCollection routes, string prefix, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { if (UseEmbeddedResourceVirtualPathProvider) { // ignore the prefix to allow the EmbeddedResourceVirtualPathProvider to handle the request routes.Ignore(prefix + "/{*pathInfo}"); } else { // add the combined script handler routes.Add( "type={0},prefix={1}".FormatWith(scriptHandler, prefix), new Route(prefix + "/js/xrm-combined.js/{*pathInfo}", null, null, scriptHandler)); // keep this route until the xrm-combined-js.aspx is removed from the files project routes.Add( "type={0},prefix={1},extension=aspx".FormatWith(scriptHandler, prefix), new Route(prefix + "/js/xrm-combined-js.aspx/{*pathInfo}", null, null, scriptHandler)); // add the embedded resource handler routes.Add( "type={0},prefix={1}".FormatWith(embeddedResourceRouteHandler, prefix), new Route( "{prefix}/{*path}", null, new RouteValueDictionary(new { prefix }), embeddedResourceRouteHandler)); } } protected static IEnumerable<string> GetPaths(string prefix, IEnumerable<string> paths) { return paths.Select(p => "~/{0}/{1}".FormatWith(prefix, p)); } protected virtual IEnumerable<string> GetPaths() { return GetPaths(_prefix, _paths); } protected virtual void RegisterStaticRoutes( RouteCollection routes, IRouteHandler portalRouteHandler, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { if (IncludeCacheInvalidationHandler) { // add the cache invalidation handler var cacheInvalidationHandler = new CacheInvalidationHandler(); routes.Add( cacheInvalidationHandler.GetType().FullName, new Route("Cache.axd/{*pathInfo}", null, null, cacheInvalidationHandler)); } } protected virtual void RegisterEmbeddedResourceRoutes( RouteCollection routes, IRouteHandler portalRouteHandler, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { // register embedded resource handler routes Register(routes, _prefix, embeddedResourceRouteHandler, scriptHandler); } protected virtual void RegisterIgnoreRoutes( RouteCollection routes, IRouteHandler portalRouteHandler, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { routes.Ignore("{resource}.axd/{*pathInfo}"); routes.Ignore("{resource}.svc/{*pathInfo}"); } protected virtual void RegisterCustomRoutes( RouteCollection routes, IRouteHandler portalRouteHandler, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { var entityRouteHandler = new EntityRouteHandler(PortalName); routes.Add( entityRouteHandler.GetType().FullName, new Route("_entity/{logicalName}/{id}", entityRouteHandler)); } protected virtual void RegisterDefaultRoutes( RouteCollection routes, IRouteHandler portalRouteHandler, IEmbeddedResourceRouteHandler embeddedResourceRouteHandler, IEmbeddedResourceRouteHandler scriptHandler) { routes.Add(portalRouteHandler.GetType().FullName, new Route("{*path}", portalRouteHandler)); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Input.Inking; using Windows.UI.Xaml.Navigation; using Windows.UI.Text.Core; using Windows.Globalization; using SDKTemplate; namespace SimpleInk { /// <summary> /// This page shows the code to do ink recognition /// </summary> public sealed partial class Scenario2 : Page { const string InstallRecoText = "You can install handwriting recognition engines for other languages by this: go to Settings -> Time & language -> Region & language, choose a language, and click Options, then click Download under Handwriting"; private MainPage rootPage; InkRecognizerContainer inkRecognizerContainer = null; private IReadOnlyList<InkRecognizer> recoView = null; private Language previousInputLanguage = null; private CoreTextServicesManager textServiceManager = null; private ToolTip recoTooltip; public Scenario2() { this.InitializeComponent(); // Initialize drawing attributes. These are used in inking mode. InkDrawingAttributes drawingAttributes = new InkDrawingAttributes(); drawingAttributes.Color = Windows.UI.Colors.Red; double penSize = 4; drawingAttributes.Size = new Windows.Foundation.Size(penSize, penSize); drawingAttributes.IgnorePressure = false; drawingAttributes.FitToCurve = true; // Show the available recognizers inkRecognizerContainer = new InkRecognizerContainer(); recoView = inkRecognizerContainer.GetRecognizers(); if (recoView.Count > 0) { foreach (InkRecognizer recognizer in recoView) { RecoName.Items.Add(recognizer.Name); } } else { RecoName.IsEnabled = false; RecoName.Items.Add("No Recognizer Available"); } RecoName.SelectedIndex = 0; // Set the text services so we can query when language changes textServiceManager = CoreTextServicesManager.GetForCurrentView(); textServiceManager.InputLanguageChanged += TextServiceManager_InputLanguageChanged; SetDefaultRecognizerByCurrentInputMethodLanguageTag(); // Initialize reco tooltip recoTooltip = new ToolTip(); recoTooltip.Content = InstallRecoText; ToolTipService.SetToolTip(InstallReco, recoTooltip); // Initialize the InkCanvas inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes); inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen | Windows.UI.Core.CoreInputDeviceTypes.Touch; this.Unloaded += Scenario2_Unloaded; this.SizeChanged += Scenario2_SizeChanged; } private void Scenario2_SizeChanged(object sender, SizeChangedEventArgs e) { SetCanvasSize(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; SetCanvasSize(); } private void Scenario2_Unloaded(object sender, RoutedEventArgs e) { recoTooltip.IsOpen = false; } private void SetCanvasSize() { Output.Width = Window.Current.Bounds.Width; Output.Height = Window.Current.Bounds.Height / 2; inkCanvas.Width = Window.Current.Bounds.Width; inkCanvas.Height = Window.Current.Bounds.Height / 2; } void OnRecognizerChanged(object sender, RoutedEventArgs e) { string selectedValue = (string)RecoName.SelectedValue; SetRecognizerByName(selectedValue); } async void OnRecognizeAsync(object sender, RoutedEventArgs e) { IReadOnlyList<InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes(); if (currentStrokes.Count > 0) { RecognizeBtn.IsEnabled = false; ClearBtn.IsEnabled = false; RecoName.IsEnabled = false; var recognitionResults = await inkRecognizerContainer.RecognizeAsync(inkCanvas.InkPresenter.StrokeContainer, InkRecognitionTarget.All); if (recognitionResults.Count > 0) { // Display recognition result string str = "Recognition result:"; foreach (var r in recognitionResults) { str += " " + r.GetTextCandidates()[0]; } rootPage.NotifyUser(str, NotifyType.StatusMessage); } else { rootPage.NotifyUser("No text recognized.", NotifyType.StatusMessage); } RecognizeBtn.IsEnabled = true; ClearBtn.IsEnabled = true; RecoName.IsEnabled = true; } else { rootPage.NotifyUser("Must first write something.", NotifyType.ErrorMessage); } } void OnClear(object sender, RoutedEventArgs e) { inkCanvas.InkPresenter.StrokeContainer.Clear(); rootPage.NotifyUser("Cleared Canvas.", NotifyType.StatusMessage); } bool SetRecognizerByName(string recognizerName) { bool recognizerFound = false; foreach (InkRecognizer reco in recoView) { if (recognizerName == reco.Name) { inkRecognizerContainer.SetDefaultRecognizer(reco); recognizerFound = true; break; } } if (!recognizerFound && rootPage != null) { rootPage.NotifyUser("Could not find target recognizer.", NotifyType.ErrorMessage); } return recognizerFound; } private void TextServiceManager_InputLanguageChanged(CoreTextServicesManager sender, object args) { SetDefaultRecognizerByCurrentInputMethodLanguageTag(); } private void SetDefaultRecognizerByCurrentInputMethodLanguageTag() { // Query recognizer name based on current input method language tag (bcp47 tag) Language currentInputLanguage = textServiceManager.InputLanguage; if (currentInputLanguage != previousInputLanguage) { // try query with the full BCP47 name string recognizerName = RecognizerHelper.LanguageTagToRecognizerName(currentInputLanguage.LanguageTag); if (recognizerName != string.Empty) { for (int index = 0; index < recoView.Count; index++) { if (recoView[index].Name == recognizerName) { inkRecognizerContainer.SetDefaultRecognizer(recoView[index]); RecoName.SelectedIndex = index; previousInputLanguage = currentInputLanguage; break; } } } } } private void RecoButton_Click(object sender, RoutedEventArgs e) { recoTooltip.IsOpen = !recoTooltip.IsOpen; } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Specialized; using gov.va.medora.mdo; using gov.va.medora.mdo.api; using gov.va.medora.mdo.dao; using gov.va.medora.mdws.dto; using System.Configuration; using System.Xml; using System.Reflection; using System.IO; using System.Web; using gov.va.medora.mdws.conf; namespace gov.va.medora.mdws { [Serializable] public class MySession { MdwsConfiguration _mdwsConfig; string _facadeName; SiteTable _siteTable; // set outside class ConnectionSet _cxnSet = new ConnectionSet(); User _user; AbstractCredentials _credentials; string _defaultVisitMethod; public bool _excludeSite200; string _defaultPermissionString; AbstractPermission _primaryPermission; Patient _patient; //public ILog log; public MySession() { _mdwsConfig = new MdwsConfiguration(); _defaultVisitMethod = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_VISIT_METHOD]; _defaultPermissionString = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_CONTEXT]; try { _siteTable = new mdo.SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + _mdwsConfig.FacadeConfiguration.SitesFileName); } catch (Exception) { /* SiteTable is going to be null - how do we let the user know?? */ } } /// <summary> /// Every client application requesting a MDWS session (invokes a function with EnableSession = True attribute) passes /// through this point. Fetches facade configuration settings and sets up session for subsequent calls /// </summary> /// <param name="facadeName">The facade name being invoked (e.g. EmrSvc)</param> /// <exception cref="System.Configuration.ConfigurationErrorsException" /> public MySession(string facadeName) { this._facadeName = facadeName; _mdwsConfig = new MdwsConfiguration(facadeName); _defaultVisitMethod = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_VISIT_METHOD]; _defaultPermissionString = _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.DEFAULT_CONTEXT]; _excludeSite200 = String.Equals("true", _mdwsConfig.AllConfigs[MdwsConfigConstants.MDWS_CONFIG_SECTION][MdwsConfigConstants.EXCLUDE_SITE_200], StringComparison.CurrentCultureIgnoreCase); try { _siteTable = new mdo.SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + _mdwsConfig.FacadeConfiguration.SitesFileName); watchSitesFile(_mdwsConfig.ResourcesPath + "xml\\"); } catch (Exception) { /* SiteTable is going to be null - how do we let the user know?? */ } } /// <summary> /// Allow a client application to specifiy their sites file by name /// </summary> /// <param name="sitesFileName">The name of the sites file</param> /// <returns>SiteArray of parsed sites file</returns> public SiteArray setSites(string sitesFileName) { SiteArray result = new SiteArray(); try { _siteTable = new mdo.SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + sitesFileName); _mdwsConfig.FacadeConfiguration.SitesFileName = sitesFileName; watchSitesFile(_mdwsConfig.ResourcesPath + "xml\\"); result = new SiteArray(_siteTable.Sites); } catch (Exception) { result.fault = new FaultTO("A sites file with that name does not exist on the server!"); } return result; } #region Setters and Getters public MdwsConfiguration MdwsConfiguration { get { return _mdwsConfig; } } public string FacadeName { get { return _facadeName; } } public SiteTable SiteTable { get { return _siteTable; } } public ConnectionSet ConnectionSet { get { return _cxnSet ?? (_cxnSet = new ConnectionSet()); } set { _cxnSet = value; } } public User User { get { return _user; } set { _user = value; } } public Patient Patient { get { return _patient; } set { _patient = value; } } public AbstractCredentials Credentials { get { return _credentials; } set { _credentials = value; } } public string DefaultPermissionString { get { return _defaultPermissionString; } set { _defaultPermissionString = value; } } public AbstractPermission PrimaryPermission { get { return _primaryPermission; } set { _primaryPermission = value; _primaryPermission.IsPrimary = true; } } /// <summary> /// Defaults to MdwsConstants.BSE_CREDENTIALS_V2WEB if configuration key is not found in web.config /// </summary> public string DefaultVisitMethod { get { return String.IsNullOrEmpty(_defaultVisitMethod) ? MdwsConstants.BSE_CREDENTIALS_V2WEB : _defaultVisitMethod; } set { _defaultVisitMethod = value; } } #endregion public Object execute(string className, string methodName, object[] args) { string userIdStr = ""; //if (_user != null) //{ // userIdStr = _user.LogonSiteId.Id + '/' + _user.Uid + ": "; //} string fullClassName = className; if (!fullClassName.StartsWith("gov.")) { fullClassName = "gov.va.medora.mdws." + fullClassName; } Object theLib = Activator.CreateInstance(Type.GetType(fullClassName), new object[] { this }); Type theClass = theLib.GetType(); Type[] theParamTypes = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { theParamTypes[i] = args[i].GetType(); } MethodInfo theMethod = theClass.GetMethod(methodName, theParamTypes); Object result = null; if (theMethod == null) { result = new Exception("Method " + className + " " + methodName + " does not exist."); } try { result = theMethod.Invoke(theLib, BindingFlags.InvokeMethod, null, args, null); } catch (Exception e) { if (e.GetType().IsAssignableFrom(typeof(System.Reflection.TargetInvocationException)) && e.InnerException != null) { result = e.InnerException; } else { result = e; } return result; } return result; } public bool HasBaseConnection { get { if (_cxnSet == null) { return false; } return _cxnSet.HasBaseConnection; } } public void close() { _cxnSet.disconnectAll(); _user = null; _patient = null; } void watchSitesFile(string path) { FileSystemWatcher watcher = new FileSystemWatcher(path); watcher.Filter = (_mdwsConfig.FacadeConfiguration.SitesFileName); watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.Size; watcher.EnableRaisingEvents = true; watcher.Changed += new FileSystemEventHandler(watcher_Changed); watcher.Deleted += new FileSystemEventHandler(watcher_Changed); watcher.Created += new FileSystemEventHandler(watcher_Changed); } void watcher_Changed(object sender, FileSystemEventArgs e) { _siteTable = new SiteTable(_mdwsConfig.ResourcesPath + "xml\\" + _mdwsConfig.FacadeConfiguration.SitesFileName); } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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; namespace Microsoft.DirectX.Direct3D { public struct DeviceCaps { internal uint devcaps; internal uint devcaps2; internal DeviceCaps(uint devcaps, uint devcaps2) { this.devcaps = devcaps; this.devcaps2 = devcaps2; } public bool VertexElementScanSharesStreamOffset { get { return (devcaps2 & 0x40) != 0; } } public bool CanStretchRectangleFromTextures { get { return (devcaps2 & 0x10) != 0; } } public bool SupportsAdaptiveTessellateNPatch { get { return (devcaps2 & 0x8) != 0; } } public bool SupportsAdaptiveTessellateRtPatch { get { return (devcaps2 & 0x4) != 0; } } public bool SupportsDMapNPatch { get { return (devcaps2 & 0x2) != 0; } } public bool SupportsStreamOffset { get { return (devcaps2 & 0x1) != 0; } } public bool SupportsPreSampledDMapNPatch { get { return (devcaps2 & 0x20) != 0; } } public bool SupportsNPatches { get { return (devcaps & 0x1000000) != 0; } } public bool SupportsRtPatchHandleZero { get { return (devcaps & 0x800000) != 0; } } public bool SupportsRtPatches { get { return (devcaps & 0x400000) != 0; } } public bool SupportsQuinticRtPatches { get { return (devcaps & 0x200000) != 0; } } public bool SupportsPureDevice { get { return (devcaps & 0x100000) != 0; } } public bool SupportsHardwareRasterization { get { return (devcaps & 0x80000) != 0; } } public bool CanDrawSystemToNonLocal { get { return (devcaps & 0x20000) != 0; } } public bool SupportsHardwareTransformAndLight { get { return (devcaps & 0x10000) != 0; } } public bool SupportsDrawPrimitives2Ex { get { return (devcaps & 0x8000) != 0; } } public bool SupportsSeparateTextureMemories { get { return (devcaps & 0x4000) != 0; } } public bool SupportsDrawPrimitives2 { get { return (devcaps & 0x2000) != 0; } } public bool SupportsTextureNonLocalVideoMemory { get { return (devcaps & 0x1000) != 0; } } public bool CanRenderAfterFlip { get { return (devcaps & 0x800) != 0; } } public bool SupportsDrawPrimitivesTransformedVertex { get { return (devcaps & 0x400) != 0; } } public bool SupportsTextureVideoMemory { get { return (devcaps & 0x200) != 0; } } public bool SupportsTextureSystemMemory { get { return (devcaps & 0x100) != 0; } } public bool SupportsTransformedVertexVideoMemory { get { return (devcaps & 0x80) != 0; } } public bool SupportsTransformedVertexSystemMemory { get { return (devcaps & 0x40) != 0; } } public bool SupportsExecuteVideoMemory { get { return (devcaps & 0x20) != 0; } } public bool SupportsExecuteSystemMemory { get { return (devcaps & 0x10) != 0; } } public override string ToString () { throw new NotImplementedException (); } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Windows.Forms; using NUnit.Core; using NUnit.Util; namespace NUnit.UiKit { /// <summary> /// FileHandler does all file opening and closing that /// involves interacting with the user. /// </summary> public class TestLoaderUI { private static bool VisualStudioSupport { get { return Services.UserSettings.GetSetting( "Options.TestLoader.VisualStudioSupport", false ); } } public static void OpenProject( Form owner ) { OpenFileDialog dlg = new OpenFileDialog(); System.ComponentModel.ISite site = owner == null ? null : owner.Site; if ( site != null ) dlg.Site = site; dlg.Title = "Open Project"; if ( VisualStudioSupport ) { dlg.Filter = "Projects & Assemblies(*.nunit,*.csproj,*.vbproj,*.vjsproj, *.vcproj,*.sln,*.dll,*.exe )|*.nunit;*.csproj;*.vjsproj;*.vbproj;*.vcproj;*.sln;*.dll;*.exe|" + "All Project Types (*.nunit,*.csproj,*.vbproj,*.vjsproj,*.vcproj,*.sln)|*.nunit;*.csproj;*.vjsproj;*.vbproj;*.vcproj;*.sln|" + "Test Projects (*.nunit)|*.nunit|" + "Solutions (*.sln)|*.sln|" + "C# Projects (*.csproj)|*.csproj|" + "J# Projects (*.vjsproj)|*.vjsproj|" + "VB Projects (*.vbproj)|*.vbproj|" + "C++ Projects (*.vcproj)|*.vcproj|" + "Assemblies (*.dll,*.exe)|*.dll;*.exe"; } else { dlg.Filter = "Projects & Assemblies(*.nunit,*.dll,*.exe)|*.nunit;*.dll;*.exe|" + "Test Projects (*.nunit)|*.nunit|" + "Assemblies (*.dll,*.exe)|*.dll;*.exe"; } dlg.FilterIndex = 1; dlg.FileName = ""; if ( dlg.ShowDialog( owner ) == DialogResult.OK ) OpenProject( owner, dlg.FileName ); } public static void OpenProject( Form owner, string testFileName, string configName, string testName ) { TestLoader loader = Services.TestLoader; if ( loader.IsProjectLoaded && SaveProjectIfDirty( owner ) == DialogResult.Cancel ) return; loader.LoadProject( testFileName, configName ); if ( loader.IsProjectLoaded ) { NUnitProject testProject = loader.TestProject; if ( testProject.Configs.Count == 0 ) UserMessage.DisplayInfo( "Loaded project contains no configuration data" ); else if ( testProject.ActiveConfig == null ) UserMessage.DisplayInfo( "Loaded project has no active configuration" ); else if ( testProject.ActiveConfig.Assemblies.Count == 0 ) UserMessage.DisplayInfo( "Active configuration contains no assemblies" ); else loader.LoadTest( testName ); } } public static void OpenProject( Form owner, string testFileName ) { OpenProject( owner, testFileName, null, null ); } // public static void OpenResults( Form owner ) // { // TestLoader loader = Services.TestLoader; // // OpenFileDialog dlg = new OpenFileDialog(); // System.ComponentModel.ISite site = owner == null ? null : owner.Site; // if ( site != null ) dlg.Site = site; // dlg.Title = "Open Test Results"; // // dlg.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*"; // dlg.FilterIndex = 1; // dlg.FileName = ""; // // if ( dlg.ShowDialog( owner ) == DialogResult.OK ) // OpenProject( owner, dlg.FileName ); // } public static void AddToProject( Form owner ) { AddToProject( owner, null ); } public static void AddToProject( Form owner, string configName ) { TestLoader loader = Services.TestLoader; ProjectConfig config = configName == null ? loader.TestProject.ActiveConfig : loader.TestProject.Configs[configName]; OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Add Assemblies To Project"; dlg.InitialDirectory = config.BasePath; if ( VisualStudioSupport ) dlg.Filter = "Projects & Assemblies(*.csproj,*.vbproj,*.vjsproj, *.vcproj,*.dll,*.exe )|*.csproj;*.vjsproj;*.vbproj;*.vcproj;*.dll;*.exe|" + "Visual Studio Projects (*.csproj,*.vjsproj,*.vbproj,*.vcproj)|*.csproj;*.vjsproj;*.vbproj;*.vcproj|" + "C# Projects (*.csproj)|*.csproj|" + "J# Projects (*.vjsproj)|*.vjsproj|" + "VB Projects (*.vbproj)|*.vbproj|" + "C++ Projects (*.vcproj)|*.vcproj|" + "Assemblies (*.dll,*.exe)|*.dll;*.exe"; else dlg.Filter = "Assemblies (*.dll,*.exe)|*.dll;*.exe"; dlg.FilterIndex = 1; dlg.FileName = ""; if ( dlg.ShowDialog( owner ) != DialogResult.OK ) return; if (PathUtils.IsAssemblyFileType(dlg.FileName)) { config.Assemblies.Add(dlg.FileName); return; } else if (VSProject.IsProjectFile(dlg.FileName)) try { VSProject vsProject = new VSProject(dlg.FileName); MessageBoxButtons buttons; string msg; if (configName != null && vsProject.Configs.Contains(configName)) { msg = "The project being added may contain multiple configurations;\r\r" + "Select\tYes to add all configurations found.\r" + "\tNo to add only the " + configName + " configuration.\r" + "\tCancel to exit without modifying the project."; buttons = MessageBoxButtons.YesNoCancel; } else { msg = "The project being added may contain multiple configurations;\r\r" + "Select\tOK to add all configurations found.\r" + "\tCancel to exit without modifying the project."; buttons = MessageBoxButtons.OKCancel; } DialogResult result = UserMessage.Ask(msg, buttons); if (result == DialogResult.Yes || result == DialogResult.OK) { loader.TestProject.Add(vsProject); return; } else if (result == DialogResult.No) { foreach (string assembly in vsProject.Configs[configName].Assemblies) config.Assemblies.Add(assembly); return; } } catch (Exception ex) { UserMessage.DisplayFailure(ex.Message, "Invalid VS Project"); } } public static void AddAssembly( Form owner ) { AddAssembly( owner, null ); } public static void AddAssembly( Form owner, string configName ) { TestLoader loader = Services.TestLoader; ProjectConfig config = configName == null ? loader.TestProject.ActiveConfig : loader.TestProject.Configs[configName]; OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Add Assembly"; dlg.InitialDirectory = config.BasePath; dlg.Filter = "Assemblies (*.dll,*.exe)|*.dll;*.exe"; dlg.FilterIndex = 1; dlg.FileName = ""; if (dlg.ShowDialog(owner) == DialogResult.OK) config.Assemblies.Add(dlg.FileName); } public static void AddVSProject( Form owner ) { TestLoader loader = Services.TestLoader; OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Add Visual Studio Project"; dlg.Filter = "All Project Types (*.csproj,*.vjsproj,*.vbproj,*.vcproj)|*.csproj;*.vjsproj;*.vbproj;*.vcproj|" + "C# Projects (*.csproj)|*.csproj|" + "J# Projects (*.vjsproj)|*.vjsproj|" + "VB Projects (*.vbproj)|*.vbproj|" + "C++ Projects (*.vcproj)|*.vcproj|" + "All Files (*.*)|*.*"; dlg.FilterIndex = 1; dlg.FileName = ""; if ( dlg.ShowDialog( owner ) == DialogResult.OK ) { try { VSProject vsProject = new VSProject( dlg.FileName ); loader.TestProject.Add( vsProject ); } catch( Exception ex ) { UserMessage.DisplayFailure( ex.Message, "Invalid VS Project" ); } } } private static bool CanWriteProjectFile( string path ) { return !File.Exists( path ) || ( File.GetAttributes( path ) & FileAttributes.ReadOnly ) == 0; } public static void SaveProject( Form owner ) { TestLoader loader = Services.TestLoader; if ( Path.IsPathRooted( loader.TestProject.ProjectPath ) && NUnitProject.IsNUnitProjectFile( loader.TestProject.ProjectPath ) && CanWriteProjectFile( loader.TestProject.ProjectPath ) ) loader.TestProject.Save(); else SaveProjectAs( owner ); } public static void SaveProjectAs( Form owner ) { TestLoader loader = Services.TestLoader; SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "Save Test Project"; dlg.Filter = "NUnit Test Project (*.nunit)|*.nunit|All Files (*.*)|*.*"; string path = NUnitProject.ProjectPathFromFile( loader.TestProject.ProjectPath ); if ( CanWriteProjectFile( path ) ) dlg.FileName = path; dlg.DefaultExt = "nunit"; dlg.ValidateNames = true; dlg.OverwritePrompt = true; while( dlg.ShowDialog( owner ) == DialogResult.OK ) { if ( !CanWriteProjectFile( dlg.FileName ) ) UserMessage.DisplayInfo( string.Format( "File {0} is write-protected. Select another file name.", dlg.FileName ) ); else { loader.TestProject.Save( dlg.FileName ); return; } } } public static void NewProject( Form owner ) { TestLoader loader = Services.TestLoader; SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "New Test Project"; dlg.Filter = "NUnit Test Project (*.nunit)|*.nunit|All Files (*.*)|*.*"; dlg.FileName = Services.ProjectService.GenerateProjectName(); dlg.DefaultExt = "nunit"; dlg.ValidateNames = true; dlg.OverwritePrompt = true; if ( dlg.ShowDialog( owner ) == DialogResult.OK ) loader.NewProject( dlg.FileName ); } public static DialogResult CloseProject( Form owner ) { DialogResult result = SaveProjectIfDirty( owner ); if( result != DialogResult.Cancel ) Services.TestLoader.UnloadProject(); return result; } private static DialogResult SaveProjectIfDirty( Form owner ) { DialogResult result = DialogResult.OK; NUnitProject project = Services.TestLoader.TestProject; if( project.IsDirty ) { string msg = string.Format( "Project {0} has been changed. Do you want to save changes?",project.Name); result = UserMessage.Ask( msg, MessageBoxButtons.YesNoCancel ); if ( result == DialogResult.Yes ) SaveProject( owner ); } return result; } public static void SaveLastResult( Form owner ) { //TODO: Save all results TestLoader loader = Services.TestLoader; SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "Save Test Results as XML"; dlg.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*"; dlg.FileName = "TestResult.xml"; dlg.InitialDirectory = Path.GetDirectoryName( loader.TestFileName ); dlg.DefaultExt = "xml"; dlg.ValidateNames = true; dlg.OverwritePrompt = true; if ( dlg.ShowDialog( owner ) == DialogResult.OK ) { try { string fileName = dlg.FileName; loader.SaveLastResult( fileName ); string msg = String.Format( "Results saved as {0}", fileName ); UserMessage.DisplayInfo( msg, "Save Results as XML" ); } catch( Exception exception ) { UserMessage.DisplayFailure( exception, "Unable to Save Results" ); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.MiscellaneousCases { /// <summary> /// Miscellaneous Cases (matches) /// </summary> public static partial class MatchesTests { /// <summary> /// Throw an exception on undefined variables /// child::*[$$abc=1] /// </summary> [Fact] public static void MatchesTest541() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"child::*[$$abc=1]"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Match should throw an exception on expression that dont have a return type of nodeset /// true() and true() /// </summary> [Fact] public static void MatchesTest542() { var xml = "books.xml"; var testExpression = @"true() and true()"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Match should throw an exception on expression that dont have a return type of nodeset /// false() or true() /// </summary> [Fact] public static void MatchesTest543() { var xml = "books.xml"; var testExpression = @"true() and true()"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// 1 and 1 /// </summary> [Fact] public static void MatchesTest544() { var xml = "books.xml"; var testExpression = @"1 and 1"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// 1 /// </summary> [Fact] public static void MatchesTest545() { var xml = "books.xml"; var testExpression = @"1"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// //node()[abc:xyz()] /// </summary> [Fact] public static void MatchesTest546() { var xml = "books.xml"; var testExpression = @"//node()[abc:xyz()]"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// //node()[abc:xyz()] /// </summary> [Fact] public static void MatchesTest547() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"//node()[abc:xyz()]"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("abc", "http://abc.htm"); Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Contains a function fasle(), which is not defined, so it should throw an exception /// descendant::node()/self::node() [self::text() = false() and self::attribute=fasle()] /// </summary> [Fact] public static void MatchesTest548() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"descendant::node()/self::node() [self::text() = false() and self::attribute=fasle()]"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("abc", "http://abc.htm"); Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// No namespace manager provided /// //*[abc()] /// </summary> [Fact] public static void MatchesTest549() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"//*[abc()]"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Namespace manager provided /// //*[abc()] /// </summary> [Fact] public static void MatchesTest5410() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"//*[abc()]"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("abc", "http://abc.htm"); Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Trying several patterns connected with | /// /bookstore | /bookstore//@* | //magazine /// </summary> [Fact] public static void MatchesTest5411() { var xml = "books.xml"; var startingNodePath = "/bookstore/magazine/@frequency"; var testExpression = @"/bookstore | /bookstore//@* | //magazine"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Trying several patterns connected with | /// /bookstore | /bookstore//@* | //magazine | comment() /// </summary> [Fact] public static void MatchesTest5412() { var xml = "books.xml"; var startingNodePath = "//comment()"; var testExpression = @"/bookstore | /bookstore//@* | //magazine | comment()"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Trying several patterns connected with |. Fix test code to move to testexpr node, thus expected=true. /// /bookstore | /bookstore//@* | //magazine | comment() (true) /// </summary> [Fact] public static void MatchesTest5413() { var xml = "books.xml"; var startingNodePath = "//book"; var testExpression = @"/bookstore | /bookstore//@* | //magazine | comment()"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected Error /// /bookstore | /bookstore//@* | //magazine | /// </summary> [Fact] public static void MatchesTest5414() { var xml = "books.xml"; var startingNodePath = "//book"; var testExpression = @"/bookstore | /bookstore//@* | //magazine |"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Newtonsoft.Json { /// <summary> /// Serializes and deserializes objects into and from the JSON format. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON. /// </summary> public class JsonSerializer { #region Properties_binder internal TypeNameHandling _typeNameHandling; internal FormatterAssemblyStyle _typeNameAssemblyFormat; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal SerializationBinder _binder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; /// <summary> /// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization. /// </summary> public virtual event EventHandler<ErrorEventArgs> Error; /// <summary> /// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references. /// </summary> public virtual IReferenceResolver ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) throw new ArgumentNullException("value", "Reference resolver cannot be null."); _referenceResolver = value; } } /// <summary> /// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names. /// </summary> public virtual SerializationBinder Binder { get { return _binder; } set { if (value == null) throw new ArgumentNullException("value", "Serialization binder cannot be null."); _binder = value; } } /// <summary> /// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages. /// </summary> /// <value>The trace writer.</value> public virtual ITraceWriter TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } /// <summary> /// Gets or sets how type name writing and reading is handled by the serializer. /// </summary> public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) throw new ArgumentOutOfRangeException("value"); _typeNameHandling = value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// </summary> /// <value>The type name assembly format.</value> public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) throw new ArgumentOutOfRangeException("value"); _typeNameAssemblyFormat = value; } } /// <summary> /// Gets or sets how object references are preserved by the serializer. /// </summary> public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) throw new ArgumentOutOfRangeException("value"); _preserveReferencesHandling = value; } } /// <summary> /// Get or set how reference loops (e.g. a class referencing itself) is handled. /// </summary> public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) throw new ArgumentOutOfRangeException("value"); _referenceLoopHandling = value; } } /// <summary> /// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. /// </summary> public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) throw new ArgumentOutOfRangeException("value"); _missingMemberHandling = value; } } /// <summary> /// Get or set how null values are handled during serialization and deserialization. /// </summary> public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) throw new ArgumentOutOfRangeException("value"); _nullValueHandling = value; } } /// <summary> /// Get or set how null default are handled during serialization and deserialization. /// </summary> public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) throw new ArgumentOutOfRangeException("value"); _defaultValueHandling = value; } } /// <summary> /// Gets or sets how objects are created during deserialization. /// </summary> /// <value>The object creation handling.</value> public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) throw new ArgumentOutOfRangeException("value"); _objectCreationHandling = value; } } /// <summary> /// Gets or sets how constructors are used during deserialization. /// </summary> /// <value>The constructor handling.</value> public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) throw new ArgumentOutOfRangeException("value"); _constructorHandling = value; } } /// <summary> /// Gets or sets how metadata properties are used during deserialization. /// </summary> /// <value>The metadata properties handling.</value> public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.ReadAhead) throw new ArgumentOutOfRangeException("value"); _metadataPropertyHandling = value; } } /// <summary> /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization. /// </summary> /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value> public virtual JsonConverterCollection Converters { get { if (_converters == null) _converters = new JsonConverterCollection(); return _converters; } } /// <summary> /// Gets or sets the contract resolver used by the serializer when /// serializing .NET objects to JSON and vice versa. /// </summary> public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } /// <summary> /// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods. /// </summary> /// <value>The context.</value> public virtual StreamingContext Context { get { return _context; } set { _context = value; } } /// <summary> /// Indicates how JSON text output is formatted. /// </summary> public virtual Formatting Formatting { get { return _formatting ?? JsonSerializerSettings.DefaultFormatting; } set { _formatting = value; } } /// <summary> /// Get or set how dates are written to JSON text. /// </summary> public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; } set { _dateFormatHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling during serialization and deserialization. /// </summary> public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>, /// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>, /// are written as JSON text. /// </summary> public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling; } set { _floatFormatHandling = value; } } /// <summary> /// Get or set how strings are escaped when writing JSON text. /// </summary> public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling; } set { _stringEscapeHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text. /// </summary> public virtual string DateFormatString { get { return _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString; } set { _dateFormatString = value; _dateFormatStringSet = true; } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) throw new ArgumentException("Value must be positive.", "value"); _maxDepth = value; _maxDepthSet = true; } } /// <summary> /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object. /// </summary> /// <value> /// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>. /// </value> public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent; } set { _checkAdditionalContent = value; } } internal bool IsCheckAdditionalContentSet() { return (_checkAdditionalContent != null); } #endregion /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling; _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling; _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling; _metadataPropertyHandling = JsonSerializerSettings.DefaultMetadataPropertyHandling; _context = JsonSerializerSettings.DefaultContext; _binder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings. /// </returns> public static JsonSerializer Create() { return new JsonSerializer(); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings. /// </returns> public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); if (settings != null) ApplySerializerSettings(serializer, settings); return serializer; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues Func<JsonSerializerSettings> defaultSettingsCreator = JsonConvert.DefaultSettings; JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; return Create(defaultSettings); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings. /// </returns> public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) ApplySerializerSettings(serializer, settings); return serializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { // insert settings converters at the beginning so they take precedence // if user wants to remove one of the default converters they will have to do it manually for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } // serializer specific if (settings._typeNameHandling != null) serializer.TypeNameHandling = settings.TypeNameHandling; if (settings._metadataPropertyHandling != null) serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; if (settings._typeNameAssemblyFormat != null) serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; if (settings._preserveReferencesHandling != null) serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; if (settings._referenceLoopHandling != null) serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; if (settings._missingMemberHandling != null) serializer.MissingMemberHandling = settings.MissingMemberHandling; if (settings._objectCreationHandling != null) serializer.ObjectCreationHandling = settings.ObjectCreationHandling; if (settings._nullValueHandling != null) serializer.NullValueHandling = settings.NullValueHandling; if (settings._defaultValueHandling != null) serializer.DefaultValueHandling = settings.DefaultValueHandling; if (settings._constructorHandling != null) serializer.ConstructorHandling = settings.ConstructorHandling; if (settings._context != null) serializer.Context = settings.Context; if (settings._checkAdditionalContent != null) serializer._checkAdditionalContent = settings._checkAdditionalContent; if (settings.Error != null) serializer.Error += settings.Error; if (settings.ContractResolver != null) serializer.ContractResolver = settings.ContractResolver; if (settings.ReferenceResolver != null) serializer.ReferenceResolver = settings.ReferenceResolver; if (settings.TraceWriter != null) serializer.TraceWriter = settings.TraceWriter; if (settings.Binder != null) serializer.Binder = settings.Binder; // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) serializer._formatting = settings._formatting; if (settings._dateFormatHandling != null) serializer._dateFormatHandling = settings._dateFormatHandling; if (settings._dateTimeZoneHandling != null) serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; if (settings._dateParseHandling != null) serializer._dateParseHandling = settings._dateParseHandling; if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) serializer._floatFormatHandling = settings._floatFormatHandling; if (settings._floatParseHandling != null) serializer._floatParseHandling = settings._floatParseHandling; if (settings._stringEscapeHandling != null) serializer._stringEscapeHandling = settings._stringEscapeHandling; if (settings._culture != null) serializer._culture = settings._culture; if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); serializerReader.Populate(reader, target); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param> /// <returns>The <see cref="Object"/> being deserialized.</returns> public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="StringReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="TextReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns> public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } /// <summary> /// Deserializes the Json structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); // set serialization options onto reader CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.Value; } DateParseHandling? previousDateParseHandling = null; if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.Value; } FloatParseHandling? previousFloatParseHandling = null; if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.Value; } int? previousMaxDepth = null; if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } string previousDateFormatString = null; if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) TraceWriter.Trace(TraceLevel.Verbose, "Deserialized JSON: " + Environment.NewLine + traceJsonReader.GetJson(), null); // reset reader back to previous options if (previousCulture != null) reader.Culture = previousCulture; if (previousDateTimeZoneHandling != null) reader.DateTimeZoneHandling = previousDateTimeZoneHandling.Value; if (previousDateParseHandling != null) reader.DateParseHandling = previousDateParseHandling.Value; if (previousFloatParseHandling != null) reader.FloatParseHandling = previousFloatParseHandling.Value; if (_maxDepthSet) reader.MaxDepth = previousMaxDepth; if (_dateFormatStringSet) reader.DateFormatString = previousDateFormatString; return value; } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the Json structure /// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); // set serialization options onto writer Formatting? previousFormatting = null; if (_formatting != null && jsonWriter.Formatting != _formatting) { previousFormatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.Value; } DateFormatHandling? previousDateFormatHandling = null; if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling) { previousDateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.Value; } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.Value; } FloatFormatHandling? previousFloatFormatHandling = null; if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling) { previousFloatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.Value; } StringEscapeHandling? previousStringEscapeHandling = null; if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { previousStringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.Value; } CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } string previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this); serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) TraceWriter.Trace(TraceLevel.Verbose, "Serialized JSON: " + Environment.NewLine + traceJsonWriter.GetJson(), null); // reset writer back to previous options if (previousFormatting != null) jsonWriter.Formatting = previousFormatting.Value; if (previousDateFormatHandling != null) jsonWriter.DateFormatHandling = previousDateFormatHandling.Value; if (previousDateTimeZoneHandling != null) jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.Value; if (previousFloatFormatHandling != null) jsonWriter.FloatFormatHandling = previousFloatFormatHandling.Value; if (previousStringEscapeHandling != null) jsonWriter.StringEscapeHandling = previousStringEscapeHandling.Value; if (_dateFormatStringSet) jsonWriter.DateFormatString = previousDateFormatString; if (previousCulture != null) jsonWriter.Culture = previousCulture; } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) _referenceResolver = new DefaultReferenceResolver(); return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, "objectType"); #endif if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) return converter; } } return null; } internal void OnError(ErrorEventArgs e) { EventHandler<ErrorEventArgs> error = Error; if (error != null) error(this, e); } } }
using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using log4net; namespace Command { /// <summary> /// Provides a registry of discovered Commands and Factories, as well as /// methods for discovering them. /// </summary> public class Registry { // Reference to class logger protected static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Dictionary of command instances keyed by command name private Dictionary<string, Command> _commands; // Dictionary of types to factory constructors/methods/properties private Dictionary<Type, Factory> _factories; /// Dictionary of class types to settings that instances of the class hold private Dictionary<Type, List<SettingAttribute>> _settings; // Dictionary of types to alternate factories protected List<Factory> _alternates; /// Return the Command object corresponding to the requested name. public Command this[string cmdName] { get { if(_commands.ContainsKey(cmdName)) { return _commands[cmdName]; } else { throw new KeyNotFoundException(string.Format( "No command named '{0}' has been registered", cmdName)); } } } /// Property for accessing the TypeConverter public ITypeConverter TypeConverter { get; set; } /// Constructor public Registry() { _commands = new Dictionary<string, Command>(StringComparer.OrdinalIgnoreCase); _factories = new Dictionary<Type, Factory>(); _settings = new Dictionary<Type, List<SettingAttribute>>(); _alternates = new List<Factory>(); TypeConverter = new PluggableTypeConverter(); } /// <summary> /// Registers commands (i.e. methods tagged with the Command attribute) /// in the current assembly. /// </summary> public void RegisterNamespace(string ns) { RegisterNamespace(Assembly.GetExecutingAssembly(), ns); } /// <summary> /// Registers commands from the supplied assembly. Commands methods must /// be tagged with the attribute Command to be locatable. /// </summary> public void RegisterNamespace(Assembly asm, string ns) { _log.TraceFormat("Searching for commands under namespace '{0}'...", ns); var cmdCount = _commands.Count; var factCount = _factories.Count; foreach(var t in asm.GetExportedTypes()) { if(t.Namespace == ns && t.IsClass) { RegisterClass(t); } } _log.TraceFormat("Found {0} commands and {1} factories under namespace {2}", _commands.Count - cmdCount, _factories.Count - factCount, ns); } /// <summary> /// Registers commands and factories from the supplied class. /// Commands must be tagged with the attribute Command to be locatable. /// </summary> public void RegisterClass(Type t) { Factory factory; Command cmd; if(t.IsClass) { // Process class level attributes List<SettingAttribute> settings = new List<SettingAttribute>(); foreach(var attr in t.GetCustomAttributes(typeof(SettingAttribute), false)) { if(attr is DynamicSettingAttribute) { // Verify that DynamicSettingAttributes are only used on IDynamicSettingsCollection if(t.GetInterface("IDynamicSettingsCollection") == null) { throw new ArgumentException(string.Format("A DynamicSettingAttribute has " + "been defined on class {0}, but this class does not implement " + "the IDynamicSettingsCollection interface", t.Name)); } } settings.Add((SettingAttribute)attr); } // Attributes are returned in random order, so sort by preferred order settings.Sort((a, b) => (a.SortKey).CompareTo(b.SortKey)); _settings[t] = settings; // Process members of class foreach(var mi in t.GetMembers(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly)) { cmd = null; factory = null; foreach(var attr in mi.GetCustomAttributes(false)) { if(attr is CommandAttribute) { cmd = new Command(t, mi as MethodInfo, attr as CommandAttribute); Add(cmd); } if(attr is FactoryAttribute) { factory = new Factory(mi, attr as FactoryAttribute); Add(factory); } } if(cmd != null && factory != null) { cmd._factory = factory; factory._command = cmd; } } } } /// <summary> /// Registers the specified Command instance. /// </summary> public void Add(Command cmd) { if(_commands.ContainsKey(cmd.Name)) { throw new ArgumentException(string.Format("A command has already been " + "registered with the name {0} (in class {1})", cmd.Name, cmd.Type)); } _commands.Add(cmd.Name, cmd); if(cmd.Alias != null) { if(!_commands.ContainsKey(cmd.Alias)) { _commands.Add(cmd.Alias, cmd); } else { _log.WarnFormat("Attempt to register command {0} under alias {1} failed; " + "alias is already registered", cmd.Name, cmd.Alias); } } } /// <summary> /// Registers the specified Factory instance as an alternate mechanism /// for obtaining objects of the Factory return type. An alternate means /// will be tried when no other non-alternate path to create an object /// can be found from the current context state. /// </summary> public void Add(Factory factory) { if(factory.IsAlternate) { _alternates.Add(factory); } else { if(_factories.ContainsKey(factory.ReturnType)) { throw new ArgumentException(string.Format("A factory has already been " + "registered for {0} objects", factory.ReturnType)); } _factories.Add(factory.ReturnType, factory); } } /// <summary> /// Checks to see if a command with the given name is available. /// </summary> public bool Contains(string cmdName) { return _commands.ContainsKey(cmdName); } /// <summary> /// Checks to see if a Factory for the specified type is available. /// </summary> public bool Contains(Type type) { return _factories.ContainsKey(type); } /// <summary> /// Returns the Factory instance for objects of the specified Type. /// </summary> public Factory GetFactory(Type type) { return _factories[type]; } /// <summary> /// Returns each Command that is currently registered. /// </summary> public IEnumerable<Command> Commands() { return _commands.Values.Distinct().OrderBy(c => c.Name); } /// <summary> /// Returns a list of the settings an ISettingsCollection instance /// holds. /// </summary> public List<SettingAttribute> GetSettings(Type type) { return _settings[type]; } /// <summary> /// Returns an IEnumerable of the alternate Factory objects registered /// for the specified type. /// </summary> public IEnumerable<Factory> GetAlternates(Type type) { return _alternates.Where(f => f.ReturnType == type); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using Umbraco.Core.Logging; using Umbraco.Core.Models; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.web; using umbraco.interfaces; using Umbraco.Core; using Media = umbraco.cms.businesslogic.media.Media; using Property = umbraco.cms.businesslogic.property.Property; namespace umbraco.cms.presentation.Trees { public abstract class BaseMediaTree : BaseTree { private User _user; public BaseMediaTree(string application) : base(application) { } /// <summary> /// Returns the current User. This ensures that we don't instantiate a new User object /// each time. /// </summary> protected User CurrentUser { get { return (_user == null ? (_user = UmbracoEnsuredPage.CurrentUser) : _user); } } public override void RenderJS(ref StringBuilder Javascript) { if (!string.IsNullOrEmpty(this.FunctionToCall)) { Javascript.Append("function openMedia(id) {\n"); Javascript.Append(this.FunctionToCall + "(id);\n"); Javascript.Append("}\n"); } else if (!this.IsDialog) { Javascript.Append( @" function openMedia(id) { " + ClientTools.Scripts.GetContentFrame() + ".location.href = 'editMedia.aspx?id=' + id;" + @" } "); } } public override void Render(ref XmlTree tree) { if (UseOptimizedRendering == false) { //We cannot run optimized mode since there are subscribers to events/methods that require document instances // so we'll render the original way by looking up the docs. var docs = new Media(m_id).Children; var args = new TreeEventArgs(tree); OnBeforeTreeRender(docs, args); foreach (var dd in docs) { var e = dd; var xNode = PerformNodeRender(e.Id, e.Text, e.HasChildren, e.ContentType.IconUrl, e.ContentType.Alias, () => GetLinkValue(e, e.Id.ToString(CultureInfo.InvariantCulture))); OnBeforeNodeRender(ref tree, ref xNode, EventArgs.Empty); if (xNode != null) { tree.Add(xNode); OnAfterNodeRender(ref tree, ref xNode, EventArgs.Empty); } } OnAfterTreeRender(docs, args); } else { //We ARE running in optmized mode, this means we will NOT be raising the BeforeTreeRender or AfterTreeRender // events - we've already detected that there are not subscribers or implementations // to call so that is fine. var entities = Services.EntityService.GetChildren(m_id, UmbracoObjectTypes.Media).ToArray(); foreach (UmbracoEntity entity in entities) { var e = entity; var xNode = PerformNodeRender(e.Id, entity.Name, e.HasChildren, e.ContentTypeIcon, e.ContentTypeAlias, () => GetLinkValue(e)); OnBeforeNodeRender(ref tree, ref xNode, EventArgs.Empty); if (xNode != null) { tree.Add(xNode); OnAfterNodeRender(ref tree, ref xNode, EventArgs.Empty); } } } } private XmlTreeNode PerformNodeRender(int nodeId, string nodeName, bool hasChildren, string icon, string contentTypeAlias, Func<string> getLinkValue) { var xNode = XmlTreeNode.Create(this); xNode.NodeID = nodeId.ToString(CultureInfo.InvariantCulture); xNode.Text = nodeName; xNode.HasChildren = hasChildren; xNode.Source = this.IsDialog ? GetTreeDialogUrl(nodeId) : GetTreeServiceUrl(nodeId); xNode.Icon = icon; xNode.OpenIcon = icon; if (IsDialog == false) { if (this.ShowContextMenu == false) xNode.Menu = null; xNode.Action = "javascript:openMedia(" + nodeId + ");"; } else { xNode.Menu = this.ShowContextMenu ? new List<IAction>(new IAction[] { ActionRefresh.Instance }) : null; if (this.DialogMode == TreeDialogModes.fulllink) { string nodeLink = getLinkValue(); if (string.IsNullOrEmpty(nodeLink) == false) { xNode.Action = "javascript:openMedia('" + nodeLink + "');"; } else { if (string.Equals(contentTypeAlias, Constants.Conventions.MediaTypes.Folder, StringComparison.OrdinalIgnoreCase)) { //#U4-2254 - Inspiration to use void from here: http://stackoverflow.com/questions/4924383/jquery-object-object-error xNode.Action = "javascript:void jQuery('.umbTree #" + nodeId.ToString(CultureInfo.InvariantCulture) + "').click();"; } else { xNode.Action = null; xNode.Style.DimNode(); } } } else { xNode.Action = "javascript:openMedia('" + nodeId.ToString(CultureInfo.InvariantCulture) + "');"; } } return xNode; } /// <summary> /// Returns the value for a link in WYSIWYG mode, by default only media items that have a /// DataTypeUploadField are linkable, however, a custom tree can be created which overrides /// this method, or another GUID for a custom data type can be added to the LinkableMediaDataTypes /// list on application startup. /// </summary> /// <param name="dd"></param> /// <param name="nodeLink"></param> /// <returns></returns> public virtual string GetLinkValue(Media dd, string nodeLink) { var props = dd.GenericProperties; foreach (Property p in props) { Guid currId = p.PropertyType.DataTypeDefinition.DataType.Id; if (LinkableMediaDataTypes.Contains(currId) && string.IsNullOrEmpty(p.Value.ToString()) == false) { return p.Value.ToString(); } } return ""; } /// <summary> /// NOTE: New implementation of the legacy GetLinkValue. This is however a bit quirky as a media item can have multiple "Linkable DataTypes". /// Returns the value for a link in WYSIWYG mode, by default only media items that have a /// DataTypeUploadField are linkable, however, a custom tree can be created which overrides /// this method, or another GUID for a custom data type can be added to the LinkableMediaDataTypes /// list on application startup. /// </summary> /// <param name="entity"></param> /// <returns></returns> internal virtual string GetLinkValue(UmbracoEntity entity) { foreach (var property in entity.UmbracoProperties) { if (LinkableMediaDataTypes.Contains(property.DataTypeControlId) && string.IsNullOrEmpty(property.Value) == false) return property.Value; } return ""; } /// <summary> /// By default, any media type that is to be "linkable" in the WYSIWYG editor must contain /// a DataTypeUploadField data type which will ouput the value for the link, however, if /// a developer wants the WYSIWYG editor to link to a custom media type, they will either have /// to create their own media tree and inherit from this one and override the GetLinkValue /// or add another GUID to the LinkableMediaDataType list on application startup that matches /// the GUID of a custom data type. The order of property types on the media item definition will determine the output value. /// </summary> public static List<Guid> LinkableMediaDataTypes { get; protected set; } /// <summary> /// Returns true if we can use the EntityService to render the tree or revert to the original way /// using normal documents /// </summary> /// <remarks> /// We determine this by: /// * If there are any subscribers to the events: BeforeTreeRender or AfterTreeRender - then we cannot run optimized /// </remarks> internal bool UseOptimizedRendering { get { if (HasEntityBasedEventSubscribers) { return false; } return true; } } } }
using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Text.RegularExpressions; using NLua; using Oxide.Core; using Oxide.Core.Plugins; using Oxide.Core.Plugins.Watchers; using Oxide.Core.Libraries.Covalence; namespace Oxide.Ext.Lua.Plugins { /// <summary> /// Represents a Lua plugin /// </summary> public class LuaPlugin : Plugin { /// <summary> /// Gets the Lua environment /// </summary> internal NLua.Lua LuaEnvironment { get; } /// <summary> /// Gets this plugin's Lua table /// </summary> private LuaTable Table { get; set; } /// <summary> /// Gets the object associated with this plugin /// </summary> public override object Object => Table; // All functions in this plugin private IDictionary<string, LuaFunction> functions; // The plugin change watcher private FSWatcher watcher; // The Lua extension private LuaExtension luaExt; /// <summary> /// Initializes a new instance of the LuaPlugin class /// </summary> /// <param name="filename"></param> internal LuaPlugin(string filename, LuaExtension luaExt, FSWatcher watcher) { // Store filename Filename = filename; this.luaExt = luaExt; LuaEnvironment = luaExt.LuaEnvironment; this.watcher = watcher; } #region Config /// <summary> /// Populates the config with default settings /// </summary> protected override void LoadDefaultConfig() { LuaEnvironment.NewTable("tmp"); LuaTable tmp = LuaEnvironment["tmp"] as LuaTable; Table["Config"] = tmp; LuaEnvironment["tmp"] = null; CallHook("LoadDefaultConfig", null); Utility.SetConfigFromTable(Config, tmp); } /// <summary> /// Loads the config file for this plugin /// </summary> protected override void LoadConfig() { base.LoadConfig(); if (Table != null) { Table["Config"] = Utility.TableFromConfig(Config, LuaEnvironment); } } /// <summary> /// Saves the config file for this plugin /// </summary> protected override void SaveConfig() { if (Config == null) return; if (Table == null) return; LuaTable configtable = Table["Config"] as LuaTable; if (configtable != null) { Utility.SetConfigFromTable(Config, configtable); } base.SaveConfig(); } #endregion /// <summary> /// Loads this plugin /// </summary> public void Load() { // Load the plugin into a table var source = File.ReadAllText(Filename); if (Regex.IsMatch(source, @"PLUGIN\.Version\s*=\s*[\'|""]", RegexOptions.IgnoreCase)) throw new Exception("Plugin version is a string, Oxide 1.18 plugins are not compatible with Oxide 2"); var pluginfunc = LuaEnvironment.LoadString(source, Path.GetFileName(Filename)); if (pluginfunc == null) throw new Exception("LoadString returned null for some reason"); LuaEnvironment.NewTable("PLUGIN"); Table = (LuaTable) LuaEnvironment["PLUGIN"]; ((LuaFunction) LuaEnvironment["setmetatable"]).Call(Table, luaExt.PluginMetatable); Name = Path.GetFileNameWithoutExtension(Filename); Table["Name"] = Name; pluginfunc.Call(); // Read plugin attributes if (!(Table["Title"] is string)) throw new Exception("Plugin is missing title"); if (!(Table["Author"] is string)) throw new Exception("Plugin is missing author"); if (!(Table["Version"] is VersionNumber)) throw new Exception("Plugin is missing version"); Title = (string)Table["Title"]; Author = (string)Table["Author"]; Version = (VersionNumber)Table["Version"]; if (Table["Description"] is string) Description = (string)Table["Description"]; if (Table["ResourceId"] is double) ResourceId = (int)(double)Table["ResourceId"]; if (Table["HasConfig"] is bool) HasConfig = (bool)Table["HasConfig"]; // Set attributes Table["Object"] = this; Table["Plugin"] = this; // Get all functions and hook them functions = new Dictionary<string, LuaFunction>(); foreach (var keyobj in Table.Keys) { string key = keyobj as string; if (key != null) { object value = Table[key]; LuaFunction func = value as LuaFunction; if (func != null) { functions.Add(key, func); } } } if (!HasConfig) HasConfig = functions.ContainsKey("LoadDefaultConfig"); // Bind any base methods (we do it here because we don't want them to be hooked) BindBaseMethods(); // Deal with any attributes LuaTable attribs = Table["_attribArr"] as LuaTable; if (attribs != null) { int i = 0; while (attribs[++i] != null) { LuaTable attrib = attribs[i] as LuaTable; string attribName = attrib["_attribName"] as string; LuaFunction attribFunc = attrib["_func"] as LuaFunction; if (attribFunc != null && !string.IsNullOrEmpty(attribName)) { HandleAttribute(attribName, attribFunc, attrib); } } } // Clean up LuaEnvironment["PLUGIN"] = null; } /// <summary> /// Handles a method attribute /// </summary> /// <param name="name"></param> /// <param name="method"></param> /// <param name="data"></param> private void HandleAttribute(string name, LuaFunction method, LuaTable data) { // What type of attribute is it? switch (name) { case "Command": // Parse data out of it List<string> cmdNames = new List<string>(); int i = 0; while (data[++i] != null) cmdNames.Add(data[i] as string); string[] cmdNamesArr = cmdNames.Where((s) => !string.IsNullOrEmpty(s)).ToArray(); string[] cmdPermsArr; if (data["permission"] is string) { cmdPermsArr = new string[] { data["permission"] as string }; } else if (data["permission"] is LuaTable || data["permissions"] is LuaTable) { LuaTable permsTable = (data["permission"] as LuaTable) ?? (data["permissions"] as LuaTable); List<string> cmdPerms = new List<string>(); i = 0; while (permsTable[++i] != null) cmdPerms.Add(permsTable[i] as string); cmdPermsArr = cmdPerms.Where((s) => !string.IsNullOrEmpty(s)).ToArray(); } else cmdPermsArr = new string[0]; // Register it AddCovalenceCommand(cmdNamesArr, cmdPermsArr, (cmd, type, caller, args) => { HandleCommandCallback(method, cmd, type, caller, args); return true; }); break; } } private void HandleCommandCallback(LuaFunction func, string cmd, CommandType type, IPlayer caller, string[] args) { LuaEnvironment.NewTable("tmp"); LuaTable argsTable = LuaEnvironment["tmp"] as LuaTable; LuaEnvironment["tmp"] = null; for (int i = 0; i < args.Length; i++) { argsTable[i + 1] = args[i]; } try { func.Call(Table, caller, argsTable); } catch (Exception) { // TODO: Error handling and stuff throw; } } /// <summary> /// Binds base methods to the PLUGIN table /// </summary> private void BindBaseMethods() { BindBaseMethod("lua_SaveConfig", "SaveConfig"); } /// <summary> /// Binds the specified base method to the PLUGIN table /// </summary> /// <param name="methodname"></param> /// <param name="luaname"></param> private void BindBaseMethod(string methodname, string luaname) { MethodInfo method = GetType().GetMethod(methodname, BindingFlags.Static | BindingFlags.NonPublic); LuaEnvironment.RegisterFunction(string.Format("PLUGIN.{0}", luaname), method); } #region Base Methods /// <summary> /// Saves the config file for the specified plugin /// </summary> /// <param name="plugintable"></param> private static void lua_SaveConfig(LuaTable plugintable) { LuaPlugin plugin = plugintable["Object"] as LuaPlugin; if (plugin == null) return; plugin.SaveConfig(); } #endregion /// <summary> /// Called when this plugin has been added to the specified manager /// </summary> /// <param name="manager"></param> public override void HandleAddedToManager(PluginManager manager) { // Call base base.HandleAddedToManager(manager); // Subscribe all our hooks foreach (string key in functions.Keys) Subscribe(key); // Add us to the watcher watcher.AddMapping(Name); // Let the plugin know that it's loading OnCallHook("Init", null); } /// <summary> /// Called when this plugin has been removed from the specified manager /// </summary> /// <param name="manager"></param> public override void HandleRemovedFromManager(PluginManager manager) { // Let plugin know that it's unloading OnCallHook("Unload", null); // Remove us from the watcher watcher.RemoveMapping(Name); // Call base base.HandleRemovedFromManager(manager); Table.Dispose(); LuaEnvironment.DeleteObject(this); LuaEnvironment.DoString("collectgarbage()"); } /// <summary> /// Called when it's time to call a hook /// </summary> /// <param name="hookname"></param> /// <param name="args"></param> /// <returns></returns> protected override object OnCallHook(string hookname, object[] args) { LuaFunction func; if (!functions.TryGetValue(hookname, out func)) return null; try { object[] returnvalues; if (args != null && args.Length > 0) { var realargs = new object[args.Length + 1]; realargs[0] = Table; Array.Copy(args, 0, realargs, 1, args.Length); returnvalues = func.Call(realargs); } else returnvalues = func.Call(Table); if (returnvalues == null || returnvalues.Length == 0) return null; return returnvalues[0]; } catch (TargetInvocationException ex) { throw ex.InnerException; } } } }